如何在C#中使用PostMessage发送Enter键?

时间:2016-06-16 16:55:49

标签: c# testing postmessage

我正在尝试使用PostMessage向窗口发送一些输入。我没有使用SendInput,因为它不会成为焦点。我输入了字符(A),但如何发送Enter密钥?这是我的代码的缩减版本。它的运行但Enter未发送?

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

const int WM_KEYDOWN    = 0x100;
const int WM_KEYUP      = 0x101;

const Int32 WM_CHAR = 0x0102;
const Int32 VK_RETURN = 0x0D;
const int VK_ENTER = 0x0D;

IntPtr val = new IntPtr((Int32)'A');
PostMessage(WindowHandle, WM_KEYDOWN, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_CHAR, (IntPtr)val, new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_KEYDOWN, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, VK_RETURN, (IntPtr)val, new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, (IntPtr)(val - 0x020), new IntPtr(0));

1 个答案:

答案 0 :(得分:2)

我认为你输错了。试试这个。

IntPtr val = new IntPtr((Int32)'A');
PostMessage(WindowHandle, WM_KEYDOWN, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_CHAR, (IntPtr)val, new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, (IntPtr)(val - 0x020), new IntPtr(0));
PostMessage(WindowHandle, WM_KEYDOWN, new IntPtr(VK_RETURN), new IntPtr(0));
PostMessage(WindowHandle, WM_KEYUP, new IntPtr(VK_RETURN), new IntPtr(0));