C# 无法将按键发送到C中正在运行的进程#
我使用下面的代码将焦点放在一个窗口上(在本例中是一个记事本窗口),并在每次单击按钮2时向其发送一些按键。然而,当我按下按钮2时,什么也没发生。有人能告诉我sendkeys命令失败的原因吗C# 无法将按键发送到C中正在运行的进程#,c#,winforms,sendkeys,C#,Winforms,Sendkeys,我使用下面的代码将焦点放在一个窗口上(在本例中是一个记事本窗口),并在每次单击按钮2时向其发送一些按键。然而,当我按下按钮2时,什么也没发生。有人能告诉我sendkeys命令失败的原因吗 public partial class Form1 : Form { [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private Process s;
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private Process s;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.s = new Process();
s.StartInfo.FileName = "notepad";
s.Start();
s.WaitForInputIdle();
}
private void button2_Click(object sender, EventArgs e)
{
ShowWindow(s.MainWindowHandle, 1);
SendKeys.SendWait("Hello");
}
}
ShowWindow
正在显示已启动的“记事本”,但没有为其提供输入焦点。发送sendkeys输出的表单正在接收它,Form1
ShowWindow
正在显示已启动的“记事本”,但没有给它输入焦点。发送sendkeys输出的表单正在接收sendkeys输出,Form1
事实证明,这就是问题所在。我没有正确设置记事本的焦距。应该使用命令SetForegroundWindow而不是ShowWindow
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
private Process s;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.s = new Process();
s.StartInfo.FileName = "notepad";
s.Start();
s.WaitForInputIdle();
}
private void button2_Click(object sender, EventArgs e)
{
//ShowWindow(s.MainWindowHandle, SW_RESTORE);
SetForegroundWindow(s.MainWindowHandle);
SendKeys.SendWait("Hello");
}
}
事实证明这就是问题所在。我没有正确设置记事本的焦距。应该使用命令SetForegroundWindow而不是ShowWindow
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
private Process s;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.s = new Process();
s.StartInfo.FileName = "notepad";
s.Start();
s.WaitForInputIdle();
}
private void button2_Click(object sender, EventArgs e)
{
//ShowWindow(s.MainWindowHandle, SW_RESTORE);
SetForegroundWindow(s.MainWindowHandle);
SendKeys.SendWait("Hello");
}
}