CefShap-如何通过C#将双击注入网页?

问题描述

我有一个基于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); 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,CefEventFlags.LeftMouseButton);
System.Threading.Thread.Sleep(50);
host.SendMouseClickEvent(x,true,CefEventFlags.LeftMouseButton);

但是我如何注入双击? 如上所示,仅发送两次点击失败:

int x = 150;
int y = 150;
var host = chromeBrowserInstance.GetBrowser().GetHost();

host.SendMouseClickEvent(x,CefEventFlags.LeftMouseButton);

System.Threading.Thread.Sleep(100);

host.SendMouseClickEvent(x,CefEventFlags.LeftMouseButton);

这将提供以下输出(缺少预期的“ doubleclicked”):

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,mouseup,clickCount
);

但是无论我为clickCount设置(甚至为0),它只会产生一次mouseup / 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,true,CefEventFlags.None
    );

    // second click
    host.SendMouseClickEvent( 
        x,2,CefEventFlags.None
    );            
}

按照amaitland的建议登录CefSharp.WPF.ChromiumWebBrowser.cs后,我发现了以上原因失败的原因: 我通过思考误解了count参数,这是将要执行的点击次数。 但实际上是一系列事件中当前事件的索引。
例如,第三个count的{​​{1}}参数是SendMouseClickEvent,因此cef知道第二个事件和第三个事件属于同一事件。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...