Click here to Skip to main content
13,904,776 members
Click here to Skip to main content
Add your own
alternative version


160 bookmarked
Posted 11 Apr 2007

Sending Keystrokes to another Application in C#

, 11 Apr 2007
Rate this:
Please Sign up or sign in to vote.
Showing dotNet SendKeys functionality

Screenshot - SendKeys.jpg


Sometimes in the life of a developer, a need arises to control another application from his/her application. It may be to provide automation services, to give control or for the ease of use of customers who are not very computer savvy.

There are many different tools and technologies available these days to accomplish that kind of automation. Integration between applications depends on the services that applications can expose or provide. For example, in the good days on Windows 3.1, Data Dynamic Exchange (<stockticker>DDE) or some screen scrapping techniques were used to accomplish that. <stockticker>DDE utilized the basic Windows Messaging Layer functionality. Since the <stockticker>DDE was limited to transferring data between two running applications, with the emergence of Object Linking and Embedding (OLE) automation became more prominent to these integration tasks with much confidence. OLE became the backbone for technologies such as Component Object Model (COM). Now-a-days different applications provide their object models to achieve the same kind of integration services. A good example of it would be the Microsoft Office line of products. Microsoft Office such as Excel or Word provide their object models to integrate with them.

But still from time to time there are applications which do not provide or expose any of the above mentioned techniques that can be utilized to do the integration with them. The only way to control these kinds of applications is emulating keystrokes to them to make them act as they would if they were in focus and taking keyboard input.

This small sample application shows how to accomplish this emulation of sending keystrokes to applications using Microsoft .NET Framework using C#.

SendKeys Application

This is very simple WinForm application, which basically utilizes .<stockticker>NET 2.0 SendKeys class to do most of its work. SendKeys class is defined in System.Windows.Forms namespace. One issue with the SendKeys class is it can only send keystrokes to the active application. Active application is the one which is in focus to accept keyboard input. To make any Windows active from another application we have to take help from the Windows native <stockticker>API SetForegroundWindow. SetForegroundWindow requires the Windows handle to bring it to the front. To get the Window handle I use yet another native <stockticker>API FindWindow. FindWindow takes two arguments, the first is the pointer to a null-terminated string that specifies the class name used to register the Window class and if this is null then the second argument is a Pointer to a null-terminated string that specifies the Window name (the Window's title).

int iHandle = NativeWin32.FindWindow(null, txtTitle.Text);

Windows native APIs can be incorporated into a .NET application via PInvoke. PInvoke functionality is by inclusion of System.Runtime.InteropServices namespace. Adding the Windows native APIs signature could be a daunting task specially if you do not have background and/or experience in C++ development. To facilitate this task some good guys brought up a very good site that can get you a jump start. In this project NativeWin32 class provides encapsulation for the Windows native <stockticker>API and also exposes their functionality.

As you have some idea about the driving force for this application creation, I will now explain the usability of the application for your reference.

When you launch this application it will display a single Winform as shown with an Auto radio button selected. This 'Auto' selection shows a combobox under 'Windows Title' filling up with all the top level Windows applications running on the machine. This service is only provided for ease of use. You can select 'Manual' which would display a text box to type the Windows title of the application you want to send keys to.

The 'Refresh' link would help to update the combobox entries to the currently running Windows. To update the combobox with the currently running applications, we again take a simple approach and call the native Windows API as shown below:

/// <summary>
/// Get all the top level visible Windows
/// </summary>
private void GetTaskWindows()
    // Get the desktopwindow handle
    int nDeshWndHandle = NativeWin32.GetDesktopWindow();
    // Get the first child window
    int nChildHandle = NativeWin32.GetWindow(nDeshWndHandle, 
    while (nChildHandle != 0)
        //If the child window is this (SendKeys) application then ignore it.
        if (nChildHandle == this.Handle.ToInt32())
            nChildHandle = NativeWin32.GetWindow
                (nChildHandle, NativeWin32.GW_HWNDNEXT);

        // Get only visible windows
        if (NativeWin32.IsWindowVisible(nChildHandle) != 0)
            StringBuilder sbTitle = new StringBuilder(1024);
            // Read the Title bar text on the windows to put in combobox
            NativeWin32.GetWindowText(nChildHandle, sbTitle, sbTitle.Capacity);
            String sWinTitle = sbTitle.ToString();
                if (sWinTitle.Length > 0)
        // Look for the next child.
         nChildHandle = NativeWin32.GetWindow(nChildHandle, 

Once the Window is decided with either of above defined way, you can select keys you want to send from the 'All Keys' listbox and press the 'Add' link to add them into the 'Keys to Send' listbox. 'All Keys' listbox displays all the possible keys that are supported and can be sent out to other applications. You can select multiple keys at the same time with the normal selection behavior provided by the listbox. One caveat to be aware of though, the selection with the added sequence from the 'All Keys' as they appear in the listbox and not as the order of your selection. Order of selection functionality can be added with ease but I leave it as an exercise to the readers.

'LoadKeys' and 'SaveKeys' give the serialization and deserialization abilities for the keys displayed in 'Keys to Send' listbox. 'Delete' link helps in removing selected keys from the 'Keys to Send' listbox.

'Replicate' link provides the functionality to multiple the keystroke 'n' times of the selected keys from the 'Keys to Send' listbox. Again the selection will multiply in sequential order.

After setting all these, pressing the 'Send Keys' button would activate the application matching with the Windows title and start sending keystrokes as someone is using a keyboard to that application.

Application Extension Possibilities

This application gives you a general idea on how to use sending keystrokes mechanism to another application. One possible extension to this approach could be sending keystrokes to multiple applications at the same time by extending the selection of multiple applications by using listbox rather then combobox.


  • April 11th, 2007


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Ali Zamurad
Web Developer
United States United States
Ali Zamurad is a software architect and a developer. He holds Bachelor degree in Computer Science and a Bachelor of Science with honor in Physics. He has been providing software solutions, consulting services and mentoring since 1992. He has experience with a broad spectum of software development tools and languages ranges from C, C++, Visual Basic and C# to name a few.

You may also be interested in...


Comments and Discussions

QuestionWith wpf the application does not work Pin
danbenedek16-Apr-12 22:00
memberdanbenedek16-Apr-12 22:00 
AnswerRe: With wpf the application does not work Pin
Nic_Roche12-Jul-12 10:42
professionalNic_Roche12-Jul-12 10:42 
QuestionCombined sends don't seem to work Pin
realcellar12-Apr-12 3:16
memberrealcellar12-Apr-12 3:16 
AnswerRe: Combined sends don't seem to work Pin
Moch Lutfi30-Apr-12 23:19
memberMoch Lutfi30-Apr-12 23:19 
QuestionDo not lose focus Pin
demelot4-Jan-12 7:54
memberdemelot4-Jan-12 7:54 
AnswerRe: Do not lose focus Pin
James Hanson17-Jan-14 2:45
memberJames Hanson17-Jan-14 2:45 
QuestionI really like this article. Pin
Nitin Kumar Chaudhary21-Dec-11 2:21
memberNitin Kumar Chaudhary21-Dec-11 2:21 
Questionbring second application to foreground keep failing. Pin
Zhi Chen16-Nov-11 19:46
memberZhi Chen16-Nov-11 19:46 
This article is pretty good. Although I have question if anyone had tried Ali's extension

"One possible extension to this approach could be sending keystrokes to multiple applications at the same time by extending the selection of multiple applications by using listbox rather then combobox."

My understanding is that once the current application relinquish the focus right to another application, the "original" application cannot set the second application to foreground.

Essentially I want to have one application send two separate keystrokes to two separate application. One after the other. I am able to make the first application set to foreground and send keystroke; however, the attempt to bring the second application to foreground keep failing.

Does this make sense to anyone?

GeneralMy vote of 5 Pin
sv050512-Sep-11 4:20
membersv050512-Sep-11 4:20 
QuestionPGDN is missing a '{' in the source Pin
robvon15-Aug-11 18:15
memberrobvon15-Aug-11 18:15 
GeneralMy vote of 4 Pin
Omar Elsherif25-May-11 8:35
memberOmar Elsherif25-May-11 8:35 
QuestionHow to send example Pin
:::::nobodyCodesThat::::::3-Jan-11 11:04
member:::::nobodyCodesThat::::::3-Jan-11 11:04 
GeneralWait for child window that being opened Pin
qhuydtvtv25-Dec-10 5:26
memberqhuydtvtv25-Dec-10 5:26 
QuestionHelp needed Pin
omairiba27-Oct-10 0:21
memberomairiba27-Oct-10 0:21 
QuestionIt seems the demo exe not work on Windows 7. Why? Pin
brant_chen16-Oct-10 3:53
memberbrant_chen16-Oct-10 3:53 
GeneralTried using with Notepad and Word. Pin
km774-Oct-10 3:16
memberkm774-Oct-10 3:16 
Generalsend keys to DirectX games Pin
espin_andrei22-Dec-09 12:22
memberespin_andrei22-Dec-09 12:22 
GeneralDoesn't work? Try this Pin
minimice11-Oct-09 4:43
memberminimice11-Oct-09 4:43 
GeneralRe: Doesn't work? Try this Pin
masterLoki026-Oct-09 5:50
membermasterLoki026-Oct-09 5:50 
GeneralRe: Doesn't work? Try this Pin
Member 85430055-Jan-12 22:26
memberMember 85430055-Jan-12 22:26 
GeneralSmall typo Pin
bloggsie25-Sep-09 5:05
memberbloggsie25-Sep-09 5:05 
Generalextract of SendKeysToApps not working Pin
faltopar24-Jul-09 5:10
memberfaltopar24-Jul-09 5:10 
GeneralDoesn't work at all with MS Word, Excel, IE Pin
senglory16-May-09 19:50
membersenglory16-May-09 19:50 
Generalit doesn't work Pin
selcukyazar6-May-09 3:24
memberselcukyazar6-May-09 3:24 
Generalneed to send a "Tab" to Photoshop Pin
Member 396415919-Apr-09 12:39
memberMember 396415919-Apr-09 12:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190306.1 | Last Updated 11 Apr 2007
Article Copyright 2007 by Ali Zamurad
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid