Sending keystrokes to a program

14,183

Solution 1

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

Solution 2

Take a look into the SendKeys class.

Share:
14,183

Related videos on Youtube

Or Betzalel
Author by

Or Betzalel

I am a beginner programmer in asp.net 3.5.

Updated on April 20, 2022

Comments

  • Or Betzalel
    Or Betzalel about 2 years

    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)
  • Kyle Rosendo
    Kyle Rosendo about 14 years
    @Or Betzalel - Updated with process name.
  • astonish
    astonish almost 11 years
    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++