3

We have a WinForms app with the WebBrowser control on a form (currently compiling it for the classic .NET Framework 4.7.2). We need to suppress or intercept the Alt+Left and Alt+Right keyboard combinations when this WebBrowser control has the input focus to implement our own history navigation. We tried several methods including overwriting of the Control.ProcessCmdKey() for the control or the whole form, but this does not help. How to do what we need in .NET Framework in C# or VB.NET?

TecMan
  • 2,743
  • 2
  • 30
  • 64
  • You can override the Form's `ProcessCmdKey`, then add the condition `if (keyData == (Keys.Alt | Keys.Left)) { // do something }` -- See the example here: [How to set the Style of a HtmlElement at the Mouse position when a Key is pressed](https://stackoverflow.com/a/61318665/7444103) -- You didn't specify a language. – Jimi May 14 '21 at 15:34

1 Answers1

0

While you cannot subscribe to the WebBrowser KeyDown, KeyUp or KeyPress events without getting a runtime error you can subscribe to the WebBrowser.PreviewKeyDown Event to detect the Alt-Left Arrow and Alt-RightArrow key combinations.

If you set the PreviewKeyDownEventArgs.IsInputKey Property to true in the event handler, the WebBrowser Control will not interpret the combination as the WebBrowser.GoBack/WebBrowser.GoFoward commands.

Private Sub WebBrowser1_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles WebBrowser1.PreviewKeyDown
  If e.KeyData = (Keys.Left Or Keys.Alt) OrElse e.KeyData = (Keys.Right Or Keys.Alt) Then
    ' setting IsInputKey = true prevents the Browser for processing 
    ' Alt-Left Arrow and Alt-Right Arrow as history navigation
    e.IsInputKey = True
  End If
End Sub
TnTinMn
  • 11,522
  • 3
  • 18
  • 39
  • Yes, that helps!! It was enough to override `OnPreviewKeyDown()` and do our custom actions for Alt+Left/Right before calling `base.OnPreviewKeyDown(e)` even without setting `e.IsInputKey` to True. I must also mention that the [WebBrowserShortcutsEnabled](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.webbrowser.webbrowsershortcutsenabled) property for our descendant of the WebBrowser control is set to False. – TecMan May 17 '21 at 11:06