Can't send key to window with SendMessage
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 开发者_如何学Goby 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);
use SendInput Function
http://msdn.microsoft.com/en-us/library/ms646310%28VS.85%29.aspx
Depending on version of Windows sending messages might not work if you are sending message to elevated application (that is application with administrative privileges) from un-elevated one. Could this be the culprit here?
精彩评论