1

I'm trying to post/send a message to some hwnd without the interference from modifier keys (ctrl, alt, shift).

Basically i want to send F1 message (without ctrl) to hwnd while im pressing ctrl (like Example 2) but with SendMessage\PostMessage.

I tried use SendInput to set up the CTRL key, post the message and set down the CTRL key back, but it fails 50% of time.

Example 1: Code with SendMessageA:

HWND hwnd = FindWindowA(0, "Notepad");
if (GetKeyState(VK_CONTROL) < -1) // if CTRL is pressed
{
 keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); // up the CTRL key
 SendMessageA(hwnd, WM_KEYDOWN, VK_F1, 0); // send F1 keydown
 keybd_event(VK_CONTROL, 0, 0, 0); // down the CTRL key
}
else
{
 SendMessageA(hwnd, WM_KEYDOWN, VK_F1, 0); // send F1 keydown
}

Theoretically this code would solve the problem, but it sometimes sends the message with the CTRL pressed and sometimes not.

Example 2: Same code with SendInput (but these works fine)

HWND hwnd = FindWindowA(0, "Notepad");
if (GetKeyState(VK_CONTROL) < -1) // if CTRL is pressed
{
 keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); // up the CTRL key
 keybd_event(VK_F1, 0, 0, 0); // send F1 keydown
 keybd_event(VK_CONTROL, 0, 0, 0); // down the CTRL key back
}
else
{
 keybd_event(VK_F1, 0, 0, 0); // send F1 keydown
}
joaopp
  • 11
  • 3
  • With reference to the first example, try putting a short delay between the first call to `keybd_event` (which is deprecated, by the way) and the call to `SendMessage`. – Paul Sanders Sep 28 '19 at 00:34
  • I tried to put delay but still dont working. – joaopp Sep 28 '19 at 00:39
  • I have no (or just some) idea of what you are trying to do. "delay" makes me cringe because it sounds like polling and that, in my book, is not thinking. What do you want to do? Why not put up a [mcve]? – Ted Lyngmo Sep 28 '19 at 04:27
  • Ted Lyngmo, i edited the post, the example 2 does exactly what I want, but I needed to make it work using PostMessage/SendMessage. – joaopp Sep 28 '19 at 04:43
  • `keybd_event()` (and its successor `SendInput()`) is **asynchronous**, [it takes time to be processed](https://devblogs.microsoft.com/oldnewthing/20140213-00/?p=1773). But `SendMessage()` is **synchronous**, it does not exit until the message is processed. So your F1 message gets processed before your Control key manipulations are processed. Also, `GetKeyState()` is relative to the calling thread, not to the whole system, use `GetAsyncKeyState()` instead. But anyway, [you can't simulate keyboard input with (Post|Send)Message()](https://devblogs.microsoft.com/oldnewthing/20050530-11/?p=35513). – Remy Lebeau Sep 28 '19 at 07:36
  • Using GetAsyncKeyState() I got the same results by putting Sleep. Keeps failing 50% of the time. – joaopp Sep 29 '19 at 05:58
  • did you manage to solve this issue? :) – Rainb Sep 19 '22 at 09:27

0 Answers0