我有一个基于CefSharp v83.4.20的应用程序,并尝试从C#代码中双击注入。Winform和WPF都会发生这种情况。
这是用于测试的Html:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div style="position: absolute; width: 100px; height: 100px; z-index: 100; background: rgb(0, 0, 0); left: 100px; top: 100px;"></div>
</body>
</html>
<script>
var elem = document.getElementsByTagName('div')[0];
elem.addEventListener('mousedown', function () {
console.log('mousedown');
});
elem.addEventListener('mouseup', function () {
console.log('mouseup');
});
elem.addEventListener('click', function () {
console.log('click');
});
elem.addEventListener('dblclick', function () {
// this never gets called when injecting two clicks, but works when manually double clicking
console.log('doubleclicked');
});
</script>
我可以很容易地从C#代码中注入点击到Html,如下所示:
int x = 150;
int y = 150;
var host = chromeBrowserInstance.GetBrowser().GetHost();
host.SendMouseClickEvent(x, y, MouseButtonType.Left, false, 0, CefEventFlags.LeftMouseButton);
System.Threading.Thread.Sleep(50);
host.SendMouseClickEvent(x, y, MouseButtonType.Left, true, 0, CefEventFlags.LeftMouseButton);
但是我怎样才能注入双击?如上所示简单发送两次点击失败:
int x = 150;
int y = 150;
var host = chromeBrowserInstance.GetBrowser().GetHost();
host.SendMouseClickEvent(x, y, MouseButtonType.Left, false, 0, CefEventFlags.LeftMouseButton);
System.Threading.Thread.Sleep(50);
host.SendMouseClickEvent(x, y, MouseButtonType.Left, true, 0, CefEventFlags.LeftMouseButton);
System.Threading.Thread.Sleep(100);
host.SendMouseClickEvent(x, y, MouseButtonType.Left, false, 0, CefEventFlags.LeftMouseButton);
System.Threading.Thread.Sleep(50);
host.SendMouseClickEvent(x, y, MouseButtonType.Left, true, 0, CefEventFlags.LeftMouseButton);
这会给出以下输出(缺少预期的"双击"(:
mousedown
mouseup
click
mousedown
mouseup
click
手动双击时,出现预期的"双击":
mousedown
mouseup
click
mousedown
mouseup
click
doubleclicked
我试着调整时间,但无济于事。有什么想法可以注入工作双击吗?
编辑:
感谢您的输入,我尝试了:
MouseEvent me = new MouseEvent(150, 150, CefEventFlags.LeftMouseButton);
bool mouseup = true;
int clickCount = 2;
host.SendMouseClickEvent(
me,
MouseButtonType.Left,
mouseup,
clickCount
);
但无论我为clickCount
(甚至0(设置了什么,它都只产生一个鼠标上移/mousedown事件
在将随机文本添加到正文后,我发现使用上面的方法clickCount
是2或3,并且正文中的文本得到mouseup = true
高亮显示,就像手动双击/三次一样
所以它在某种程度上起作用,但不会产生预期的事件。
这会双击并使dblclick
事件激发:
public void double_click(int x, int y) {
var host = browser.GetHost();
// first click
host.SendMouseClickEvent(
x, y, MouseButtonType.Left, false, 1, CefEventFlags.LeftMouseButton
);
host.SendMouseClickEvent(
x, y, MouseButtonType.Left, true, 1, CefEventFlags.None
);
// second click
host.SendMouseClickEvent(
x, y, MouseButtonType.Left, false, 2, CefEventFlags.LeftMouseButton
);
host.SendMouseClickEvent(
x, y, MouseButtonType.Left, true, 1, CefEventFlags.None
);
}
按照amaitland的建议,在CefSharp.WPF.ChromiumWebBrowser.cs
中进行了一些登录后,我发现了上述失败的原因:我误解了count
参数,因为认为它将是要执行的点击次数但实际上它是一系列事件中当前事件的索引
例如,第三个SendMouseClickEvent
的count
参数是2
,因此cef知道第二个和第三个事件属于一起。