How to handle Message Boxes while using webbrowser in C#?

13,330

Solution 1

You can "manage" the message box dialog by importing some window functions from user32.dll and getting the messagebox dialog's handle by it's class name and window name. For example to click its OK button:

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.

Solution 2

Copy paste from Sires anwser: https://stackoverflow.com/a/251524/954225

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);
}
Share:
13,330
Emil
Author by

Emil

Be The Change You Wanna See in the World!

Updated on July 05, 2022

Comments

  • Emil
    Emil almost 2 years

    I'm using this webbrowswer feature of C#. Trying to log in a website through my application. Everything goes fine, except when a wrong ID or password is entered there's little message box (that is set on the webpage itself) which pops up and blocks everything until "Ok" is clicked.Message from webpage

    So the question is: Is there any possible way to manage this little window (like reading the text inside of it)? If it is then great! But if there's no way to do that then is there anyway to simply make this message box go away programatically?