我正在尝试使用SendMessage到记事本,以便可以在不使记事本成为活动窗口的情况下插入书面文本。
过去我使用来完成类似的操作SendText,但是这需要给予记事本以焦点。
SendText
现在,首先我要获取Windows句柄:
Process[] processes = Process.GetProcessesByName("notepad"); Console.WriteLine(processes[0].MainWindowHandle.ToString());
我已经确认它是记事本的正确手柄,与相同Windows Task Manager。
Windows Task Manager
[DllImport("User32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
从这里开始,我无法在所有实验中都使SendMessage正常工作。我走错了方向吗?
[DllImport("user32.dll", EntryPoint = "FindWindowEx")] public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("User32.dll")] public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam); private void button1_Click(object sender, EventArgs e) { Process [] notepads=Process.GetProcessesByName("notepad"); if(notepads.Length==0)return; if (notepads[0] != null) { IntPtr child= FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null); SendMessage(child, 0x000C, 0, textBox1.Text); } }
WM_SETTEXT = 0x000c