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

How do I send Enter key with PostMessage in C#?

我正在尝试使用 PostMessage 向 window 发送一些输入。我没有使用 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));

我认为您发送的输入错误。试试这个。

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));