如何在 CEF 中捕获按键?

How to capture a keypress in CEF?

提问人:Diego Pino 提问时间:6/21/2021 更新时间:6/22/2021 访问量:779

问:

我想在 CEF 中拦截按键,这样我就可以实际实现一些按键快捷方式。

我在 CEF API 文档 [1] 中读到,为了监听 KeyPress 事件,有必要实现接口或继承 .然后覆盖两个方法:和 。后者在按键到达用户界面之前被调用。ClientKeyHandlerOnKeyEventOnPreKeyEvent

无论如何,我继续更改基于 CEF 的浏览器并覆盖这两种方法。此分支 [2] 上提供了更改(由 CefProject 构建)。

启动浏览器并按任意键后,我在控制台中看不到任何 stderr/stdout 输出。似乎这些方法从未被调用过,这让我怀疑我对这应该如何工作的理解是否正确。

这是我到目前为止尝试过的:

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;
+
  • CEF 版本:87.1.12+g03f9336+chromium-87.0.4280.88
  • 操作系统: Ubuntu 21.04

[1] https://magpcss.org/ceforum/apidocs3/projects/(默认)/CefKeyboardHandler.html#OnPreKeyEvent(CefRefPtr%3CCefBrowser%3E,constCefKeyEvent&,CefEventHandle,bool*))

[2] https://github.com/dpino/cef-project/tree/onkeypress

C++ Chromium Chromium 嵌入式

评论


答:

0赞 Diego Pino 6/22/2021 #1

我解决了这个问题。

有必要覆盖该方法并返回现在正在实现的对象,非常类似于它对其他处理程序(、等)的工作方式:GetKeyboardHandlerCefKeyboardHandlerCefDisplayHandlerCefLifespanHandler

--- 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: