How to deactivate “right click” on WPF Webbrowser Control?

后端 未结 5 594
终归单人心
终归单人心 2020-12-01 09:41

I can\'t seem to find an answer to this. Does anyone know?

Thanks

5条回答
  •  萌比男神i
    2020-12-01 10:08

    Digging graves it seems, but...

    Based on e.g. answer here https://stackoverflow.com/a/6979961/4537127 get IWebBrowser2 interface, then get DWebBrowserEvents2_Event interface, and attach handler to DocumentComplete event

    SHDocVw.DWebBrowserEvents2_Event wbEvents = (SHDocVw.DWebBrowserEvents2_Event)myWebBrowser2;
    wbEvents.DocumentComplete += new SHDocVw.DWebBrowserEvents2_DocumentCompleteEventHandler(OnWebBrowserDocumentComplete);
    

    (Above must to be done only once on WebBrowser LoadCompleted event, so add some logic to run it only on first one)

    And then in this handler, run sone JavaScript to attach event listener to document, and as bonus, to the iframe in this document

    private void OnWebBrowserDocumentComplete(object pDisp, ref object URL)
    {
        /* try-catch wrap this if you get e.g. DISP_E_EXCEPTION */
        MyBrowser.InvokeScript("execScript", new Object[]
        {
            "document.addEventListener('contextmenu', function(e){ e.preventDefault(); }, false);" +
            "var frm = document.getElementById('frm');" +
            "frm.onload = function() { frm.contentDocument.body.addEventListener('contextmenu', function(e){ e.preventDefault(); }, false); };",
            "JavaScript"
        });
    }
    

    This will work even if the iframe content is changed. I use this with DITA WebHelp classic running in WPF WebBrowser.

    And no mshtml reference needed.

提交回复
热议问题