0

我正在尝试实现一个程序,该程序将相同的消息发送到一个窗口,如果连续按下某个键,该窗口将被发送。这是应用程序代码的一部分(整个 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”发送到记事本。

感谢您的回复

4

1 回答 1

4

我假设您正在为 x86 进行编译。在 x86 目标上,0xC01E0001不是有效值IntPtr(最大值为0x7FFFFFFF)。

这里有2个选项:

  • 您确实lParam在目标应用程序中使用了该值。在这种情况下,您必须为 , 使用另一个值IntPtr或使用类型UIntPtr(但此类型不符合 CLS)。
  • 您不在lParam目标应用程序中使用该值。IntPtr.Zero在这种情况下,只需传递lParam.
于 2011-07-13T12:56:25.347 回答