Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't send key to window with SendMessage

Tags:

windows

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

like image 854
guidoman Avatar asked Mar 19 '10 11:03

guidoman


2 Answers

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!

like image 67
guidoman Avatar answered Oct 17 '22 20:10

guidoman


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);
like image 44
Nick Dandoulakis Avatar answered Oct 17 '22 21:10

Nick Dandoulakis