4

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.

4

1 回答 1

10

几个问题:

  • 你的声明是错误的,最后两个参数是 IntPtr,而不是 int
  • 您应该使用 PostMessage,而不是 SendMessage
  • 您发送到错误的窗口。记事本的编辑窗口是子窗口
  • 您忘记发送 WM_KEYUP
  • 您得到的实际字母取决于 Shift 键的状态

颈部镜头:Vista 和 Win7 UIPI(用户界面特权隔离)可防止受限进程将消息注入提升的进程。

于 2010-06-20T19:00:29.973 回答