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 + 200,
    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)) != 0) {
        // Add a separator if the menu already has items.
        if (model->GetCount() > 0)
        {
            model->RemoveAt(2);
            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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM