0

In Excel 2007-2013 I used Application.OnKey to disable shortcuts

Application.OnKey("{F5}", "")

But in Excel 2016 it provokes crashes of Excel (it explodes later, then I press F5). I suppose it is some bug in new Excel, maybe someday it is going to be fixed, but right now I need a workaround, another way to disable shortcuts. Any suggestions?

Alex Butenko
  • 3,664
  • 3
  • 35
  • 54
  • Try removing the parentheses:`Application.Onkey "{F5}",""` – BruceWayne Feb 03 '16 at 20:06
  • @BruceWayne I cannot, It's C#, but in VB.NET and VBA it is the same - crash, even without parentheses – Alex Butenko Feb 03 '16 at 20:08
  • Try using just a regular key and see if it crashes. I wonder if it's the key `{F5}` or `ÒnKey` generally. – BruceWayne Feb 03 '16 at 20:09
  • @BruceWayne OnKey generally, F5 just for example – Alex Butenko Feb 03 '16 at 20:10
  • Does [this thread](http://stackoverflow.com/questions/10193055/how-to-perform-onkey-event-in-an-excel-add-in-created-with-visual-studio-2010) help at all? Or any of [these](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=vsto%20excel%20application.onkey) results? – BruceWayne Feb 03 '16 at 20:19
  • @BruceWayne I know how to use google search and I'm afraid my question is not about how to use Application.OnKey, but how to avoid it. – Alex Butenko Feb 03 '16 at 20:24
  • Ah! Sorry! I have been searching and can't find a way to stop short cuts. Is there a specific one you want to stop that we can perhaps tackle another way? – BruceWayne Feb 03 '16 at 21:07
  • I have specific five to disable:) Ctrl+F3, F3, F5, Ctrl+F8 and F8. I use them for other purposes in my add-in. – Alex Butenko Feb 03 '16 at 21:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/102520/discussion-between-brucewayne-and-alex-butenko). – BruceWayne Feb 03 '16 at 21:14

1 Answers1

1

I found how to avoid crashes:

First step is to set something else, not empty string in Application.OnKey

Application.OnKey("{F5}", " ")

If you just leave it alone, Excel will show the message about wrong macro name.

I removed this message temporarily setting Application.DisplayAlerts = false when key event happens:

static int HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
    if (nCode < 0) {
        return (int) WinApi.CallNextHookEx(_hookID, nCode, wParam, lParam);
    }
    if (nCode == HC_ACTION) {
        ExcelAddIn.ExcelApp.DisplayAlerts = false;
        ExecuteAsync(() => {
            ExecuteInUIThread(() => {
                OnKeyPress((uint) wParam);
                Application.DisplayAlerts = true;
            });
        });
    }
    return (int) WinApi.CallNextHookEx(_hookID, nCode, wParam, lParam);
}

But after that I found that this bug is fixed already and fix version is goning to be released soon (if not yet).

Alex Butenko
  • 3,664
  • 3
  • 35
  • 54