Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending keystrokes to a program

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)
like image 817
Or Betzalel Avatar asked Apr 30 '10 11:04

Or Betzalel


People also ask

How do I send keystrokes to another app?

There are two methods to send keystrokes to an application: SendKeys. Send and SendKeys. SendWait. The difference between the two methods is that SendWait blocks the current thread when the keystroke is sent, waiting for a response, while Send doesn't.

How do you send keystrokes?

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)".

How do I automate a key press in Windows?

To automate any keypress, you can use the press command. To specify a single keyboard character, use the character itself. For example, to automate pressing the letter 'a', use the command "press a" (without quotes). Similarly, to press a sequence of keys just pass them in order.


2 Answers

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}");
like image 50
Kyle Rosendo Avatar answered Sep 19 '22 04:09

Kyle Rosendo


Take a look into the SendKeys class.

like image 29
Oliver Avatar answered Sep 20 '22 04:09

Oliver