Home » excel » c# – SheetBeforeDoubleClick from COM Addin

c# – SheetBeforeDoubleClick from COM Addin

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to write a COM addin for Excel XP in C# that disables double clicking a cell to edit it.

I want to popup a box saying that editing a cell this way is prohibited and then stop all execution.

Looking through the documentation at Microsoft this seems like a very easy task, you create an Application event AppEvents_SheetBeforeDoubleClickEventHandler with the signature func(object sheet, Range Target, ref bool Cancel) and you set Cancel to true so that execution stops.

I have the following:

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
    Excel.Application app = application as Excel.Application;
    app.SheetBeforeDoubleClick += Excel.AppEvents_SheetBeforeDoubleClickEventHandler(beforeDoubleClick);
}

void beforeDoubleClick(object sheet, Excel.Range Target, ref bool Cancel)
{
    MessageBox.Show("Cannot edit cells this way sorry.");
    Cancel = true;
}

The message box is shown, but the cell is then put into edit mode, however, if I have the same thing from VBA it works.

The same thing happens with a VB.NET addin using the following code.

Private WithEvents app As Excel.Application
Public Sub OnConnection(ByVal application As Object, 
                            ByVal connectMode As Extensibility.ext_ConnectMode, 
                            ByVal addInInst As Object, 
                            ByRef custom As System.Array) 
                            Implements Extensibility.IDTExtensibility2.OnConnection
    app = application
End Sub

Sub Worksheet1_BeforeDoubleClick(ByVal obj As Object, 
                                 ByVal Target As Excel.Range, 
                                 ByRef Cancel As Boolean) 
                                 Handles app.SheetBeforeDoubleClick
    MsgBox("Double-clicking in this sheet is not allowed.")
    Cancel = True
End Sub
How to&Answers:

I had no problems executing your code: the ‘Cancel’ prevented the double-click operation.

Some searching turned up the following from MSKB: BUG: Cancel parameter for Office events is ignored in Visual Studio .NET 2003.

This behavior of ignoring the cancel parameter seems to exist for Excel versions 2002 and below when using .NET code created using Visual Studio .NET 2003 (.NET Framework 1.1).

There is a complex work-around given in the article that involves hand-tuning the Interop Assembly. It looks pretty doable, though, if a fair amount of effort.

It would be easier to upgrade to VS 2005 or VS 2008. I compiled my code using VS 2008 targeting .NET 3.5, and ran my code on Excel 2007.

By the way, the user will be able to enter a value by typing within the Formula Bar, executing a Copy-Paste command, or the like. To prevent the user from entering a value you might protect the worksheet instead.