Simulating a keystroke in Win32 (C or C++) using SendInput

This program is a simple example of using the Win32 SendInput function to generate a simulated keystroke. When you run this program, it simply waits 5 seconds and then simulates a press and release of the “A” key on the keyboard.

Here’s the complete source code.

//
// keystroke.c - Pauses, then simulates a key press
// and release of the "A" key.
//
// Written by Ted Burke - last updated 17-4-2012
//
// To compile with MinGW:
//
//		gcc -o keystroke.exe keystroke.c
//
// To run the program:
//
//		keystroke.exe
//
// ...then switch to e.g. a Notepad window and wait
// 5 seconds for the A key to be magically pressed.
//

// Because the SendInput function is only supported in
// Windows 2000 and later, WINVER needs to be set as
// follows so that SendInput gets defined when windows.h
// is included below.
#define WINVER 0x0500
#include <windows.h>

int main()
{
	// This structure will be used to create the keyboard
	// input event.
	INPUT ip;

	// Pause for 5 seconds.
	Sleep(5000);

	// Set up a generic keyboard event.
	ip.type = INPUT_KEYBOARD;
	ip.ki.wScan = 0; // hardware scan code for key
	ip.ki.time = 0;
	ip.ki.dwExtraInfo = 0;

	// Press the "A" key
	ip.ki.wVk = 0x41; // virtual-key code for the "a" key
	ip.ki.dwFlags = 0; // 0 for key press
	SendInput(1, &ip, sizeof(INPUT));

	// Release the "A" key
	ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
	SendInput(1, &ip, sizeof(INPUT));

	// Exit normally
	return 0;
}

Here’s a screenshot of the console window where I compiled and ran the program.

As soon as I ran the program in the console window, I switched the focus to a Notepad window where the simulated keystroke typed a character, as shown in the following screenshot.

About these ads
This entry was posted in Uncategorized and tagged , , , , , , . Bookmark the permalink.

25 Responses to Simulating a keystroke in Win32 (C or C++) using SendInput

  1. bram geelen says:

    where can I find the different key codes for different buttons? like 0×41, but for other keys :D

    • batchloaf says:

      Hi Bram,

      Here’s a link to the list of virtual key codes on Microsoft’s MSDN website.

      There is an alternative way of filling the keyboard event structure where you specify the key as a unicode character rather than as a virtual key code. For example, you could simulate pressing the ‘d’ key, with something like the following:

          INPUT ip;
          ip.type = INPUT_KEYBOARD;
          ip.ki.time = 0;
          ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a unicode character
          ip.ki.wScan = 'd'; // Which keypress to simulate
          ip.ki.wVk = 0;
          ip.ki.dwExtraInfo = 0;
          SendInput(1, &ip, sizeof(INPUT));
      

      I think you still need to use virtual key codes sometimes though to simulate the special keys on the keyboard, so it’s best to know both ways.

      • bram geelen says:

        thanks for the link!
        However, when I try to compile, I get errors that both INPUT and ip are undeclared.

        D:\eclipse workspace>gcc -o keystroke.exe keystroke.c
        keystroke.c: In function `main’:
        keystroke.c:25: `INPUT’ undeclared (first use in this function)
        keystroke.c:25: (Each undeclared identifier is reported only once
        keystroke.c:25: for each function it appears in.)
        keystroke.c:25: parse error before `ip’
        keystroke.c:32: `ip’ undeclared (first use in this function)
        keystroke.c:32: `INPUT_KEYBOARD’ undeclared (first use in this function)

        do I need to compile with a VS compiler?

      • batchloaf says:

        No, you shouldn’t need to use the VC++ compiler. I’m using gcc myself. It’s the version installed with MinGW. Are you using MinGW too?

        Did you definitely include both of the following lines at the start of your program?

            #define WINVER 0x0500
            #include <windows.h>
        

        The SendInput function (and some related stuff) is defined in a header file that gets included by windows.h. However, the definitions are dependent on the versions of Windows that your compiling for. That’s why the WINVER definition line must come before windows.h is inluded. Basically, it makes sure that windows.h will include all the relevant stuff. If you don’t set WINVER before including windows.h, gcc thinks you want to compile a program that will also be compatible wiith older versions of Windows that didn’t support SendInput etc.

        If that’s not the solution, let me know and I’ll see if I can work out why it’s not working for you.

        Here’s a complete main.c example using the second (unicode) form of SendInput:

        #define WINVER 0x0500
        #include <windows.h>
        
        int main()
        {
        	// Pause for 5 seconds.
        	Sleep(5000);
        
        	// Create input event
        	INPUT ip;
        	ip.type = INPUT_KEYBOARD;
        	ip.ki.time = 0;
        	ip.ki.dwFlags = KEYEVENTF_UNICODE;
        	ip.ki.wScan = 'd';
        	ip.ki.wVk = 0;
        	ip.ki.dwExtraInfo = 0;
        	SendInput(1, &ip, sizeof(INPUT));
        
        	// Exit normally
        	return 0;
        }
        
  2. bram geelen says:

    Thanks! that worked wonderfully!

  3. pyroesp says:

    Hey, thanks for the piece of code. It’s just what I was looking for (hate all that C++ and C# things).
    It’s pretty easy to understand.

    I played with it a bit and I can send a ‘CTRL+V’ command.
    Thanks again for the code !

  4. Cody Baldwin says:

    Wow, exactly what I needed and nice easy to read code. A+ from a fellow C++ programmer!

  5. Pingback: Boot Straight to Desktop in Windows 8 | Black-Pixel

  6. Saravana Kumar p says:

    Can anybody please tell me how to send a key to a window which is not in focus?
    Thanks in advance

  7. Shoxolat says:

    Thanks you for the code. It’s just what I was looking for.

  8. This site was… how do you say it? Relevant!! Finally I’ve found something that
    helped me. Thanks!

  9. Sumit Agrawal says:

    Thank you one of the simplest,Error Less example on net I found

  10. Bob Taylor says:

    Laser sharp. No errors. when compiled as advised.

  11. I was able to use your code to send space bar to games, such as Counter Strike and Icy Tower however I am having a problem with sending the arrows, when trying to simulate the arrows it worked in Notepad and I got it to arrow up and in Counter Strike main menu it kept on arrowing up, while when I tried it in gameplay nothing happened.

    I tried using both Virtual keys and hardware scan codes, but with no luck.

  12. Nadsa says:

    Exactly what I needed… Thanks a lot..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s