I'm writing a C program under Windows that should send an ENTER key to a dialog box to close it automatically.
I retrieve the handle to the top level window I'm interested in (by means of EnumDesktopWindows()) and then try to send an ENTER key using SendMessage (note also that closing the window by sending WM_CLOSE works fine).
None of the following works:
SendMessage( hTargetWindow, WM_CHAR, VK_RETURN, 0 );
SendMessage( hTargetWindow, WM_CHAR, VK_RETURN, 1 );
SendMessage( hTargetWindow, WM_KEYDOWN, VK_RETURN, 1 );
SendMessage( hTargetWindow, WM_KEYUP, VK_RETURN, 1 );
SendMessage( hTargetWindow, WM_KEYDOWN, VK_RETURN, 1 );
SendMessage( hTargetWindow, WM_CHAR, VK_RETURN, 1 );
SendMessage( hTargetWindow, WM_KEYUP, VK_RETURN, 1 );
and so on...
As a possibly simpler scenario, I also tried to send an ascii key to, say, notepad.
How is this supposed to work?
Thanks in advance
None of the ways suggested by Nick D worked! Surprisingly, the following works:
PostMessage(hTargetWindow, WM_KEYDOWN, VK_RETURN, 0);
That is, I'm invoking PostMessage instead of SendMessage. I'm not a Windows expert, so I don't understand exactly the difference between the two functions.
Anyway, this does exactly what I need: sending an ENTER key to a dialog (BTW, I'm simulating the behavior of the registry key enableDefaultReply under Win XP Embedded). Actually, this does what I need with one exception: it seems to work only if the whole window has the focus. But this should be easy to fix.
Thanks for suggesting PostMessage!
This should work
SendMessage(hTargetWindow, WM_KEYDOWN, VK_RETURN, 0);
But the dialog won't close if the default button, that actually closes the dialog, isn't focused.
And for sending ASCII chars:
PostMessage(hTargetWindow, WM_CHAR, ch, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With