C# IE11 自动化 - 设置仅给定窗口句柄的文档表单元素



我已经使用以下 C# 代码连接到一个打开的 IE11 窗口。 但是我不知道如何使用getElementID访问它的文档元素,因为我需要阅读和设置这些元素。

//Import the FindWindow API to find our window
[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);
//Import the SetForeground API to activate it
[DllImportAttribute("User32.dll")]
private static extern IntPtr SetForegroundWindow(int hWnd);
......
// Find the IE window
int hWnd = FindWindow(null, "ACME Form Input - Internet Explorer");
if (hWnd > 0) // The IE window was found.
{
// Bring the IE window to the front.
SetForegroundWindow(hWnd);

使用上面的代码,如何访问IE文档以获取和设置其表单元素? 请帮忙!

安 迪

为了回应您的评论,我建议使用类似 filesystemwatcher 类的东西来监控您的文件夹,用于文本文件操作的标准 System.IO 东西,然后使用 selenium 用于网站自动化。基本上,Selenium可以充当chrome,Firefox等(或无头(,并在页面上找到html元素并发送文本,单击按钮等。

要以您想要的方式访问文档元素,您需要将 ie.document 强制转换或分配给 mshtml 文档。您需要将 ref 添加到 mshtml,我在下面有一个显示分配的示例。

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");

最新更新