9

In window form, I made a button and I'm trying to make it send F1 to a specific window (Such as FireFox, My Computer, etc...)

My questions are :

  • How do I do it by the window's name? (such as "Mozilla Firefox")
  • How do I do it by the process's name? (such as firefox.exe)
Oliver
  • 43,366
  • 8
  • 94
  • 151
Or Betzalel
  • 2,427
  • 11
  • 47
  • 70

2 Answers2

15

By Window name:

[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}");

By Process name:

Process proc = Process.GetProcessesByName("firefox")[0];
IntPtr ptrFF = proc.Handle;
SetForegroundWindow(ptrFF);
SendKeys.SendWait("{F1}");
Matt
  • 74,352
  • 26
  • 153
  • 180
Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118
  • @Or Betzalel - Updated with process name. – Kyle Rosendo Apr 30 '10 at 11:37
  • For community documentation purposes. From my experience "IntPtr ptrFF = proc.Handle;" will not grab the right handle. You should be using proc.MainWindowHandle instead. Ensure this is correct by using Spy++ – astonish Aug 29 '13 at 14:28
1

Take a look into the SendKeys class.

Oliver
  • 43,366
  • 8
  • 94
  • 151