try this:
There are two different parts to this solution. The first is pretty easy - just set an event handler for the MouseDown event of your browser control:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
}
private void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
e.ReturnValue = false;
// Your custom code
}
}
but there were also some javascript-heavy websites on which this solution did not work. For those, I found another solution involving injecting javascript into the document which will prevent the middle-click:
HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
HtmlElement mscript = browser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)mscript.DomElement;
element.text = "function handleMouseEvent(e) { "
+ "var evt = (e==null ? event:e); "
+ "if ( e.which == 2 ) e.preventDefault(); "
+ "return true; } "
+ "document.onmousedown = handleMouseEvent; "
+ "document.onmouseup = handleMouseEvent; "
+ "document.onclick = handleMouseEvent; ";
head.AppendChild(mscript);
UPDATE
The JavaScript injection methodology can be improved by following the suggested way to do it using managed code only:
stackoverflow.com/a/6222430/1248295
This is an alternative example implementation of the javascript injection, wrote in VB.NET:
Private ReadOnly handleMouseEventJs As String =
"
function HandleMouseEvent(e) {
var evt = (e==null ? event:e);
if (e.which == 2) e.preventDefault();
return true;
}
document.onmousedown = HandleMouseEvent;
// These events below seems are not necessary to handle for this purpose.
// document.onmouseup = HandleMouseEvent;
// document.onclick = HandleMouseEvent;
"
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) _
Handles WebBrowser1.Navigated
Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
Dim doc As HtmlDocument = wb.Document
Dim head As HtmlElement = doc.GetElementsByTagName("head")(0)
Dim js As HtmlElement = doc.CreateElement("script")
js.SetAttribute("text", handleMouseEventJs)
head.AppendChild(js)
' This method call seems not necessary at all, it works fine without invocking it.
' doc.InvokeScript("HandleMouseEvent", Nothing)
End Sub
UPDATE 2
Inject this code instead:
document.body.onmousedown = function(e) { if (e.button === 1) return false; }
https://stackoverflow.com/a/30423534/1248295