Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 933
Emil Avatar asked Dec 21 '22 00:12

Emil


1 Answers

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.

like image 65
Saeb Amini Avatar answered Jan 02 '23 21:01

Saeb Amini