【问题标题】:Sending Keyboard RETURN Key on remote server with Remote Desktop Connection Closed在远程桌面连接关闭的远程服务器上发送键盘返回键
【发布时间】:2021-03-01 05:52:13
【问题描述】:

我有一个 WinForms WebView2 项目,它是一个在网页上运行一些 JavaScript 的简单机器人。我正在使用 JS 单击网页上的元素并下载文件。该网站提示我“您确定要离开该页面吗?”对话框,所以我想发送 RETURN 键盘按下以确认我想离开网页并下载文件。

我想使用 Windows 任务计划程序自动运行它。只要我远程连接到我的服务器并且窗口没有最小化,这种方法就可以工作。但是,当我没有远程连接到我的服务器时,我的回车键返回并出现错误。

我已经用 SendKeys 尝试过这段代码

//Get Webview proccess
Process p = Process.GetProcessesByName("msedgewebview2").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    printToTextbox("pressed ENTER key");
    SendKeys.SendWait("{ENTER}");
    await checkDownloadFinished();
}

我启动我的 Bot,然后退出我的远程会话。当我返回时,程序到达SendKeys.SendWait("{ENTER}");时会出现此错误

System.ComponentModel.Win32Exception: 'Access is denied'

我也试过 Nuget 包 InputSimulator

Process p = Process.GetProcessesByName("msedgewebview2").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    printToTextbox("pressed ENTER key");
    InputSimulator s = new InputSimulator();
    s.Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
    await checkDownloadFinished();
}

按照相同的过程,我启动我的机器人并退出我的远程会话。当我返回时,我遇到了这个错误:

System.Exception: 'Some simulated input commands were not sent successfully. The most common reason
 for this happening are the security features of Windows including User Interface Privacy Isolation
 (UIPI). Your application can only send commands to applications of the same or lower elevation.
 Similarly certain commands are restricted to Accessibility/UIAutomation applications. Refer to the
 project home page and the code samples for more information.'

还有其他与 c# 兼容的方式来发送击键吗?或者有没有办法防止对话框弹出?谢谢!

【问题讨论】:

    标签: c# .net sendkeys webview2 inputsimulator


    【解决方案1】:

    你做错了:-)

    您应该尝试查看:CoreWebView2.ScriptDialogOpening Event

    scriptdialogopening 的 eventargs 带有一个 Accept() 方法来单击对话框上的 Ok

    这里是 eventargs 链接:CoreWebView2ScriptDialogOpeningEventArgs

    现在你不必和SendKeys 搞混了。

    【讨论】:

    • 非常感谢!这绝对是一个更好的方法。我一直试图在我的表单中实现这一点,但无法找出正确的方法(我之前没有使用过事件)。我在这里引用了示例 repo:link 但是他们实现事件的方式不适用于CoreWebView2ScriptDialogOpeningEventArgs 事件编辑:没关系!我想通了!
    • 是的,您的用例正是他们实现该事件的原因:顺便说一句,您可能应该检查 eventargs 的属性,因此您只需为所需的对话框按“确定”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2013-05-15
    • 2013-08-09
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多