Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on 'OK' button of message box using WINAPI in c#

I am trying to click on 'OK' button on a message box of C# windows form using winapi. Below is the code that I am working on.

private const int WM_CLOSE = 16;
private const int BN_CLICKED = 245;

[DllImport("user32.dll", CharSet=CharSet.Auto)]
        public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);

[DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className,  string  windowTitle);

//this works
hwnd = FindWindow(null, "Message");
if(hwnd!=0)
      SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero);

//this doesn't work.
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "ok");
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);

Though i get a value in hwndChild, it is not recognising BN_CLICKED. I am not sure what am I missing. any help?

I am trying to close the message box button of another application and this is what I am doing. But, I m still missing something.

IntPtr hwndChild = IntPtr.Zero;
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero,' '"Button", "OK");
SendMessage((int)hwndChild, WM_COMMAND, (BN_CLICKED '<<16) | IDOK, hwndChild);
like image 308
Virus Avatar asked Feb 19 '13 16:02

Virus


1 Answers

BN_CLICKED is not a message. You need to send a WM_COMMAND message containing the BN_CLICKED notification and the button ID in the wParam and the button handle in lParam.

The parent window of the button receives this notification code through the WM_COMMAND message.

private const uint WM_COMMAND = 0x0111;
private const int BN_CLICKED = 245;
private const int IDOK = 1;

[DllImport("user32.dll", CharSet=CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);

[DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className,  string  windowTitle);

SendMessage(hwndChild, WM_COMMAND, (BN_CLICKED << 16) | IDOK, hwndChild);
like image 101
Dark Falcon Avatar answered Nov 12 '22 07:11

Dark Falcon