我在C#windowsform程序中使用webbrowser控件,该程序浏览网站的多个页面,然后使用网站中的某些表单进行交易。 (我尝试用httpwebrequest
和webclient
做这个,但是遇到了一些困难,并且复制了一些网站如何动态生成一些表单选择。我决定使用webbrowser并利用网站的脚本 - 它不是我的网站)。
在最后一个步骤中,我到达一个页面,其中包含一个表单,其中站点在提交表单时在页面上运行验证脚本。如果用户输入了错误信息,则会弹出警报。
但是当我在我的程序中导航到该页面时(在我给空字段赋值之前),我得到警报。当我使用Chrome,Firefox或IE手动执行此操作时,不会发生这种情况。但它发生在webbrowser中。我可以通过提交带有不验证信息的表单在常规浏览器中复制它 - 但在Web浏览器中,它会在我加载页面时发生。
我的目标是:
这里有几个类似于我的问题。我找到的最有希望的帖子有以下代码:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,
string lpszClass, string lpszWindow);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string
lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam,
IntPtr lParam);
private void ClickOKButton()
{
IntPtr hwnd = FindWindow("#32770", "Message from webpage");
hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Button", "OK");
uint message = 0xf5;
SendMessage(hwnd, message, IntPtr.Zero, IntPtr.Zero);
}
这段代码有点超出了我对新手的理解 - 我尝试在一个新类中设置它然后实例化这个类的对象我导航到有问题的页面,然后调用ClickOKButton
方法。没工作。我也尝试在表单级别包含它,然后在程序中运行ClickOKButton
函数,我导航到警报出现的页面。但它没有用。
所以我有几个问题:
InvokeMember("submit")
命令之后加载,即出现警报时。提交后我的代码中的下一步是一个documentcompleted事件处理程序,然后触发,然后完成新表单。在完成字段之前,几乎就像webbrowser正在提交表单一样。因此,我不知道在哪里插入这个ClickOKButton
代码。我写了下面的代码,它运行得很完美。创建了控制台应用程序,它点击了javasript Alert / confirm框的Ok按钮。
using System;
using System.Runtime.InteropServices;
namespace IE_Automation
{
public class IEPoppupWindowClicker
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
private const int BM_CLICK = 0xF5;
private const uint WM_ACTIVATE = 0x6;
private const int WA_ACTIVE = 1;
public void ActivateAndClickOkButton()
{
// find dialog window with titlebar text of "Message from webpage"
var hwnd = FindWindow("#32770", "Message from webpage");
if (hwnd != IntPtr.Zero)
{
// find button on dialog window: classname = "Button", text = "OK"
var btn = FindWindowEx(hwnd, IntPtr.Zero, "Button", "OK");
if (btn != IntPtr.Zero)
{
// activate the button on dialog first or it may not acknowledge a click msg on first try
SendMessage(btn, WM_ACTIVATE, WA_ACTIVE, 0);
// send button a click message
SendMessage(btn, BM_CLICK, 0, 0);
}
else
{
//Interaction.MsgBox("button not found!");
}
}
else
{
//Interaction.MsgBox("window not found!");
}
}
}
}
尝试使用
webBrowser.Document.ActiveElement.InvokeMember("click");
自动点击警告框。它对我有用。