CEF 右键添加开发者选项菜单项

时间:2024-01-01 17:12:45

在项目开发过程中,有时候需要进行调试测试,然后我们可以在cef上下文菜单中添加自定义开发者工具菜单项,这样会比较方便,最后效果:

CEF 右键添加开发者选项菜单项

CEF 右键添加开发者选项菜单项

实现过程:

让自己的MyClientHandler来继承 CefContextMenuHandler这个抽象类,然对其下面的纯虚函数进行重写

1.获得事件处理器

virtual CefRefPtr<CefContextMenuHandler> GetContextMenuHandler()
{
return this;
}

2. 重写CefContextMenuHandler 的方法

virtual void OnBeforeContextMenu(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params,
CefRefPtr<CefMenuModel> model); virtual bool OnContextMenuCommand(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params,
int command_id,
EventFlags event_flags);

在MyClientHandler 类中添加 创建开发者工具窗口函数

void ShowDevelopTools(CefRefPtr<CefBrowser> browser);

实现:

enum MyEnum
{
MENU_ID_USER_OPENLINK = MENU_ID_USER_FIRST + ,
MENU_ID_USER_SHOWDEVTOOLS,
}; void CCefBrowserEventHandler::OnBeforeContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model)
{
model->Remove(MENU_ID_PRINT);
model->Remove(MENU_ID_VIEW_SOURCE); if ((params->GetTypeFlags() & (CM_TYPEFLAG_PAGE | CM_TYPEFLAG_FRAME)) != ) {
// Add a separator if the menu already has items.
if (model->GetCount() > )
{
model->RemoveAt();
model->Remove(MENU_ID_BACK);
model->Remove(MENU_ID_FORWARD);
//model->Clear();
//model->AddSeparator();
#ifdef _DEBUG
model->AddItem(MENU_ID_USER_SHOWDEVTOOLS, L"开发者工具"); //"&Show DevTools");
#else #endif
}
}
} bool CCefBrowserEventHandler::OnContextMenuCommand(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefContextMenuParams> params, int command_id, EventFlags event_flags)
{
switch (command_id)
{
case MENU_ID_USER_SHOWDEVTOOLS:
{
ShowDevelopTools(browser);
return true;
}
default:
break;
} return false;
} void CCefBrowserEventHandler::ShowDevelopTools(CefRefPtr<CefBrowser> browser)
{
CefWindowInfo windowInfo;
CefBrowserSettings settings; #if defined(OS_WIN)
//windowInfo.SetAsPopup(browser->GetHost()->GetWindowHandle(), "DevTools");
windowInfo.SetAsPopup(NULL, "DevTools"); //RECT rc = { 0, 0, 800, 600 };
//windowInfo.SetAsChild(*theApp.m_pMainWnd, rc);
#endif browser->GetHost()->ShowDevTools(windowInfo, this, settings, CefPoint());
}

参考:https://segmentfault.com/q/1010000013209473/a-1020000013211845

参考:https://github.com/cztomczak/cef2go/issues/22

参考:https://blog.csdn.net/markbruce/article/details/78846985