向程序发送按键输入

9

在Windows窗体中,我创建了一个按钮,并试图使它发送F1到特定的窗口(例如Firefox,我的电脑等)。

我的问题是:

  • 如何通过窗口名称实现?(例如“Mozilla Firefox”)
  • 如何通过进程名称实现?(例如firefox.exe)
2个回答

15

按窗口名称:

[DllImport("User32.dll")] 
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
[DllImport("User32.dll")] 
static extern int SetForegroundWindow(IntPtr hWnd);

IntPtr ptrFF = FindWindow(null, "Mozilla Firefox");
SetForegroundWindow(ptrFF);
SendKeys.SendWait("{F1}");
按进程名称:
Process proc = Process.GetProcessesByName("firefox")[0];
IntPtr ptrFF = proc.Handle;
SetForegroundWindow(ptrFF);
SendKeys.SendWait("{F1}");

@Or Betzalel - 已更新进程名称。 - Kyle Rosendo
为了社区文档目的。根据我的经验,“IntPtr ptrFF = proc.Handle;”将无法获取正确的句柄。您应该使用proc.MainWindowHandle。通过使用Spy++确保这是正确的。 - astonish

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接