【问题标题】:Using SendKeys when Windows locks gets Access Denied当 Windows 锁被拒绝访问时使用 SendKeys
【发布时间】:2015-05-13 04:01:28
【问题描述】:

我有一个带有 WebBrowser 控件的 .NET Winform,它使用用户名和密码登录网站。在密码文本框中输入某些内容之前,“提交”按钮被禁用,所以我不能使用 txt.SetAttribute() 因为它似乎没有启用提交按钮。使用 SendKeys.Send(password) 可以正常工作,并且启用了提交按钮。

问题是当我的电脑锁定时,SendKeys 命令似乎会导致以下情况:

System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)

起初我以为这与我的帐户有关,但我是 PC 上的管理员,我的会话仍然存在,只是 PC 被锁定。

我读到here 我可以使用 SendMessage API 函数,所以我尝试了这个:

System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessesByName(_formProcessName).FirstOrDefault();
if (p == null)
{
    throw new Exception(string.Format("Login Error. Cannot find window process name: [{0}]", _formProcessName));
}
IntPtr h = p.MainWindowHandle;
const int WM_SETTEXT = 0x000C;
SendMessage(h, WM_SETTEXT, IntPtr.Zero, _password);  

...无济于事。没有错误,但它似乎没有向窗口发送任何内容,即使它确实获得了正确的窗口句柄。

我的问题是,即使我的电脑被锁定,我如何才能对 webbrowser 控件执行 SendKeys()?有人有什么建议吗?

【问题讨论】:

  • 您可以通过禁用屏幕保护程序和自动待机功能来阻止您的 PC 被“锁定”。 (如果这是实际发生的情况。)
  • 这是一个选项。但这是一个 POC,潜在客户不会发现该解决方案是理想的。

标签: c# .net winforms webbrowser-control


【解决方案1】:

经过大量挖掘,我决定切换到Selenium。而且更简单!!

using (var driver = new ChromeDriver())
{
    // Go to the home page
    driver.Navigate().GoToUrl("yourloginpageurl");

    var userNameField = driver.FindElementByName("userIdTextInput");
    userNameField.SendKeys("aaa");

    var passwordField = driver.FindElementByName("pwdIdTextInput");
    passwordField.SendKeys("bbb");

    var loginButton = driver.FindElementByXPath("//form[@id='abc']/button");
    loginButton.Click();

}

就这么简单。 PC被锁定时它可以正常工作,因此主要问题已解决。它也更容易编码。 built-in wait objects 比 WebBrowser 的 DocumentWait 事件更容易。如果您在 WebBrowser 控件的问题后遇到问题,我建议您尝试 Selenium。到目前为止,我看到的唯一缺点是它是您正在使用的浏览器的真实实例,因此它没有内置到您的表单中,您可以根据需要将其隐藏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 2011-04-29
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    相关资源
    最近更新 更多