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

This short example program simulates pressing Ctrl-V on the keyboard (the Windows shortcut for “Paste”) once every second. It’s a modified version of an earlier example I posted on keystroke simulation using the Win32 SendInput function. What’s different this time is that the effect of holding down the control key while pressing another key is simulated.

Basically, each “Ctrl-V” is simulated in four steps:

  1. Press the Control key
  2. Press the V key
  3. Release the V key
  4. Release the Control key

I compiled this example using the gcc compiler (from MinGW), but I think it should work fine in Visual C++ (or similar).

//
// ctrlv.c - Simulates pressing Ctrl-V once a second
//
// Written by Ted Burke - last updated 18-10-2012
//
// To compile with MinGW:
//
//		gcc -o ctrlv.exe ctrlv.c
//
// To run the program:
//
//		ctrlv.exe
//

// 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()
{
	// Create a generic keyboard event structure
	INPUT ip;
	ip.type = INPUT_KEYBOARD;
	ip.ki.wScan = 0;
	ip.ki.time = 0;
	ip.ki.dwExtraInfo = 0;

	while(1)
	{
		// Press the "Ctrl" key
		ip.ki.wVk = VK_CONTROL;
		ip.ki.dwFlags = 0; // 0 for key press
		SendInput(1, &ip, sizeof(INPUT));

		// Press the "V" key
		ip.ki.wVk = 'V';
		ip.ki.dwFlags = 0; // 0 for key press
		SendInput(1, &ip, sizeof(INPUT));

		// Release the "V" key
		ip.ki.wVk = 'V';
		ip.ki.dwFlags = KEYEVENTF_KEYUP;
		SendInput(1, &ip, sizeof(INPUT));

		// Release the "Ctrl" key
		ip.ki.wVk = VK_CONTROL;
		ip.ki.dwFlags = KEYEVENTF_KEYUP;
		SendInput(1, &ip, sizeof(INPUT));
		
		Sleep(1000); // pause for 1 second
	}

	// We won't actually ever reach this point
	return 0;
}

To try it out:

  1. Open Notepad,
  2. Type a word and then copy it to the clipboard,
  3. Switch to a console window and run ctrlv.exe,
  4. Switch back to Notepad and you should see the word pasted repeatedly, once a second.
  5. Switch back to the console and press Ctrl-C to stop ctrlv.exe.
Advertisements
This entry was posted in Uncategorized and tagged , , , , , , , , . Bookmark the permalink.

44 Responses to Simulating a Ctrl-V keystroke in Win32 (C or C++) using SendInput

  1. Arivu says:

    ip.ki.wVk = ‘V’;
    ip.ki.dwFlags = 0; // 0 for key press
    SendInput(1, &ip, sizeof(INPUT));

    In the above code snippet you have used ‘V’ directly. Can we use a key directly in quotes other than entering its virtual key code(like 0x41 for ‘a’ as in previous example)???

    • batchloaf says:

      Hi Arivu,

      Actually, this is an interesting point. The virtual key codes for letter and number keys are equal to the ASCII value of the corresponding characters. In C, when you write a letter (or digit) in single quotes, it is treated as a char value (i.e. basically an 8-bit int) with the value of the corresponding ASCII character.

      For example, the character ‘A’ has an ASCII value of 0x41 (in hexadecimal). Therefore, if one writes the following in C, then x, y and z all end up equal to exactly the same value:

      int x, y, z;
      x = 65;   // decimal
      y = 0x41; // hex
      z = 'A';  // character
      

      For convenience, the virtual key code for each letter keys has been chosen to be equal to the ASCII value of the corresponding capital letter. You can therefore set ip.ki.wVk equal to ‘V’, VK_KEY_V, 0x56, or 86. It won’t make any difference which one you use. The same is also true for number keys.

      Ted

  2. The whole point of SendInput over keybd_event is that you can place an array of input messages on the queue. They way you have done it allows other input events to appear in between your sequence. You need to create an array of 4 INPUT structs and blat them all in one single call to SendInput.

  3. Scott says:

    I’m using your code to simulate key press. But I’m doing it in a plugin (not a console) type scenario. I’m using it to close a window in my program using a plugin.

    It works, and it does close the window. But the problem is that the key press code keeps on executing. Even if my plugin and it’s host program is no longer running. Ouch!
    If I do a Ctrl+Alt+Del and then Cancel. It fixes the problem.

    I can’t figure out why SendInput() keeps on running even when the program is closed. It’s very odd.
    Is there a way to manually flush SendInput() or stop it?

    -ScottA

    • Scott says:

      Oh Shoot.
      Never mind. I found my mistake.
      -ScottA

    • batchloaf says:

      Hi Scott,

      Wow, that’s a weird problem!! What kind of plugin is it? Is it a browser plugin or something? I have no idea how this could be happening, but I suspect it must be something to do with the plugin code being executed multiple times. I don’t think there’s anything in the SendInput code that could result in sending the keystroke multiple times. I’ll do a quick google to see if this is an isolted occurence.

      Ted

  4. Lny says:

    Hey Ted,

    could it be that the “keep button down/pressed” scenario only works with the control keys like CTRL / ALT / ALTGR and so on? I have the same code as you do but without the sequence for CTRL-key and a delay added between the two V-key calls. But still the V-key is pressed just momentary.

    (MinGW @ Win7)

    Lny

    • batchloaf says:

      Hi Lny,

      I’m pretty sure the separate key down / key up events apply to normal keys as well as Ctrl / Alt etc. However, I’m not sure whether, for example, the key will autorepeat while held pressed down this way. Is there a specific reason you need to hold down a key?

      Ted

      • Lny says:

        Hello Ted,

        I build this: http://goo.gl/168eiK Its an SNES controller with a bluetooth module. It gets connected to my android phone and talks to an app called Amarino (http://www.amarino-toolkit.net/) via a pretty simple protocol. I implemented it on an AVR (Attiny2313) and it talks fine to Easymote app (which converts the serial stream to keyboard presses). But enought about this.

        Why I need held buttons is that I want to use my controller with my PC as well. I’m not so deep into C and especially not into Android (just using what other programmed).

        To come straight to the point: If I press the forward button on the controller, the corresponding key on the keyboard need to be pressd as long as the button is being pressed.

        Lny

      • batchloaf says:

        Hi Lny,

        Maybe you need to simulate the effect of auto-repeat when you physically press a key by generating a long stream of key down (and maybe key up) events? I actually don’t really understand what happens when a key auto-repeats, but I expect a series of key stroke events are generated and processed as individual key presses by the receiving application. Seems like it might be worth a try anyway.

        Ted

  5. chakravarty says:

    Hi there! Thanks for the example. I am trying to do “Alt+f” (to open file menu on notepad) but it doesn’t seem to be working. I just replaces VK_MENU for VK_CONTROL and ‘f’ for ‘V’ in your above code. Appreciate your help on this

    • batchloaf says:

      Hi Chakravarty,

      The virtual key codes for letter keys have the same value as the ascii value of the corresponding capital letter. Therefore, the virtual key code for the F key is ‘F’ rather than ‘f’. Try using that instead as shown in the example below:

              // Press the "Alt" key
              ip.ki.wVk = VK_MENU;
              ip.ki.dwFlags = 0; // 0 for key press
              SendInput(1, &ip, sizeof(INPUT));
       
              // Press the "F" key
              ip.ki.wVk = 'F';
              ip.ki.dwFlags = 0; // 0 for key press
              SendInput(1, &ip, sizeof(INPUT));
       
              // Release the "F" key
              ip.ki.wVk = 'F';
              ip.ki.dwFlags = KEYEVENTF_KEYUP;
              SendInput(1, &ip, sizeof(INPUT));
       
              // Release the "Alt" key
              ip.ki.wVk = VK_MENU;
              ip.ki.dwFlags = KEYEVENTF_KEYUP;
              SendInput(1, &ip, sizeof(INPUT));
      

      If that still doesn’t work, I suggest trying VK_LMENU instead of VK_MENU. Apparently, there are separate virtual key codes for the left and right ALT keys. VK_MENU is probably fine though.

      Ted

  6. suma says:

    Thanks Ted, that worked.

  7. Krishna says:

    Can I use this to simulate ACPI hot kye combinations of alt+ctrl+shift+F1?

  8. Partha D says:

    I need to hook Alt and Cntrl key. the situation is when the user press Cntrl+Y, or Alt+Y or Cntrl+Alt+Y, I need to send ‘w’,’e’ and ‘r’ to the active window( say notepad). I am able to to hook the keyboard but whenever I send the characters to the active window it doesn’t show up( in notepad say). But to my surprise if the active window is any Qt based editor the n I can see the desired output. I even saw it in the Qt creator IDE code editor. Can you show me how to do it using C++.

    • batchloaf says:

      Hi Partha,

      Sending normal keystrokes (e.g. ‘w’, ‘e’, ‘r’) to a normal window (e.g. Notepad) using SendInput (in C/C++) was the topic of the earlier post I mentioned (and linked to) in this article. Here’s the link again:

      https://batchloaf.wordpress.com/2012/04/17/simulating-a-keystroke-in-win32-c-or-c-using-sendinput/

      Based my own experience, that approach works reliably for normal keystrokes in normal windows (like Notepad). However, others have left comments here which suggest that it won’t work for certain ‘special’ types of windows. In particular, some games seem to deliberately prevent people from simulating keystrokes, presumably to prevent cheating.

      Ted

      • Partha D says:

        Thanks for the quick reply. I will have a look at it. I don’t need any special window. I am developing a language input tool ( for Bangla language) where I need to show Unicode Bangla characters when the user presses english letters on the keyboard. SO the tool should work for notepad, word etc.

  9. Partha D says:

    Hi batchloaf , my problem is not with normal keystrokes but with Alt+key/Cntrl+key or Cntrl+Alt+key. If I don’t use these modifier keys then the output is fine. But whenever these modifier keys are used I dn’t see the output on the screen. Can you give my an example project on my situation as mentioned in my first post. Eagerly waiting for it

    • batchloaf says:

      Hi Partha,

      I currently don’t have Windows installed on either of my laptops, so I can’t try generating this kind of keystroke myself just now. However, I can make two suggestions:

      • The SendInput function does allow you to set flags for “modifier keys” (such as Ctrl or Alt) when you generate a keystroke, so it should be possible to add those flags to your keystroke. I would expect this to work for something like cutting (Ctrl-X) or pasting (Ctrl-Y), but maybe not for special characters (e.g. Bangla) which are presumably dependent on regional keyboard settings. I suppose it’s worth a try though.
      • The good news is that I think SendInput can explicitly specify the unicode value of a keyboard event, which would allow you to specify the Bangla characters directly rather than using a special keyboard combination. Can you give me an example of a typical Bangla character and its unicode value that I can try out?

      If I get a chance to try this on someone else’s Windows PC today, I’ll give it a whirl. No guarantees though – I have a very busy day ahead of me!

      It sounds like an interesting application you’re working on by the way – I’d be interested to know more about.

      Ted

  10. Partha D says:

    Yes, I am using a similar code for the hook dll for generating unicode characters. The user can write just fine without any problem. The problem arises in case of Alt/Cntrl + the keys combinations. When I try to output these nothing shows up in the active window

  11. Partha D says:

    any update on the alt key thing?

    • batchloaf says:

      Hi Partha,

      I have verified that I can generate unicode keystrokes without difficulty, as shown in this example which I’ve just posted:

      Using SendInput to type unicode characters

      However, I just want to clarify what it is you’re trying to do because maybe I am not understanding it correctly.

      If you just want to do things like “Alt-K” generates “খ” then maybe you can use my simple example program and set up a windows keyboard shortcut to run the program every time Alt-K is pressed? It’s not a very elegant solution, but if you only need to do it for a few unicode characters, maybe it would work?

      Ted

  12. datt's says:

    hey i just want to send keystroke in manner “hello” rather than first code for character ‘h’ and than ‘e’…… so that’s possible if possible then can u help me?

    • batchloaf says:

      Hi datt’s,

      You can create an array of INPUT structures to press and release a whole sequence of keys, then use the SendInput structure to process them all in one go. Is that what you mean?

      Here’s an example. (Disclaimer: I haven’t been able to test this myself because I’m not on a Windows machine.)

      //
      // sendhello.c - Simulates typing "hello" using SendInput
      //
      // Written by Ted Burke - last updated 11-8-2016
      //
      // To compile with MinGW:
      //
      //      gcc -o sendhello.exe sendhello.c
      //
      // To run the program:
      //
      //      sendhello.exe
      //
       
      // 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()
      {
          // Create an array of generic keyboard INPUT structures
          INPUT ip[10];
          for (n=0 ; n<10 ; ++n)
          {
              ip.type = INPUT_KEYBOARD;
              ip.ki.wScan = 0;
              ip.ki.time = 0;
              ip.ki.dwFlags = 0; // 0 for key press
              ip.ki.dwExtraInfo = 0;
          }
          
          // Now we need to adjust each INPUT structure so that
          // the whole sequence is equivalent to typing "hello".
          // Note that every second structure must be changed
          // from a key press to a key release.
          
          // INPUT structures to press and release the 'H' key
          ip[0].ki.wVk = 'H';
          ip[1].ki.wVk = 'H';
          ip[1].ki.dwFlags = KEYEVENTF_KEYUP;
          // INPUT structures to press and release the 'E' key
          ip[2].ki.wVk = 'E';
          ip[3].ki.wVk = 'E';
          ip[3].ki.dwFlags = KEYEVENTF_KEYUP;
          // INPUT structures to press and release the 'L' key
          ip[4].ki.wVk = 'L';
          ip[5].ki.wVk = 'L';
          ip[5].ki.dwFlags = KEYEVENTF_KEYUP;
          // INPUT structures to press and release the 'L' key
          ip[6].ki.wVk = 'L';
          ip[7].ki.wVk = 'L';
          ip[7].ki.dwFlags = KEYEVENTF_KEYUP;
          // INPUT structures to press and release the 'O' key
          ip[8].ki.wVk = 'O';
          ip[9].ki.wVk = 'O'; 
          ip[9].ki.dwFlags = KEYEVENTF_KEYUP;
          
          // Send all 10 INPUT structures to type the word
          SendInput(10, ip, sizeof(INPUT));
           
          // The End
          return 0;
      }
      

      If you’re going to be sending lots of different words at different times, you could wrap something like this up in a function that receives a string as its argument and then automatically generates the INPUT structures to type each character in the string.

      Hope that helps.

      Ted

  13. yujin says:

    thanks a lot. this article is really helpful.
    you saved my day 🙂

  14. I tried this method to paste the clipboard into the cmd console (command DOS window) using ALT+SPACE+E+P, but no luck. Is there an easy way (in C), when you have opened a cmd console (command DOS window), that you paste a set of commands, from the clipboard, into the cmd console / command DOS window?

    • batchloaf says:

      Hi Pistolen,

      I’m on a Linux laptop here, so I haven’t been able to test this myself, but it seems like the full sequence should be…

      Launch command window
      Delay (e.g. 1 second?) to allow command window to open and take focus
      Press Alt
      Press Space
      Release Space
      Release Alt
      Delay (not sure how long) to allow menu to open
      Press E
      Release E
      Delay (not sure how long) to allow sub-menu to appear
      Press P
      Release P

      Is that the sequence you implemented?

      Since the E and P keypresses only do what you intend once the menu/sub-menu have appeared on the screen, I’m guessing you need to leave a short delay between “Alt+Space” and “E” and again between “E” and “P”. I would start with 1 second delays (hopefully much longer than necessary) and then, if it works, reduce the delay by trial and error. You should see those menus appear on the screen during the sequence, so if you’re not seeing anything at all happen then maybe the “Alt-Space” isn’t even working.

      Finally, check that the command window is definitely in focus when the key sequence is being generated. I think it should automatically get the focus when you open it, but you probably need to leave a small delay after launching it to allow the window to actually appear and begin receiving messages (e.g. keystrokes).

      Ted

      • Pistolen-Paultje says:

        Hi Ted,

        OK I compiled the code as you suggested above. But it looks like the ALT-key is not recognised as a valid virtual-key-code. Right-mouse-click (pasting when using a mouse, virtual-key-code VK_RBUTTON), also did not work.

        Paul

      • batchloaf says:

        Hi Paul,

        You used “VK_MENU” for the Alt key, right?

        Apparently, there are additional specific virtual key codes for the left and right Alt keys respectively:

        VK_LMENU
        VK_RMENU

        If you haven’t already tried those, it might be worth a shot? Well, VK_LMENU at least. I don’t think the right Alt key does what you’re looking for.

        Ted

      • Pistolen-Paultje says:

        Hi Ted,

        Correct, for the alt-space-e-p I used VK_MENU.
        For the 2nd option, I used VK_RBUTTON.
        What I tried to achieve: I have a set of commands in my clipboard (captured using the clip command) in a DOS-box. I want to paste the clipboard contents into the same DOS-box.
        There is a tool PASTE (http://www.c3scripts.com/tutorials/msdos/clip-paste.zip), but this is display-ing/echo-ing is as text in the DOS-box and not writing it as a command.

        Paul

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