我在 Windows 窗体中有一个 WebBrowser 控件,我想使用鼠标中键单击向我的浏览器添加一个新选项卡。唯一的问题是每次我使用鼠标中键时,都会出现移动页面的箭头。
那么我如何才能仅针对我的链接点击禁用此移动/拖动命令?
试试这个:这个解决方案有两个不同的部分。第一个非常简单 - 只需为浏览器控件的 MouseDown 事件设置一个事件处理程序:
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
}
}
但也有一些 javascript-heavy 网站,此解决方案无法正常工作。对于那些,我找到了另一种解决方案,涉及将 javascript 注入到文档中,这将阻止中键:
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);
更新
JavaScript 注入方法可以通过遵循仅使用托管代码的建议方法进行改进: stackoverflow.com/a/6222430/1248295
这是 javascript 注入的另一个示例实现,用 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
更新 2
而是注入此代码:
document.body.onmousedown = function(e) { if (e.button === 1) return false; }
单击鼠标中键时显示的移动图标由您的鼠标设置控制。但是您可以检测到鼠标中键单击您的WebBrowser
控件。
为您的控件注册DocumentCompleted
事件WebBrowser
并使用以下代码:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
// code to add tab or do sth else
}
}