Sending WM_KEYUP message to a window gives an OverflowException

0

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:

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

c#
winforms
pinvoke
windows-messages
overflowexception
asked on Stack Overflow Jul 13, 2011 by Răzvan Flavius Panda • edited Jul 13, 2011 by Răzvan Flavius Panda

1 Answer

4

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.
answered on Stack Overflow Jul 13, 2011 by user703016

User contributions licensed under CC BY-SA 3.0