Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

.net - How do you override the ContextMenu that appears when right clicking on winforms WebBrowser Control?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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

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

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...