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.

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

83 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 0x41, but for other keys 😀

    • 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..

  13. It said that INPUT is not declared in the scope!

  14. batchloaf says:

    Hi Bob,

    I have come across that error before, but never with this version of the code.

    • Have you modified the code in any way, no matter how small and seemingly insignificant?
    • What C compiler are you using? (I used gcc. It should be possible to use another compiler, but maybe some tiny modifications could be required?)
    • What version of Windows are you using?

    The usual reason that people see this particular error is either that the first of the following two lines (lines 23 and 24 of my code above) has been omitted, or that they are both included but in the wrong order:

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

    Line 23 must appear before line 24 because the “windows.h” header file is responsible for providing the definition of the INPUT structure, but it only does so if it knows it’s compiling for versions of Windows later than version 0x0500 (when the INPUT structure was presumably first introduced). Defining WINVER = 0x0500 before including “windows.h” ensures that it includes anything included up to this version of Windows.

    Ted

  15. Can someone help me. I can’t figure out how to send key strokes inside a video game. Is it because they use DirectX? If that is the problem, how do I work around this?

    • batchloaf says:

      Hi Timothy,

      Yes, I think you’re right. Games often receive keyboard input (along with input from game controllers and other intput devices) via DirectX. Specifically, I think it arrives via the DirectInput API. There is also a newer related Microsoft API called Xinput, but I don’t think that handles keyboard.

      I found some information here which suggests you can still use SendInput to simulate keystrokes via DirectInput, but you need to use scan codes for the key. The examples on that page are all in C#, but I tried to adapt my C example above using the information I found there. I’m on a Linux machine here, so I can’t check the following, but I think something like this might work:

      //
      // keystroke.c - Pauses, then simulates a key press
      // and release of the "A" key.
      //
      // Written by Ted Burke - last updated 3-9-2014
      //
      // 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 = 0x1E; // DirectInput key scancode for the "A" key
          ip.ki.time = 0;
          ip.ki.dwExtraInfo = 0;
       
          // Press the key (using scancode to specify which key)
          ip.ki.dwFlags = KEYEVENTF_SCANCODE;
          SendInput(1, &ip, sizeof(INPUT));
       
          // Release the key (again, using scancode to specify which key)
          ip.ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE;
          SendInput(1, &ip, sizeof(INPUT));
       
          // Exit normally
          return 0;
      }
      

      Note that the DirectInput scancode for the “A” key (the value was 0x1E) came from here:

      http://www.gamespp.com/directx/directInputKeyboardScanCodes.html

      Apparently, these scancode values are defined in the DirectInput header file “dinput.h”, but for simplicity I decided to just paste in the actual value rather than including the header file in case the compiler couldn’t find it. You can find scancodes for other keys (other than the “A” key) at the link above also.

      No guarantees, but give it a try and see what happens! Please let me know how it goes.

      Ted

      • Guilherme Ritter says:

        THANK YOU! I’ve been trying to send key presses to PCSXR (completely legal PlayStation 1 emulator) for quite a while now, and this worked! I recommend a delay of 60 ms between key down and key up, as I tested this quite extensively with AutoHotKey. I just hope this works with JNA…

      • batchloaf says:

        Great, glad to hear it worked for you Guilherme! Hopefully others might find that useful.

        Ted

      • Guilherme Ritter says:

        😉
        Also, I forgot to say: the delay I talked about should be 60 ms after a key down event and another 60 ms after a key up event.
        Also, it worked with JNA!

      • batchloaf says:

        Great, thanks Guilherme!

        Ted

  16. Thank you so much for the quick response. I am excited to try it out. I am even more excited to compare the latter code to the original.

  17. My first attempt to try the code in Windows was blocked by some errors. I will have fun trying to correct it.

  18. It started working after I placed after #include. Is that the correct thing to insert for something i’m trying to do in Direct X? I will try and find out.

  19. It works everywhere else but not in game.

    • batchloaf says:

      Hmmm, I wonder what the problem is?

      Based on the following pages…

      …it looks like it might be worth trying the modified example below:

      //
      // keystroke.c - Pauses, then simulates a key press
      // and release of the "A" key.
      //
      // Written by Ted Burke - last updated 4-9-2014
      //
      // 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 keyboard event for the "A" key
          ip.type = INPUT_KEYBOARD;
          ip.ki.wScan = 0x1E; // DirectInput key scancode for the "A" key
          ip.ki.time = 0;
          ip.ki.dwExtraInfo = 0;
       
          // Press the key
          ip.ki.dwFlags = KEYEVENTF_UNICODE;
          SendInput(1, &ip, sizeof(INPUT));
       
          // Release the key
          ip.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
          SendInput(1, &ip, sizeof(INPUT));
       
          // Exit normally
          return 0;
      }
      

      The primary change from my example yesterday is that I’ve switched from using the KEYEVENTF_SCANCODE flag for the keyboard event to using the KEYEVENTF_UNICODE flag. I’m still a little bit confused by the two pieces of documentation I linked above. If this modified example doesn’t work, it could make sense to try changing the wScan value of the keyboard event from this…

      ip.ki.wScan = 0x1E; // DirectInput "A" scancode
      

      …to something like this…

      ip.ki.wScan = 'a'; // ascii value for "a" character
      

      …or this…

      ip.ki.wScan = 'A'; // ascii value for "A" character
      

      To check whether this change of scancode value is working, it should be enough to check in e.g. Notepad. i.e. Getting the right value for wScan is nothing to do with DirectInput – it’s just that a different wScan value may be required when using the KEYEVENTF_UNICODE flag.

      Finally, just make sure that when you’re testing any of these examples with the game that you definitely switch the focus to the game window within five seconds of running the program. In each example above, I have inserted a 5 second delay into the program before the keyboard event is generated, so when you run the program you then have five seconds to switch the focus to whichever window you want to receive the event.

      Ted

      • batchloaf says:

        By the way, I just noticed that WordPress had mangled one line of my code example yesterday.

        Where it said this:

        #include
        

        …of course, it should have said this…

        #include <windows.h>
        

        WordPress has an annoying habit of silently removing anything that’s enclosed in angle brackets because it looks like a HTML tag. Apologies if that caused any confusion!

      • Thank you for the response. I am tempted to test this now, but then I’ll forget to sleep. Is what I should type after #include.

  20. Oh, nvm the last comment. Thank you and Good morning!

  21. Quick question before I really stop trying for the day hehe. Would the above UNICODE example work in notepad?

  22. Oh nvm. You clearly said it should work in notepad.

  23. Thanks for helping me nonstop. I tried and I couldn’t get UNICODE to work in notepad. So I tried SCANCODE with ‘a’ and ‘A’. It works well in notepad but not in the game “MapleStory”(free). I would make sure it prints ‘a’ in notepad then switch over to the game, wait for 10 seconds, then switch back to notepad. It would print in notepad but not in the game. I am thankful that I have learned soooo much more during this journey but it is frustrating to not accomplish the main goal.

  24. I was a bit sad because I thought I was going to succeed with PYAHK. I think deep in my heart I want to do this through C first.

    I found this:

    Hey dude. I can shed some light on this topic. I’ve made several maple scripts now including auto attacks for all warriors and a Kanna map bottling script. The problem you are encountering is that if it’s an auto attack, maple isn’t actually detecting y down per se. When we use our physical keyboard to hold down space for auto attack for example, maple detects a repeated pressed down state that controlsending y down cannot imitate.

    What is the workaround? Assuming that you want to bot an attk, change your y up y down script into a single line of {y 50}. What this will do is send the y key 50 times to maple. Obviously not each press will register because of the speed at which ahk does this, but you can modify 50 into something that lasts approximately how much you want. This is the crude way. A finer way is to look up setkeydelay function and use that to fine tune the sleep between each send of y.

    An example from my kanna script: I found that I could controlsend y down y up style for Vanquisher charm and it worked well. However, for a move like shikigami hunting, it would send the first attack then stop. Thus I changed it to ControlSend,,{y 20}, Maplestory. I apologize this isn’t in formal code format but I’m lazy on my iPad. If you’re still confused, post the name of the skill and how you want to use it. I’ll see how I can help!

    Happy mapling!

    I think I might try something similar in C!!!

  25. papucho says:

    Hi, your code is great! Thanks.

    Here is the same code, but accepting arguments.

    Can be any virtual key code

    Usage for pressing the “A” key

    keystroke.exe 41

    #define WINVER 0x0500
    #include
    #include

    int main(int argc, char *argv[])
    {

    if( argc == 2 )
    {
    printf(“The argument supplied is %s\n”, argv[1]);
    }
    else if( argc > 2 )
    {
    printf(“Too many arguments supplied.\n”);
    }
    else
    {
    printf(“One argument expected.\n”);
    return 135;
    }

    // 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;

    // read a hex string and turn it into a value
    //virtual key code
    int vkc;
    sscanf(argv[1], “%x”, &vkc);

    // Press the “A” key
    ip.ki.wVk = vkc;//atoi( argv[1] );//0xB3; // 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;
    }

  26. Rishikesh says:

    can you tell me how to disable window key of keyboard?

  27. Ki Tog says:

    firstly thx ! pls help…how can i simulate ‘█’ ? trlV[5].type = INPUT_KEYBOARD;
    ctrlV[5].ki.wVk =0x61; //VK_NUMPAD1

    ctrlV[6].type = INPUT_KEYBOARD;
    ctrlV[6].ki.wVk =0x61; //OR VK_NUMPAD1
    ctrlV[6].ki.dwFlags = KEYEVENTF_KEYUP;

    SendInput(8, ctrlV, sizeof(INPUT)); this code doesn’t affect the numberpad…it presses the regular keys 1-9 … :c how can i simulate numberpad keys ?

  28. alin says:

    Is there a way around the code so that the console window does not appear.

  29. Alin Anto says:

    Is there a way around the code so that the console window does not appear?

    • batchloaf says:

      Hi Alin,

      Well, SendInput is a Win32 function, so it should be possible to convert this to a Win32 “Windows application” rather than a console application, but it will definitely require some changes. Normally, writing a Win32 application from scratch requires a bit of work to register a windows class, create a window, run an event loop, etc. However, if all you want to do is call SendInput a couple of times you can probably skip most of that stuff. You’ll need to changing this line though:

      int main()
      

      …to something like…

      int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
      

      …because Windows applications have a different entry point (“WinMain” rather than “main”).

      Also, how exactly you compile the program as a Win32 Windows application rather than a console program depends on what compiler you’re using.

      Ted

      • Guilherme Ritter says:

        That’s weird. I use Code::Blocks with GCC in Windows 7, I write a standard C program, compile, run it by clicking on the executable, switch to another window and it works just fine. Here’s my code, based on yours and the DirectX method (I just have no idea on how to use code tags here):

        #define WINVER 0x0500
        #include

        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 = DIK_A; // DirectInput key scancode for the “A” key
        ip.ki.wScan = 0x1E; // DirectInput key scancode for the “A” key
        ip.ki.time = 0;
        ip.ki.dwExtraInfo = 0;

        // Press the key (using scancode to specify which key)
        ip.ki.dwFlags = KEYEVENTF_SCANCODE;
        SendInput(1, &ip, sizeof(INPUT));

        Sleep(60);

        // Release the key (again, using scancode to specify which key)
        ip.ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE;
        SendInput(1, &ip, sizeof(INPUT));

        Sleep(60);

        // Exit normally
        return 0;
        }

      • batchloaf says:

        But does a console window appear when you run the program, Guilherme? Icompiled it as a console application, so a console always appears when I run it. I can switch to other windows to let them receive the keystrokes, but the console window is there in the background somewhere.

        Ted

      • Guilherme Ritter says:

        You’re right, a console windows does appear. I understood the question as if a console was necessary to run the program. My bad.

      • batchloaf says:

        No harm getting another perspective anyway! Thanks Guilherme.

  30. timon says:

    Dear Ted,

    Is it possible that a document copied from notepad/word, that is text document in clipboard form, be transferred ‘one character at a time’ to another notepad/word file? or may be a browser window? (say Google IME, or Google Translate) through scancode simulation/emulation as if a human typist is typing a document? key press>key release>next key press?

    It is very important that it is done through scan-code input, not by some virtual keyboard thing (I am no coder, as I can understand it). Not some software that merely record keystroke and play it back.

    I desperately need this for modifying some South Asian Keyaboard (Which run on background) for people who suffer from RSI also make it faster.

    (Or OS environment of Windows 7)

    • batchloaf says:

      Hi Timon,

      In principle that doesn’t sound like that would be too difficult to do, but let me clarify what you’re proposing:

      1. The original text that needs to be copied is in e.g. Notepad.
      2. The user highlights the text and copies it to the clipboard in the usual way (for example by pressing Ctrl+C or selecting “Copy” from the Edit menu).
      3. The user switches focus to a different “target” application (such as a browser window) and clicks wherever the text needs to be typed.
      4. The user presses some kind of keyboard shortcut to launch some kind of helper utility that types out whatever text is contained in the clipboard one keystroke at a time.

      Is that the basic idea of what you’re trying to do? If so, that seems like it would be possible, but I don’t really understand why it needs to be typed out one character at a time rather than simply pasted straight into the target application in the normal way. If there’s something special about the target application, such as it doesn’t allow pasting text, then maybe it will also prevent automatic typing of the text?

      Anyway, if you can provide a little more detail I’ll have a think about how it might be done.

      Ted

  31. timon says:

    Dear Ted,
    If you are not a linguist, then it would be a little difficult explain this typing challenges of South East Asian alphabets. Let me try my best. I am afraid it would be a little longwinded.
    Unlike roman script, Devnagari and it’s derived alphabets (All Indic alphabets) have lots and lots of letters and accent marks. Not as many as Chinese, but each of them slightly over a hundred glyphs to deal with.
    Say there is only one ‘R’ in English but there are 4 ‘R’s! = (র, ড়, ঢ়, ঋ)
    3 Ss (স, শ, ষ) (last 2 represent ‘Sh’ sound)
    2 Cs (চ, ছ) First one ‘Ch’ last one ‘Chh’ sound)
    Then there is ‘hard’ (The way English, German pronounce their ‘T’ ‘D’) and ‘soft’ consonants (The way Italians, Spanish, Russians pronounce their ‘T’ ‘D’)
    Soft T =ত, Hard T=ট
    Soft D=দ, Hard D=ড
    And I am not getting into Vowel marks, Diacritics and ligatured (2 Fonts joined together like ” Æ”) fonts at all! (almost nearly hundred
    ===
    Now how they type with computers with 26 Roman letters on? Well, first thing, there is another virtual keyboard software (Called “keyboard Interface’) underneath it. And (Usually by Shift + Some Function key) turning on that software, typist have to use ‘shift’ key (Thank god there is no Uppercase or Lower case letters in Indic Alphabets!) and the ‘joiner key’, usually ‘g’ or ‘h’ (located middle of keyboard). The ‘virtual keyboard’ software running underneath, acting as translator, turn those keystrokes, produce Unicode fonts, join them, put diacritic mark on them as necessary.
    Use of Shift key: say I am going to write ‘soft T’ (ত), here I type lower case t, But writing ‘hard T’ (ট) I have to use Upper case ‘T’, joining 2 ‘soft t’s (ত+ত=ত্ত) I type t, h (h=joiner), t it becomes a single ligatured font = ত্ত, and joining 2 ‘hard d’s together (ড+ড=ড্ড) I press uppercase D, h, D, joined it becomes ড্ড,

    Ok, you see, to type meaningfully, the typist have to use the ‘shift’ key a lot. It slows down the fastest of typists, they are slower than any western language typist in output, and it makes them injury-prone (cause you have use the little finger in an odd angle to press shift key). And as a serious translator, pounding keyboard for a decade, I myself suffer from mild case of RSI.
    So I thought (I am no coder I admit it, only interested in writing, translating, editing long documents) this can be solved in a smart way. Lets make a simple code that turns 1 keystroke in lowercase, 2 keystrokes in uppercase. a=a, but aa=A. see? I asked in online forum, and got this following code (given below).
    It works beautifully. Alas! Except it does not work for those ‘virtual keyboards’ and ‘Google Transliterate’ now called Google IME, which also is a virtual online keyboard for many Indic languages, something we have to use a lot, furthermore Google Transliterate does not accept any pre typed document, al character must be put in real-time, one key stroke in a time). So I asked some IT savvy people (Who incidentally does not have time or inclination to solve this particular problem) and they said it something to do with ‘imitating scancode’ (I hope I got it write), so for this reason I am making this, what I say little unusual request. A keyboard imitator, which types one virtual character at a time, I hope can ‘fool’ Google and ‘keyboard interfaces’!

    (I have few more things to add in my next post)
    —–

    F1::toggle:=!toggle ; press F1 to activate, deactivate

    #If toggle

    :*:aa::A
    :*:bb::B
    :*:cc::C
    :*:dd::D
    :*:ee::E
    :*:ff::F
    :*:gg::G
    :*:hh::H
    :*:ii::I
    :*:jj::J
    :*:kk::K
    :*:ll::L
    :*:mm::M
    :*:nn::N
    :*:oo::O
    :*:pp::P
    :*:qq::Q
    :*:rr::R
    :*:ss::S
    :*:tt::T
    :*:uu::U
    :*:vv::V
    :*:ww::W
    :*:xx::X
    :*:yy::Y
    :*:zz::Z

    • batchloaf says:

      Wow, ok, fascinating problem! Thanks for the detailed explanation. I’d like to help you at least some of the way with this. Unfortunately, this is a difficult week to do it though because my schedule is pretty jam packed. I guess the first step would be to try something like what I described above – a little test utility to copy characters from the clipboard to an application by simulating keystrokes. I can take a shot at writing something simple like that and we can see if the keystrokes are even accepted by Google IME, but it will probably be a few days until I’ll get a chance to do it. Are you working to a particular deadline?

      Ted

  32. timon says:

    Thank you Ted, Please take your time. I am thinking about this line of solutions, say since around 2009, so a week, fortnight, a month or two months is not going make much difference. 🙂
    In my layperson’s view, the code block should not be very long, perhaps a paragraph length, (7-10 lines). Again may be I am wrong. Dealing steps as below,

    1. ‘Get’, ‘read’ clipboard (^a^c ; copy all)
    2. ‘Match’ letters with Scancode or Virtual Key Code List
    3. ‘Echo’ ‘Generate’ Scancode
    4. ‘SetKeyDelay’, 30 ; 30 millis delay between keys
    5. ‘Send’, %clipboard%
    6. (May be we should ) append the ‘scan code/vk code list’ with it.
    I am not exactly sure of those technical terms and wordings but it should be something like that.

  33. hiraghm says:

    I’ve been looking for example programming tutorials to try writing a keyboard “wedge”. I’d like to attach my TRS-80 Model 100 via the serial port and use it as a keyboard, since I love its keyboard’s feel. I don’t want to hardware hack the M100 to turn it into a USB keyboard, since I want to also continue using it as it was originally designed, when not using it as a keyboard.
    Basically, my idea is to run a simple terminal emulator on the M100 to send the keystrokes over the serial port to the Windows 7 PC, then have the PC grab that information from the serial port and insert it into the input stream as keystrokes.
    Could this sample code be adapted to that purpose, or am I looking in the wrong place entirely?

    • batchloaf says:

      Hi Hiraghm,

      Wow, that’s a really interesting idea!

      I think you could get it working for general typing etc using an approach similar to that shown above, but I suspect that for more complicated keyboard combinations (Ctrl, Alt, Shift, etc) you might find it doesn’t quite do everything you would need. I’m kind of speculating here, but I think that if you want to make a completely solid keyboard replacement, you might want to write some kind of keyboard driver.

      Alternatively, I’m sure Windows has some kind of historic serial keyboard driver. Could you program the M100 to adapt its output to that protocol. If that’s possible, you wouldn’t really need to do anything at the Windows end other than set up the serial keyboard driver. That’s probably what I’d try first!

      Ted

  34. Pingback: Boot Straight to Desktop in Windows 8 – black-pixel

  35. chintam says:

    what if we not introduce 5 seconds of delay before SendInput??

    • batchloaf says:

      Hi Chintam,

      That 5 second delay is only there so that I would have time to switch to the Notepad window before the keystrokes are simulated. They’re not required for using SendInput normally, but in this case I was running the program in a console and if there was no delay the keystrokes were generated as soon as the program ran, so the focus would still be on the console rather than Notepad.

      Ted

  36. Ivan says:

    Hi Ted, thanks for your code. It ‘really valuable.
    I’m looking for create a UDP server that prints ‘a’ only when a message is sent on a given UDP port from a client, but I’m a newbie of c and c ++;
    I tried to use some udp socket from the web but when I compile them appear incomprehensible errors.
    could you help me ?
    Thanks in advance
    Ivan

      • batchloaf says:

        Hi Ivan,

        Sorry I didn’t get time to respond earlier. I’m glad you solved your problem.

        For what it’s worth, I would have suggested using Python if you wanted a fast and simple solution. I tried it out by creating the following simple Python script to send a short message to a specific IP address and port number (127.0.0.1:5005 in my experiment) via UDP:

        import socket
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.sendto("Hello", ("127.0.0.1", 5005))
        

        I saved that file as “sender.py”.

        Then, I created the server as I understood you meant from your description – i.e. print out the letter ‘a’ every time a message is received:

        import socket
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(("127.0.0.1", 5005))
        
        while 1:
            data, addr = sock.recvfrom(1024)
            print('a')
        
        

        I saved that file as “receiver.py”.

        I opened two command windows and ran the server in one (“python receiver.py”) and the sender in the other (“python sender.py”). Every time I ran the sender program in the second command window, the letter a was printed in the first command window.

        One problem I encountered was that pressing Ctrl+C didn’t immediately stop the receiver program running. It wouldn’t exit until it received something over the UDP socket. To prevent this, I added a 1 second timeout to the UDP socket which means that pressing Ctrl + C quickly closes the program. Here’s the modified version with the timeout:

        import socket
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(1.0)
        sock.bind(("127.0.0.1", 5005))
        
        while 1:
            try:
                data, addr = sock.recvfrom(1024)
                print('a')
            except socket.timeout:
                pass
        

        Anyway, glad you already solved your problem!

        Ted

  37. Martns says:

    Hi Ted,
    How to focus on both (Notepad and console, like a virtual keyboard)?

  38. Simon says:

    Hello Ted, I don’t know if you’re still answering to this thread, but I have a question.

    I wrote a program using your code and it works great. But then I wanted various functions to use the input events. I found myself using the same piece of code inside every function, namely:

    // This structure will be used to create the keyboard
    // input event.
    INPUT ip;

    // 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;

    So I wanted to avoid this and have that piece of code appear just once. I moved this code outside of all functions and put it just below the #includes, thinking it would work as a global variable, accessible to all other functions. This did not work, it gives me a compilation error. I use CLion, and it doesn’t complain about the “INPUT ip;” declaration, but it complains on all four lines that begin with “ip.”. When I hover over them, CLion says ” Unknown type name ‘ip’ “. Any idea how to fix this? I don’t understand why they work perfectly if they’re inside main or any other function, but they don’t when they’re outside.

    Thanks in advance.

    • batchloaf says:

      Hi Simon,

      I suggest you try declaring ip globally and simultaneously initialising it as follows:

      INPUT ip = {.type = INPUT_KEYBOARD, .ki.wScan = 0, .ki.time = 0, .ki.dwExtraInfo = 0};
      

      Ted

  39. daniel loughrey says:

    Hey, is it possible to simulate typing a int variable? Or would I need to use another programming language.

  40. Hi Ted,
    First of all thank you very much for this blog post. I was working on my hobby project in D language. I want to create an IME for my own use. So I did some googling and decided to use SendInput function for this task. After a few days of coding, I successfully created my IME program and all felt good. But suddenly I noticed that at a certain point, the backspace keys are not working properly. All I wanted to send 4 backspace keys but for some reason, only two keypresses are happening. After two days of frustration, I found this blog and I inspect each and every step you wrote. Suddenly I realized that I missed one important step. Let me explain that.
    Since I am working unicode letters, I have use input.ki.wScan for all the letters and I have used KEYEVENTF_UNICODE flag. So MSDN says that when we use this flag, the SendInput function will send both key down & key up messages to the active program. That’s okay for me. But I did a mistake in sending backspace keys. Since backspace doesn’t need to be treated as a Unicode key, I have used input.ki.wVk. And I didn’t use the KEYEVENTF_UNICODE flag. But I forget about the key up message. When we not use KEYEVENTF_UNICODE flag, we need to send the keys twice. I realized my mistake when I read your code and comments. So literally you saved me from frustration. Thanks a lot.
    A hobby D programmer from India.

Leave a comment