我正在尝试使用 SendMessage 到记事本,这样我就可以在不使记事本成为事件窗口的情况下插入书面文本。
我过去曾使用 SendText
做过类似的事情,但这需要给予记事本焦点。
现在,我首先要检索 Windows 句柄:
Process[] processes = Process.GetProcessesByName("notepad");
Console.WriteLine(processes[0].MainWindowHandle.ToString());
我已经确认它是记事本的正确句柄,与 Windows 任务管理器
中显示的相同。
[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
关于c# - 如何在 C#/Win32 中将文本发送到记事本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/523405/