C# IE11 自动化 - 无法连接以打开 IE 窗口



我正在尝试连接到已经打开的Internet Explorer窗口。 连接后,我需要将一些击键(通过 SendKeys(发送到 IE 窗口进行一些处理。 我在下面有以下代码,直到 SendKeys 命令为止。 它找到标题为"图形数据库"的IE窗口。 当它点击"SendKeys.Send("{TAB}"(;"我收到错误"发生了类型为'系统.空引用异常'的未处理异常"。

附加信息:我还收到以下有关NullReferenceException错误的信息。 奇怪的是,如果我编码打开一个新的IE窗口,然后使用SendKeys,它可以正常工作。连接到现有窗口似乎会导致此问题。

发送密钥无法在此应用程序内运行,因为该应用程序未处理 Windows 消息。 更改应用程序以处理消息,或使用 SendKeys.SendWait 方法。

任何人都可以帮我弄清楚该怎么做才能解决这个问题吗?

安 迪

InternetExplorer IE = null;
// Get all browser objects
ShellWindows allBrowsers = new ShellWindows();
if (allBrowsers.Count == 0)
{
throw new Exception("Cannot find IE");
}
// Attach to IE program process
foreach (InternetExplorer browser in allBrowsers)
{                           
if (browser.LocationName == "Graphics Database")
{
MessageBox.Show ("Found IE browser '" + browser.LocationName + "'");
IE = (InternetExplorer)browser;
}
}
IE.Visible = true;
System.Threading.Thread.Sleep(2000);
SendKeys.Send("{TAB}");
SendKeys.Send("G1007");
SendKeys.Send("{ENTER}");

我能够解决这个问题。我永远无法获得IE。可见 = 真实工作。这似乎在我的代码中没有任何作用。我不得不使用 SetForegroundWindow(( 将焦点设置为 IE 窗口。

// Find the IE window 
int hWnd = FindWindow(null, "Graphics Database - Internet Explorer"); 
if (hWnd > 0) // The IE window was found. 
{ 
// Bring the IE window to the front. 
SetForegroundWindow(hWnd);

这个网站极大地帮助了我让SetForegroundWindow((工作。

http://forums.codeguru.com/showthread.php?460402-C-General-How-do-I-activate-an-external-Window

安迪请耐心等待,因为这会很长。首先,您需要查看mshtml文档和Dom.https://msdn.microsoft.com/en-us/library/aa741314(v=vs.85(.aspx 我不知道为什么自动化如此复杂,但确实如此。UIautomation类非常适合Windows应用程序,但是对于IE我找不到任何东西。其他人会指向第三方,如waitn和Selenium。Waitn似乎不再受支持,Selenium不会让你抓住一个开放的IE浏览器。我最近走上了这条路,因为我希望能够创建一个应用程序来存储我的网络密码并自动填写它们,因为由于安全限制,我无法在浏览器中保存我的用户名和密码。我这里有一个例子,希望它有所帮助。首先打开 IE 并导航到 http://aavtrain.com/index.asp。然后有一个控制台项目,其中引用了 mshtml 和 shdocvw。下面是代码。它获取窗口,然后查找用户名、密码和提交的元素。然后填充用户名和密码并单击"提交"按钮。我没有登录此站点,因此它不会登录您。我一直在使用它进行测试。我遇到的问题是带有javascript登录表单的网站。如果您进一步了解此信息,请回发,因为我仍在尝试发展概念并创建可重用的东西。

SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
Console.WriteLine("Starting Searchnnn");
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
if (ie.LocationURL.Contains("aavtrain"))
{
Console.WriteLine(ie.LocationURL);
Console.WriteLine("nnnn");
Console.WriteLine("FOUND!n");
mshtml.HTMLDocument document = ie.Document;
mshtml.IHTMLElementCollection elCol = document.getElementsByName("user_name");
mshtml.IHTMLElementCollection elCol2 = document.getElementsByName("password");
mshtml.IHTMLElementCollection elCol3 = document.getElementsByName("Submit");
Console.WriteLine("AutofillPassword");

foreach (mshtml.IHTMLInputElement i in elCol)
{
i.defaultValue = "John";
}
foreach (mshtml.IHTMLInputElement i in elCol2)
{
i.defaultValue = "Password";
}
Console.WriteLine("Will Click Button in 2 seconds");
Thread.Sleep(2000);
foreach (mshtml.HTMLInputButtonElement i in elCol3)
{
i.click();
}

}
}
Console.WriteLine("Finished");

最新更新