我正在尝试实现一个程序,该程序将相同的消息发送到一个窗口,如果连续按下某个键,该窗口将被发送。这是应用程序代码的一部分(整个 Form1.cs 代码在此处):
[DllImport("User32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, IntPtr windowTitle);
private void button1_Click(object sender, EventArgs e)
{
// find notepad process
System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("notepad");
// find child handle of notepad process
// that is where we can send WM_KEYDOWN, WM_CHAR and WM_KEY up messages to write in the window
IntPtr childHandle = FindWindowEx(p[0].MainWindowHandle, IntPtr.Zero,"Edit", IntPtr.Zero);
// WM_KEYDOWN message with parameters for 1st key
SendMessage(childHandle, (uint)0x0100, (UIntPtr)0x00000041, (IntPtr)(0x001E0001));
// WM_CHAR message with parameters for 1st key
SendMessage(childHandle, (uint)0x0102, (UIntPtr)0x00000061, (IntPtr)(0x001E0001));
// WM_KEYDOWN message with parameters for n-th key
SendMessage(childHandle, (uint)0x0100, (UIntPtr)0x00000041, (IntPtr)(0x401E0001));
// WM_CHAR message with parameters for n-th key
SendMessage(childHandle, (uint)0x0102, (UIntPtr)0x00000061, (IntPtr)(0x401E0001));
// WM_KEYUP message
SendMessage(childHandle, (uint)0x0101, (UIntPtr)0x00000041, (IntPtr)(0xC01E0001));
}
到达代码中的 WM_KEYUP SendMessage 后,程序崩溃并给出错误:
我该如何解决这个错误?WM_KEYUP 之前的 4 个 SendMessage 调用工作正常,它们将 2 个字母“a”发送到记事本。
感谢您的回复