你如何重写出现时,右键单击的WinForms WebBrowser控件的文本菜单?右键、重写、现时、控件

2023-09-05 04:27:56 作者:穿着校服的大哥i

当你右击WebBrowser控件,将出现选项,如后退,查看源文件等标准的IE上下文菜单。

When you right click on WebBrowser control, the standard IE context menu with options such as "Back", "View Source", etc. appears.

如何让我的自己的ContextMenuStrip出现呢? WebBrowser.ContextMenuStrip不适用于此防治工作。

How do I make my own ContextMenuStrip appear instead? WebBrowser.ContextMenuStrip doesn't work for this Control.

推荐答案

很多本网站上的其他解决方案使它听起来像是这是很难做到的,因为它是一个COM对象......并建议增加一个新的类ExtendedWebBrowser。对于这个任务,它原来是pretty的简单。

A lot of the other solutions on this site made it sound like this was very difficult to do because it was a COM object... and recommended adding a new class "ExtendedWebBrowser". For this task, it turns out to be pretty simple.

在你的code增加了一个Web浏览器控件,添加DocumentCompleted事件处理程序。

In your code which adds a web browser control, add the DocumentCompleted event handler.

    WebBrowser webBrowser1 = new WebBrowser();
    webBrowser1.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

定义这些事件处理程序(改变的ContextMenuStrip来匹配您创建的名称)。

Define these event handlers (change contextMenuStrip to match name of the one you created).

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser browser = (WebBrowser) sender;
        browser.Document.ContextMenuShowing += new HtmlElementEventHandler(Document_ContextMenuShowing);
    }

    void Document_ContextMenuShowing(object sender, HtmlElementEventArgs e)
    {
        // If shift is held when right clicking we show the default IE control.
        e.ReturnValue = e.ShiftKeyPressed; // Only shows ContextMenu if shift key is pressed. 

        // If shift wasn't held, we show our own ContextMenuStrip
        if (!e.ReturnValue)
        {
            // All the MousePosition events seemed returned the offset from the form.  But, was then showed relative to Screen.
            contextMenuStripHtmlRightClick.Show(this, this.Location.X + e.MousePosition.X, this.Location.Y + e.MousePosition.Y); // make it offset of form
        }
    }

请注意:我重写执行以下操作:   *如果移位按住当你右击它显示了IE浏览器的返回值。   *否则,它显示了contextMenuStripHtmlRightClick(在本实施例中未示出的定义)

Note: my override does the following: * if shift is held down when you right click it shows IE return value. * Otherwise it shows the contextMenuStripHtmlRightClick (definition not shown in this example)