开发者

Sending WM_KEYUP message to a window gives an OverflowException

开发者 https://www.devze.com 2023-03-19 19:07 出处:网络
I am trying to implement a program that sends the same messages to a window that would be sent if a certain key is continuously pressed.

I am trying to implement a program that sends the same messages to a window that would be sent if a certain key is continuously pressed. This is part of the code (entire Form1.cs code is here ) for the application:

开发者_运维技巧
    [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));
    }

Upon reaching the WM_KEYUP SendMessage in the code the program crashes and gives the error:

Sending WM_KEYUP message to a window gives an OverflowException

How can i fix this error? The 4 SendMessage calls before the WM_KEYUP one work ok and they send 2 letter 'a' to notepad.

Thanks for your replies


I assume you are compiling for x86. On x86 targets, 0xC01E0001 is not a valid IntPtr value (the maximum is 0x7FFFFFFF).

2 options here :

  • You do use the value lParam in the target application. In this case you have to use another value for the IntPtr, or use the type UIntPtr (but this type is not CLS-compliant).
  • You do not use the value lParam in the target application. In this case just pass IntPtr.Zero as lParam.
0

精彩评论

暂无评论...
验证码 换一张
取 消