C# and SendMessage (keys) is not working

2019-02-23 23:05发布

问题:

I tried to send a key to an application. For an easy test I just used notepad. That's what the code looks like:

[DllImport("USER32.DLL", EntryPoint = "SendMessageW", SetLastError = true,
         CharSet = CharSet.Unicode, ExactSpelling = true,
         CallingConvention = CallingConvention.StdCall)]
    public static extern bool SendMessage(IntPtr hwnd, int Msg, int wParam, int lParam);


        const int WM_KEYDOWN = 0x100;
    const int WM_a = 0x41;

        public void Press()
    {
        Process[] p = Process.GetProcessesByName("notepad");
        IntPtr pHandle = p[0].MainWindowHandle;

        SendMessage(pHandle, WM_KEYDOWN, WM_a, 0);
    }

But nothing happens.

My main goal is to send the key to an elevated application, but I would be happy to send it to notepad first. I want to work with SendMessage, because I want to control how long I press a button, also I don't want to have the other application in the foreground. That's the reason I am not working with SendKeys.

回答1:

Several problems:

  • Your declaration is wrong, the last 2 parameters are IntPtr, not int
  • You should use PostMessage, not SendMessage
  • You are sending to the wrong window. The edit window of Notepad is a child window
  • You are forgetting to send WM_KEYUP
  • The actual letter you get will depend on the state of the Shift key

The neck shot: Vista and Win7 UIPI (User Interface Privilege Isolation) prevents a restricted process from injecting messages into an elevated process.