C# using Sendkey function to send a key to another application

User2012384 picture User2012384 · Mar 8, 2013 · Viewed 126k times · Source

I want to send a specific key (e.g. k) to another program named notepad, and below is the code that I used:

private void SendKey()
{
    [DllImport ("User32.dll")]
    static extern int SetForegroundWindow(IntPtr point);

    var p = Process.GetProcessesByName("notepad")[0];
    var pointer = p.Handle;

    SetForegroundWindow(pointer);
    SendKeys.Send("k");
}

But the code doesn't work, what's wrong with the code?

Edited: Is it possible that I send the "K" to the notepad without notepad to be the active window? (e.g. active window = "Google chrome", notepad is in the backgound, which means sending a key to a background application)

Answer

Mohammad Dehghan picture Mohammad Dehghan · Mar 8, 2013

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.