我尝试使用将线程输入附加到另一个线程的组合,并设置键状态以发送 shift + a 组合({{1} })到记事本。问题是,下面的代码打印A
而不是a
。
我已经尝试调试代码并按下 shift ,同时单步执行断点,并且在按住shift时效果很好。所以我知道线程附件正在工作。
所以看起来A
命令似乎不起作用。我做错了什么?
以下是代码:
SetKeyboardState(...)
更新
发布四个命令:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
static extern bool SetKeyboardState(byte[] lpKeyState);
public static void simKeyPressWithModifier(IntPtr winHandle)
{
uint threadId = User32.GetWindowThreadProcessId(winHandle, IntPtr.Zero);
byte[] keys = new byte[256];
if (!GetKeyboardState(keys))
{
int err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
User32.AttachThreadInput((uint)AppDomain.GetCurrentThreadId(), threadId, true);
int sKey = (int)VK.VK_LSHIFT;
keys[sKey] = 0xFF;
if (!SetKeyboardState(keys))
{
int err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
User32.PostMessage(winHandle, WM.WM_KEYDOWN, (IntPtr)Keys.A, IntPtr.Zero);
keys[sKey] = 0;
if (!SetKeyboardState(keys))
{
int err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
User32.AttachThreadInput((uint)AppDomain.GetCurrentThreadId(), threadId, false);
}
结果为两个小写的 public static void simKeyPressWithModifier(IntPtr winHandle)
{
User32.PostMessage(winHandle, WM.WM_KEYDOWN, (IntPtr)VK.VK_LSHIFT, IntPtr.Zero);
User32.PostMessage(winHandle, WM.WM_KEYDOWN, (IntPtr)Keys.A, IntPtr.Zero);
User32.PostMessage(winHandle, WM.WM_KEYUP, (IntPtr)Keys.A, IntPtr.Zero);
User32.PostMessage(winHandle, WM.WM_KEYUP, (IntPtr)VK.VK_LSHIFT, IntPtr.Zero);
}
。
如果我a
代替SendMessage
,则根本不显示任何内容:
PostMessage
在C#中使用Windows 8.1上的.NET Framework 4。
public static void simKeyPressWithModifier(IntPtr winHandle)
{
User32.SendMessage(winHandle, WM.WM_KEYDOWN, (IntPtr)VK.VK_LSHIFT, IntPtr.Zero);
User32.SendMessage(winHandle, WM.WM_KEYDOWN, (IntPtr)Keys.A, IntPtr.Zero);
User32.SendMessage(winHandle, WM.WM_KEYUP, (IntPtr)Keys.A, IntPtr.Zero);
User32.SendMessage(winHandle, WM.WM_KEYUP, (IntPtr)VK.VK_LSHIFT, IntPtr.Zero);
}