向程序发送击键

Or *_*lel 9 c# keystroke sendkeys winforms

在窗口形式中,我做了一个按钮,我试图将它发送F1到特定窗口(例如FireFox,我的电脑等......)

我的问题是:

  • 我怎么用窗口的名字来做呢?(例如"Mozilla Firefox")
  • 我怎么用流程的名字来做?(例如firefox.exe)

Kyl*_*ndo 14

按窗口名称:

[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}");
Run Code Online (Sandbox Code Playgroud)

按流程名称:

Process proc = Process.GetProcessesByName("firefox")[0];
IntPtr ptrFF = proc.Handle;
SetForegroundWindow(ptrFF);
SendKeys.SendWait("{F1}");
Run Code Online (Sandbox Code Playgroud)