Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a key to another application

Tags:

c#

sendkeys

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)?

like image 436
User2012384 Avatar asked Mar 08 '13 10:03

User2012384


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 SendKeys?

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 you send keys in VBA?

Using the SendKeys Method You can use the SendKeys method in your Excel macros VBA code, to simulate keystrokes that you would manually input in the active window. The Keys argument is required, and is the key or keys that you want to send to the application, as text. The Wait option is optional.


1 Answers

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.

like image 105
Mohammad Dehghan Avatar answered Oct 29 '22 22:10

Mohammad Dehghan