C # and SendMessage (keys) not working

I tried to send the key to the application. For an easy test, I just used a notebook. 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 the application with elevated rights, but I will gladly send it to notepad. I want to work with SendMessage because I want to control how long I press the button, also I do not want another application to be in the foreground. This is the reason I am not working with SendKeys.

+3
c # pinvoke sendmessage
source share
1 answer

A few problems:

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

Neck shot: Vista and Win7 UIPI (Isolation of User Interface Privileges) prevent injection messages from entering an elevated process.

+8
source share

All Articles