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

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

How do I create my own ContextMenuStrip? WebBrowser.ContextMenuStrip does not work for this control.

+3
source share
1 answer

Many other solutions on this site seemed like it was very difficult to do, because it was a COM object ... and recommended adding a new class called "ExtendedWebBrowser". For this task, it turns out to be quite simple.

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

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

Define these event handlers (change contextMenuStrip to match the name of what 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 the shift is held when you right-click, it shows the return value of IE. * Otherwise, it shows contextMenuStripHtmlRightClick (definition not shown in this example)

+5
source

All Articles