I would like to intercept key presses in CEF, so I can actually implement a few key shortcuts.
I've read in the CEF API docs [1] that in order to listen to KeyPress events it's necessary to implement the interface, or inherit from, ClientKeyHandler
. Then overwrite two methods: OnKeyEvent
and OnPreKeyEvent
. The latter is called before a keypress has reached the user interface.
In any case, I proceeded to change my CEF based browser and overwrite these two methods. Changes are available on this branch [2] (built of top of CefProject).
Once I launch the browser and press whatever keys, I don't see any stderr/stdout output in the console. It seems these methods are never called, which make me wonder whether my understanding on how this is supposed to work is correct.
This is what I've tried so far:
diff --git a/examples/minimal/client_minimal.cc b/examples/minimal/client_minimal.cc
index ca8f7cc..70b527a 100644
--- a/examples/minimal/client_minimal.cc
+++ b/examples/minimal/client_minimal.cc
@@ -31,4 +31,10 @@ void Client::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
return shared::OnBeforeClose(browser);
}
+bool Client::OnPreKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event, bool* is_keyboard_shortcut) {
+ fprintf(stderr, "### Client::OnPreKeyEvent");
+
+ return false;
+}
+
} // namespace minimal
diff --git a/examples/minimal/client_minimal.h b/examples/minimal/client_minimal.h
index 86ed374..445375d 100644
--- a/examples/minimal/client_minimal.h
+++ b/examples/minimal/client_minimal.h
@@ -12,6 +12,7 @@ namespace minimal {
// Minimal implementation of client handlers.
class Client : public CefClient,
public CefDisplayHandler,
+ public CefKeyboardHandler,
public CefLifeSpanHandler {
public:
Client();
@@ -29,6 +30,9 @@ class Client : public CefClient,
bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
+ // CefKeyboardHandler methods:
+ bool OnPreKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event, bool* is_keyboard_shortcut) OVERRIDE;
+
I fixed this issue.
It's necessary to overwrite the method GetKeyboardHandler
and return the object that is now implementing CefKeyboardHandler
, very much like how it works for other handlers (CefDisplayHandler
, CefLifespanHandler
, etc):
--- a/examples/minimal/client_minimal.h
+++ b/examples/minimal/client_minimal.h
@@ -19,6 +19,7 @@ class Client : public CefClient,
// CefClient methods:
CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE { return this; }
+ CefRefPtr<CefKeyboardHandler> GetKeyboardHandler() OVERRIDE { return this; }
CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE { return this; }
// CefDisplayHandler methods: