如何在C#中使用webbrowser处理消息框?

问题描述 投票:4回答:3

我正在使用C#的webbrowswer功能。尝试通过我的应用程序登录网站。一切都很顺利,除非输入错误的ID或密码时,会弹出一个小消息框(在网页上设置)弹出并阻止所有内容,直到点击“确定”。

所以问题是:有没有办法管理这个小窗口(比如阅读里面的文字)?如果真的那么棒!但是,如果没有办法做到这一点,那么无论如何只是让这个消息框以编程方式消失?

c# browser messagebox
3个回答
8
投票

您可以通过从user32.dll导入一些窗口函数并通过它的类名和窗口名称获取消息框对话框的句柄来“管理”消息框对话框。例如,单击其“确定”按钮:

public class Foo
{
    [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);
    }
}

Some reading material from MSDN


2
投票

从系列回复粘贴:qazxsw poi

https://stackoverflow.com/a/251524/954225

0
投票

这是Saeb答案的精炼版。 Saeb的代码对我不起作用,我再添加一步来激活按钮然后点击它。

private void InjectAlertBlocker() {
    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
    string alertBlocker = "window.alert = function () { }";
    element.text = alertBlocker;
    head.AppendChild(scriptEl);
}
© www.soinside.com 2019 - 2024. All rights reserved.