System windows forms sendkeys send

Today we are going to cover the topic on how to send keys to another application using C#.

Full Source Code is available at:

DevInDeep/SendKeys (github.com)

This guide is a continuation on our previous post. Last week we were talking about how to get the active window using C#. This time around we are going to send commands and keystrokes to an external application.

As a result, the user will be able to connect their custom C# application to another one. Or simply put, take control over it.

If you need a refresher on the subject, please follow this tutorial first.

Or, you can continue on the next segment here.

More DevInDeep Tutorials:

  • How to Scrape Web Page using C#
  • Face Mask Detection using ML.NET Model Builder and C#
  • How to implement Text Detection with C#

If you already know how to import the “User32.dll” and obtain the current active window, then you are all set to continue from here.

For the purposes of this demo, we are going to reuse the code from the ActiveWindowWatcher class.

In this second part, we are going to send keys to another application. Once we have the current active window, then we can send keystrokes or commands to it.

As an example, I am going to use Notepad. It’s perfect to demonstrate this demo. We can send different commands to open a file, or we can send a shortcut to close the application all together. However, Notepad also allows us to write custom text as well. So, we will connect our own text field to Notepad, and anything we write inside of it, it will be displayed there.

First things first. We are going to open Notepad. Then, we will obtain the handle of the main window. And afterwards, we are going to take control over the app from our C# code. We will send commands, for example Ctrl + O, Alt + F4 or send keyboard keystrokes. It will look just like the user is performing these operations through their physical keyboard.

Our Windows Forms C# application will control the work of Notepad. So, let’s see how we can achieve this. Remember this is all part of the Virtual Keyboard series that we are working towards.

In the first post we learned how to obtain the current active window. Now, we are going to learn how to send keys to another application (current active window). Basically, we are building a virtual keyboard. Because, that’s what a virtual keyboard does. It sends keystrokes to the currently active application/window.

But, let’s not be hasty. Let’s take each step as it comes. We are going to do one thing at a time. Let’s send keystrokes to another application first.

Send Keys to Another Application using C#
Send Keys to Another Application using C#

This is the demo application we are going to build. It is a standard Windows Forms, C# project. Once, the application is started it is running an instance of ActiveWindowWatcher.

activeWindowWatcher = new ActiveWindowWatcher(TimeSpan.FromSeconds(1));
activeWindowWatcher.ActiveWindowChanged += ActiveWindowChanged;
activeWindowWatcher.Start();

If you don’t have the code for this class, you can download it from here. Also make sure to check out the tutorial.

What this class does, is it captures the current active window every second. By clicking on the button Lock Window it will retrieve the current active windows application and save the Title and Handle of the window.

In our case, the app captured the Window Handle and Window Title of Notepad. It was able to do that via the ActiveWindowChanged event. This event is raised every time when a different window is active (comes into focus).

Here is the code for handling the event

private void ActiveWindowChanged(object sender, ActiveWindowChangedEventArgs e)
{
       activeWindow = ActiveWindowModel.Create(e.WindowHandle, e.WindowTitle);
       lblCurrentlyActiveWindow.Text = $"Active Window: {e.WindowTitle}";
}

activeWindow is a field inside the Form class that holds information about the current active application. So every time the focused application changes, this field will too.

By now, we have already obtained the active window. In our case, that would be the Notepad Application Window. Now it’s time to send some commands and/or keystrokes.

But, before we do that, let’s see what else do we need.

More DevInDeep Tutorials

  • Learn ML.NET from start to finish using C#

Import and Declare Win32 functions

In order to send keys to another application we need to obtain the main window handle. This is needed because, when we click on our application form, we are the ones getting the focus. As a result, the send keys function would send keystrokes to our app. And we don’t want that. So, when we click on a button hosted by our application, we would need to activate the window we want to send the keys to.

To do that we need to use the SetForegroundWindow function. According to the MSDN documentation, this User32.dll method, brings the thread that created the specified window into the foreground and activates the window. As a result, keyboard input is directed to the window, and various visual cues are changed for the user.

This is exactly what we need. When user press a button on our application, we are going to send keys to a particular window. But then, we also need the focus back on our application, in case we want to continue on sending keystrokes. This might not be the best explanation, but bare with me. Run the demo and you will see what I am talking about.

So, let’s declare the SetForegroundWindow function in our WindowAPI.cs.

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

public static void SetActiveWindow(IntPtr windowHandle) => SetForegroundWindow(windowHandle);

In this code block, we are importing SetForegroundWindow. You should always wrap these methods inside another one that is public, and that the client code can call. It is a good practice to wrap these methods into your own custom ones, because then you can handle any exception that comes your way. But, you can also use your own user defined types if needed. However, this is just an example, and we are not going to dig deep into best practices for this current scenario.

Send Keys Command

The SendKeys method is part of the System.Windows.Forms namespace. Please note that this can be used from Windows Forms or WPF. But, in the case of WPF applications, you do need to reference the System.Windows.Forms library. And you would also need to use the SendWait method instead of Send.

We are going to use WPF to build the Virtual Keyboard, so this change will be demonstrated in the next post.

Send Keys method is described as: Sends keystrokes to the active application. This is what we need, so let’s see how to use it. What follows is the C# implementation of the method

public static void SendKeys(IntPtr windowHandle, string key)
{
       if (SetForegroundWindow(windowHandle))
              System.Windows.Forms.SendKeys.Send(key);
}

In our WindowAPI.cs class we implement the SendKeys method. It takes a window handle which points to the main window of the application we want to send keys to.

Please note that in the definition of SendKeys method it says that the function sends keystrokes to the active application. This means that before we send the keys to the other application we must first activate its main window.

We do that by using the SetForegroundWindow method by providing the Window Handle of the Application we want to focus on. If the window is in focus then we simply use SendKeys.Send(key_to_send).

There is one more override of this function. Here is the C# code for it:

public static void SendKeys(IntPtr windowHandle, bool ctrlActive, bool altActive, string key)
{
       if (ctrlActive)
              SendKeys(windowHandle, "^{" + key.ToLower() + "}");
       else if (altActive)
              SendKeys(windowHandle, "%{" + key.ToLower() + "}");
       else
              SendKeys(windowHandle, "{" + key + "}");
}

This C# code block simply handles situations when user has pressed Ctrl or Alt.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses () have special meanings to SendKeys. To specify one of these characters, enclose it within braces ({})

  • SHIFT +
  • CTRL ^
  • ALT %

We can use this function when we want to execute Ctrl + O or Alt + F4 commands on the another application.

Send Keys to Another Application C#

Let’s now look at the code behind the Send button

private void btnSend_Click(object sender, EventArgs e) =>
     WindowAPI.SendKeys(activeWindow.WindowHandle,rbtCTRL.Checked,rbtALT.Checked, cboLetter.Text);

It is important to note, that the send button only sends commands to the active application. As you can see we still provide the window handle of the active application main window, but we also provide other information as well.

The second parameter, signals the method if the user has Control or Ctrl key/button active. The third parameter, signals if the Alt key is checked. Finally, we are sending the letter key code.

It may look a little bit weird how this code is wired up, but be patient. This examples leads us one step closer to building a proper virtual keyboard.

The idea behind this example is to see how we can execute shortcut commands. They should simulate the user pressing keyboard buttons such as: Ctrl + O, Ctrl + A, Alt + F4 and so on.

Key Press Event

The next C# code we are going to review is the one behind the KeyPress event handler of the text box.

private void txtText_KeyPress(object sender, KeyPressEventArgs e)
{
       WindowAPI.SendKeys(activeWindow.WindowHandle, e.KeyChar.ToString());
       WindowAPI.SetActiveWindow(Process.GetCurrentProcess().MainWindowHandle);
}

We want to be able to send any key stroke the user enters into our text field to Notepad. That is why we are handling KeyPress event.

This KeyPress event occurs when a character, space or backspace key is pressed while the control has the focus.

Once a Key Press event is dispatched on our main window under the text box control, we are sending that key to the active application. In our example that is Notepad. Notepad, will identify this as a user typing on the keyboard as well. Thus, it will display the characters we are inserting in our text box.

The second line of the code activates or puts focus back on our window. Because, if you remember, when sending keys to another application, the main window of that app must come into focus. So, if we focus there we will loose focus on our window, and thus we will loose focus of our text box control. As a result, right after we send the keys to Notepad, we are going to put the focus back on our main window. This will allow the user to continue typing.

The problem with this scenario is the constant window flickering. Or the constant focus transfer from one window to another. It’s distracting. This could put you off a little, but there is a solution. We will resolve this problem in our next and probably final post of these series.

How to detect File Content Change using C# – CODE-AI (devindeep.com)

Conclusion

In this article we saw How to Send Keys to Another Application in C#. Knowing how to use the Windows API and how to get the active window, combine it with the Send Keys functionality we described today, puts us very close to building a Virtual Keyboard.

There is one more thing to improve. And that is the constant flicking or focus transferring between applications. We will cover the issue and the fix in our next post.

  • With SendKeys (System.Windows.Forms), you’ll programmatically be able to simulate key pressed events with C# or VB, and the application will behave as if the user actually typed that character sequence or hit that particular hotkey; we’ll also cover special keys and focus / timing issues.

    Note: in Windows 8 / 7 / Vista, this won’t work on a UAC prompt and related credentials box.

  • Let’s first type some text: each letter will be handled by whatever control currently has the focus. Info // Optionally go to other field:
    SomeOtherField.Focus();
    // Add string at insertion point / over selected text:
    SendKeys.Send("This is a test...");
    The Send() method processes the string you passed immediately; to wait for a response from the program (like auto-populated database records matching input), use SendWait() instead.
  • System keys, modifiers, and navigation / editing keys have their own symbols.
    TOP ROW
    Escape {ESC}
    Function Keys {F1} … {F16}
    Print Screen {PRTSC}
    Break {BREAK}
    Help {HELP} (Depending on active app, could be F1 or Ctrl+F1)
    LOCK KEYS
    Caps lock {CAPSLOCK}
    Num Lock {NUMLOCK}
    Scroll Lock {SCROLLLOCK}
    NAVIGATION AND EDITING KEYS
    Tab {TAB}
    Backspace {BACKSPACE}, {BS}, or {BKSP}
    Validation {ENTER} or ~ (a tilde)
    Ins Or Insert {INSERT} or {INS}
    Delete {DELETE} or {DEL}
    Text Navigation {HOME} {END} {PGDN} for Page Down {PGUP} for Page Up
    Arrow Keys {UP} {RIGHT} {DOWN} {LEFT}
    NUMERIC OPERATOR KEYS (on keypad side, not numpad)
    Keypad Add {ADD}
    Keypad Subtract {SUBTRACT}
    Keypad Multiply {MULTIPLY}
    Keypad Divide {DIVIDE}
    MODIFIER KEYS
    Shift +
    Control (Ctrl) ^
    Alt %
  • To mimic a key press on Enter, for example, write this: SendKeys.Send("{ENTER}");
    // Or this:
    SendKeys.Send("~");
  • To repeat a key (pretend like user pressed it multiple times), use curly braces and an integer: // Go up 7 lines in a text area:
    SendKeys.Send("{UP 7}");
    // To type three times the letter 'w':
    SendKeys.Send("{w 3}");
  • To hit a specific keyboard shortcut, combine or exclude modifier keys: // Let us "Save As" in a classic-menu program with Alt+F,A
    SendKeys.Send("%(FA)");
    // Let's make text bold and type an "A": Ctrl+B, release, A
    SendKeys.Send("^BA");

    Note: modifier keys combinations (like Ctrl+Alt+Delete) will not have the expected result.

  • Practical example of SendKeys for ComboBox selected text with index change and focus moved.

Sending a key to another application can be a useful technique for automating tasks, especially in a test environment or for creating macros. There are several ways to achieve this in C#, including using the SendKeys class, P/Invoke and Windows API, and using an automation library like UI Automation. In this article, we will explore the different methods to send a key to another application in C# and their respective pros and cons.

Method 1: SendKeys Class

To send a key to another application using the SendKeys class in C#, you can follow these steps:

  1. First, add a reference to the System.Windows.Forms namespace.
using System.Windows.Forms;
  1. Use the SendKeys method to send a key to the active window.

This will send the «A» key to the active window.

  1. You can also send a combination of keys by using the «+» symbol to indicate the «Shift» key, «^» to indicate the «Control» key, and «%» to indicate the «Alt» key.
SendKeys.Send("^a"); // Sends Control+A
SendKeys.Send("%{F4}"); // Sends Alt+F4
  1. You can also send a key multiple times by using the «{n}» syntax, where «n» is the number of times to send the key.
SendKeys.Send("{BACKSPACE 5}"); // Sends Backspace 5 times
  1. If you need to send a key to a specific window, you can use the SetForegroundWindow method from the user32.dll library to bring the window to the front.
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

// Get the handle of the window you want to send keys to
IntPtr hWnd = FindWindow(null, "Window Title");

// Bring the window to the front
SetForegroundWindow(hWnd);

// Send the key to the window
SendKeys.Send("A");

These are just a few examples of how to use the SendKeys class to send keys to another application in C#. For more information and options, you can refer to the official Microsoft documentation.

Method 2: P/Invoke and Windows API

To send a key to another application in C# using P/Invoke and Windows API, you can use the SendMessage function from user32.dll library. This function sends the specified message to a window or windows. Here is how to do it:

  1. First, you need to define the constants and structures needed for the SendMessage function:
using System;
using System.Runtime.InteropServices;

public static class User32
{
    public const int WM_KEYDOWN = 0x0100;
    public const int WM_KEYUP = 0x0101;

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
}
  1. Next, you can use the FindWindow function from user32.dll to get the handle of the target window:
IntPtr handle = User32.FindWindow(null, "Window Title");

Replace «Window Title» with the title of the window you want to send the key to.

  1. After getting the handle of the target window, you can use the SendMessage function to send the key:
User32.SendMessage(handle, User32.WM_KEYDOWN, (IntPtr)Keys.A, IntPtr.Zero);
User32.SendMessage(handle, User32.WM_KEYUP, (IntPtr)Keys.A, IntPtr.Zero);

Replace Keys.A with the key you want to send. The first call sends a key down message and the second call sends a key up message.

That’s it! You have successfully sent a key to another application using P/Invoke and Windows API in C#.

Method 3: UI Automation Library

To send a key to another application using the UI Automation Library in C#, you can follow these steps:

  1. Get the handle of the target application window using the FindWindow function from the user32.dll library.
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

IntPtr hWnd = FindWindow(null, "Target Application Title");
  1. Get the AutomationElement object of the target application window using the AutomationElement.FromHandle method.
AutomationElement targetWindow = AutomationElement.FromHandle(hWnd);
  1. Find the target control within the target application window using the AutomationElement.FindFirst method.
Condition condition = new PropertyCondition(AutomationElement.NameProperty, "Target Control Name");
AutomationElement targetControl = targetWindow.FindFirst(TreeScope.Descendants, condition);
  1. Set the focus to the target control using the AutomationElement.SetFocus method.
targetControl.SetFocus();
  1. Send the key to the target control using the SendKeys.SendWait method.
SendKeys.SendWait("Key to Send");

Here’s the complete code example:

using System;
using System.Runtime.InteropServices;
using System.Windows.Automation;
using System.Windows.Forms;

public class KeySender
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    public static void SendKeyToTargetControl(string targetApplicationTitle, string targetControlName, string keyToSend)
    {
        IntPtr hWnd = FindWindow(null, targetApplicationTitle);
        AutomationElement targetWindow = AutomationElement.FromHandle(hWnd);
        Condition condition = new PropertyCondition(AutomationElement.NameProperty, targetControlName);
        AutomationElement targetControl = targetWindow.FindFirst(TreeScope.Descendants, condition);
        targetControl.SetFocus();
        SendKeys.SendWait(keyToSend);
    }
}

// Usage example:
KeySender.SendKeyToTargetControl("Target Application Title", "Target Control Name", "Key to Send");

OK turns out what you really want is this: http://inputsimulator.codeplex.com/

Which has done all the hard work of exposing the Win32 SendInput methods to C#. This allows you to directly send the windows key. This is tested and works:

InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

Note however that in some cases you want to specifically send the key to the application (such as ALT+F4), in which case use the Form library method. In others, you want to send it to the OS in general, use the above.


Old

Keeping this here for reference, it will not work in all operating systems, and will not always behave how you want. Note that you’re trying to send these key strokes to the app, and the OS usually intercepts them early. In the case of Windows 7 and Vista, too early (before the E is sent).

SendWait("^({ESC}E)") or Send("^({ESC}E)")

Note from here: http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx

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)». To specify to hold down SHIFT while
E is pressed, followed by C without SHIFT, use «+EC».

Note that since you want ESC and (say) E pressed at the same time, you need to enclose them in brackets.

Имитация ввода с клавиатуры.

7 декабря, 2010 Автор: Kazun

Для имитации ввода с клавиатуры можно воспользоваться несколькими методами.

1)Использование Com объектов.
Для этого воспользуемся методом SendKeys объекта Wscript.Shell.Клавиши,которые можно имитировать, можно посмотреть SendKeys.

#Создаем объект WScript.Shell
$wshell = New-Object -ComObject WScript.Shell 
#Нажимаем Enter
$wshell.SendKeys("{Enter}")

Подробнее по применение ,можно прочитать http://xaegr.wordpress.com/2007/03/30/send-keys/ .

2)Использование .Net.
Здесь мы можем работать с двумя классами System.Windows.Forms.SendKeys и методом Send или
SendWait.Разница,что SendWait — ожидает окончания обработки сообщений. И второй класс Microsoft.VisualBasic.Devices.Keyboard и метода SendKeys.

Используя класс System.Windows.Forms.SendKeys и статические методы Send,SendWait.

[System.Windows.Forms.SendKeys]::Send("{Enter}")
[System.Windows.Forms.SendKeys]::SendWait("{Enter}")

Используя класс Microsoft.VisualBasic.Devices.Keyboard.

#Загружаем сборку.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
#Создаем объект класса
$Comp = new-object Microsoft.VisualBasic.Devices.Computer
$Comp.KeyBoard.SendKeys("{ENTER}",$true)

Все рассматриваемые методы посылают имитацию нажатий в активное приложение,кроме текущего.
Для активации приложение можно воспользоваться методом AppActivate ,Interaction.AppActivate.

#Загружаем сборку.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
#Создаем объект класса
$Comp = new-object Microsoft.VisualBasic.Devices.Computer
#Получаем pid процесса cmd.exe
$id = (gps cmd).id
#Активируем приложение cmd.exe
[Microsoft.VisualBasic.Interaction]::AppActivate($id)
Start-Sleep 1
#Посылаем Enter.
$Comp.KeyBoard.SendKeys("{ENTER}",$true)
#Создаем объект WScript.Shell
$wshell = New-Object -ComObject WScript.Shell
#Получаем pid процесса cmd.exe 
$id = (gps cmd).id
#Активируем приложение
$wshell.AppActivate($id)
start-sleep 1
$wshell.SendKeys("{Enter}")
Start-Sleep 1

Опубликовано в PowerShell | Добавить комментарий

  • System windows forms messagebox system windows forms messagebox
  • System restore is disabled in windows
  • System windows forms messagebox show
  • System reset factory reset windows 10
  • System windows forms label powershell