简体   繁体   English

左键按下的 hWnd PostMessage 模拟不起作用

[英]hWnd PostMessage simulation of a left keypress doesn't work

I'm trying to make a program that will simulate a LEFT keypress to a window.我正在尝试制作一个程序来模拟 window 的LEFT按键。

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...但是这两行代码的结果与在 window 上正常按LEFT的结果并不相同...

Normally pressing LEFT (WORKS):通常按LEFT (工作):

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

PostMessage ing a LEFT keypress (DOESN'T WORK): PostMessage ing 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?是因为cRepeatScanCodefExtendedfRepeatfUp不一样吗? if so how do I set them correctly?如果是这样,我该如何正确设置它们?

First, for the cRepeat ..., according to the WM_KEYDOWN and WM_KEYUP It is in different bits of lParam .首先,对于cRepeat ...,根据WM_KEYDOWNWM_KEYUP它在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 inRaymond's article , using PostMessage to simulate keyboard input is unreliable.然后,正如雷蒙德的文章中提到的,使用PostMessage来模拟键盘输入是不可靠的。 Instead, you could use SendInput method.相反,您可以使用SendInput方法。 Of course you can use SendKeys wrapped in forms.当然,您可以使用包装在 forms 中的SendKeys

Before that you need to get the keyboard focus.在此之前,您需要获得键盘焦点。

SetForegroundWindow(hwnd);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM