gpt4 book ai didi

c# - 在 Windows 浏览器窗体中停用鼠标中键移动

转载 作者:太空宇宙 更新时间:2023-11-03 16:24:31 25 4
gpt4 key购买 nike

我在 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 繁重的网站无法使用此解决方案。对于那些,我找到了另一种解决方案,涉及将 javascript 注入(inject)文档,这将阻止中间单击:

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 注入(inject)方法: stackoverflow.com/a/6222430/1248295

这是 javascript 注入(inject)的替代示例实现,用 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

改为注入(inject)此代码:

document.body.onmousedown = function(e) { if (e.button === 1) return false; }

https://stackoverflow.com/a/30423534/1248295

关于c# - 在 Windows 浏览器窗体中停用鼠标中键移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12978130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com