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)?
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.
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)".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With