cefsharp and previewkeydown event not working
Asked Answered
B

2

9

This might be a simple question, but I have a winforms app that is loading a ChromiumWebBrowser control (CefSharp) and I can't figure out how to capture key preview events as they are all being swallowed by the control.

The standard attaching a handler to the PreviewKeyDown event of the browser control isn't working. Is there a known workaround?

Buoy answered 14/4, 2016 at 23:31 Comment(0)
P
9

CEF is run in it's own message loop, so the standard events don't work.

The first an easiest option is to implement IKeyboardHandler, you can check the CefSharp source for a more detailed example (there's one that forwards messages to the parent window if required).

Second run with settings.MultiThreadedMessageLoop = false, and call Cef.DoMessageLoopWork() on application idle, this will integrate CEF into the same message loop as your main application. Again, the source contains examples see https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.WinForms.Example/Program.cs#L63

The third option is to hook into the CEF message loop, see https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.WinForms.Example/ChromeWidgetMessageInterceptor.cs for an example

CEF = Chromium Embedded Framework - CefSharp is just a wrapper.

Pasticcio answered 15/4, 2016 at 1:54 Comment(3)
I tried both options 1 and 3 and while I was able to get the mouse events from the interceptor I wasn't able to capture any keyboard events for some reason. That being said option 1 worked great, thanksBuoy
Option 1 works for me - thanks (chromiumWebBrowser.KeyboardHandler = new MyKeyboardHandler();)Baxie
Full working example on adding KeyboardHandler with Reload (F5) and Devtools (F12) here if someone needs: github.com/cefsharp/CefSharp/discussions/…Witenagemot
C
0

You can get Keyboard events by setting ChromiumWebBrowser.KeyboardHandler to IKeyboardHandler even multiThreadedMessageLoop = true.

You can do it by implementing interface on form:

public partial class WinWebForm : Form, IKeyboardHandler

And then assigning it to webbrowser component:

webBrowser.KeyboardHandler = this;

You need to capture RawKeyDownEvent:

public bool OnKeyEvent(IWebBrowser chromiumWebBrowser, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
    {
        if (type == KeyType.RawKeyDown)
        {

When you are accessing Form inside OnKeyEvent you need to use Form.BeginInvoke to ensure you are accessing Form components on right thread:

this.BeginInvoke(new Action(() => {
                                DoZoom(-0.1);
                            }));
Chardin answered 9/10, 2023 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.