User2012384
User2012384

Reputation: 4919

How to send a key to another application

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?

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 background, which means sending a key to a background application)?

Upvotes: 40

Views: 172325

Answers (3)

Allseeingindho
Allseeingindho

Reputation: 26

You can send anything by first copying into the clipboard and then paste the send keys ctrl+v:

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();

if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    Clipboard.Clear();
    Clipboard.SetText(txtCode.Text); 
    string strClip = Clipboard.GetText();
    SendKeys.Send("^{v}");
}

Upvotes: 0

Parsidic_thirst
Parsidic_thirst

Reputation: 11

    public string h1;
    public string h2;
    public string m1;
    public string m2;
    public string s1;
    public string s2;

   public partial class Form1 

    hours hour = new hours();
Sendkeys.SendWait(Convert.ToString(hour.h1+hour.h2+hour.m1+hour.m2+hour.s1+hour.s2              +" "));   

it is a simple matter of sending a classed string to the sendkey process using the convert to string procedure

Upvotes: 0

Moha Dehghan
Moha Dehghan

Reputation: 18443

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.

Upvotes: 73

Related Questions