-1

I'm trying to make a program that will simulate a LEFT keypress to a window.

I'm using this:

PostMessage(hwnd, WM_KEYDOWN, new IntPtr(0x25), new IntPtr(0));

and this:

PostMessage(hwnd, WM_KEYUP, new IntPtr(0x25), new IntPtr(0));

But the results of these two lines of code aren't identical to the result of normally pressing LEFT on the window...

Normally pressing LEFT(WORKS):

P WM_KEYDOWN nVirtKey:VK_LEFT cRepeat:1 ScanCode:4B fExtended:1 fAltDown:0 fRepeat:0 fUp:0
P WM_KEYUP nVirtKey:VK_LEFT cRepeat:1 ScanCode:4B fExtended:1 fAltDown:0 fRepeat:1 fUp:1

PostMessageing a LEFT keypress (DOESN'T WORK):

P WM_KEYDOWN nVirtKey:VK_LEFT cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0
P WM_KEYUP nVirtKey:VK_LEFT cRepeat:0 ScanCode:00 fExtended:0 fAltDown:0 fRepeat:0 fUp:0

Why is that? Is it because of the cRepeat, ScanCode, fExtended, fRepeat and fUp that aren't the same? if so how do I set them correctly?

Flafy
  • 176
  • 1
  • 3
  • 15
  • 2
    Same answer, as always: [You can't simulate keyboard input with PostMessage](https://devblogs.microsoft.com/oldnewthing/20050530-11/?p=35513). – IInspectable Apr 15 '20 at 13:16

1 Answers1

0

First, for the cRepeat..., according to the WM_KEYDOWN and WM_KEYUP It is in different bits of lParam. To set them:

//WM_KEYDOWN
UINT scan = 0x1 | 0x4b << 16 | 0x1 << 24 | 0x0 << 30 | 0x0 << 31;
//WM_KEYUP
scan = 0x1 | 0x4b << 16 | 0x1 << 24 | 0x1 << 30 | 0x1 << 31;

Then, as metioned in Raymond's article, using PostMessage to simulate keyboard input is unreliable. Instead, you could use SendInput method. Of course you can use SendKeys wrapped in forms.

Before that you need to get the keyboard focus.

SetForegroundWindow(hwnd);
Drake Wu
  • 6,927
  • 1
  • 7
  • 30
  • [Foreground activation permission is like love: You can’t steal it, it has to be given to you](https://devblogs.microsoft.com/oldnewthing/20090220-00/?p=19083). I find it a fair bit unsettling to see users with an *"MSFT"* tag in their user names consistently publish wrong or dangerously incomplete answers. Using the accept ratio is likely the wrong metric if the goal is quality. – IInspectable Apr 17 '20 at 08:19