Thorarin
Thorarin

Reputation: 48496

Simulate clicking a button in another window in C#

I'd like to close a dialog that pops up automatically, but I'm having some trouble getting it to work. My Win32 programming is a bit rusty after several years of limited usage.

I'm using FindWindowEx to get handles to the dialog and the button I want to click. I was under the impression that sending a WM_COMMAND to the dialog, with the button handle in the wParam parameter would do the trick.

Window window = Window.FindWindow("TSomeDialog", null);
Window cancelButton = Window.FindWindow("TButton", "Cancel", window);

Message message = Message.Create(window.HWnd, 0x0111, cancelButton.HWnd, IntPtr.Zero);
PostMessage(message);

public void PostMessage(Message message)
{
    // Win32 API import
    PostMessage(message.HWnd, message.Msg, message.WParam, message.LParam);
}

Window is a class that implements IWin32Window and wraps some Win32 API calls. I have inlined the constant for WM_COMMAND (0x111).

What am I doing wrong? :)

Upvotes: 1

Views: 3983

Answers (3)

Peter Ruderman
Peter Ruderman

Reputation: 12485

Well, according to the documentation for WM_COMMAND, lParam should be the handle to the control's window (it looks like you're passing it in wParam).

wParam should have its high order word equal to BN_CLICKED and its low order word equal to the control's identifier.

(You can use GetWindowLong with GWL_ID to retrieve this, but presumably its IDCANCEL.)

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292655

Why not send a WM_CLOSE message instead ?

Upvotes: 0

Vincent McNabb
Vincent McNabb

Reputation: 34729

Why not just send a WM_SYSCOMMAND message with a SC_CLOSE parameter? That should close the window.

Upvotes: 0

Related Questions