C#和SendMessage(键)不起作用
我试图将密钥发送到应用程序.为了进行简单的测试,我只使用了记事本.代码就是这样的:
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);
}
但是什么也没发生.
我的主要目标是将密钥发送到提升的应用程序,但是我很乐意首先将其发送到记事本. 我想使用SendMessage,因为我想控制按下按钮的时间,也不想在前台使用其他应用程序.这就是我不使用SendKeys的原因.
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.
几个问题:
- 您的声明有误,最后2个参数是IntPtr,而不是int
- 您应该使用PostMessage,而不是SendMessage
- 您发送到错误的窗口.记事本的编辑窗口是子窗口
- 您忘记发送WM_KEYUP
- 实际收到的字母取决于Shift键的状态
令人吃惊的是:Vista和Win7 UIPI(用户界面特权隔离)可防止受限制的进程向提升的进程中注入消息.
The neck shot: Vista and Win7 UIPI (User Interface Privilege Isolation) prevents a restricted process from injecting messages into an elevated process.