tags:

views:

64

answers:

3

I want my program to press certain keys on my keyboard without me doing it physically.

How i do this?

Edit: found this keybd_event() function. seem to be working http://www.codeproject.com/KB/cpp/sendkeys_cpp_Article.aspx

A: 

Send Key Events

fabrizioM
Didnt find c++ code there, but gave me good keyword for google
Newbie
A: 

Use SendMessage with WM_KEYDOWN

Example:

SendMessage(hwnd, WM_KEYDOWN, VK_T, NULL);
Brian R. Bondy
I guess this works only inside my own app window?
Newbie
@Newbie: No you can send a message to any window within your windows session
Brian R. Bondy
Yeah, but to do that, i would have to select the focused window separately, or is there some easy way to select the currently focused window?
Newbie
Not sure what you want, the foreground window? GetForegroundWindow http://msdn.microsoft.com/en-us/library/ms633505(VS.85).aspx
Brian R. Bondy
+1  A: 

There is SendInput function that can generate keystrokes and other kinds of input. I have used to create application similar to virtual keyboards.

Example using Unicode:

// This may be needed
// #define _WIN32_WINNT 0x0501 

#include <windows.h>
#include <winuser.h>

void    pressKey(WORD a_unicode)    
{       
        KEYBDINPUT kbinput;
        ZeroMemory(&kbinput, sizeof(kbinput));
        kbinput.wScan = a_unicode;
        kbinput.dwFlags = KEYEVENTF_UNICODE; 
        kbinput.time = 0;

        INPUT input;
        ZeroMemory(&input, sizeof(input));
        input.type = INPUT_KEYBOARD;
        input.ki = kbinput;

        SendInput(1, &input, sizeof(input));
}   
Virne
didnt seem to work, at least not the VK_TAB etc.
Newbie
Right approach, wrong code. It should assign the vVk member. And generate the KEYUP event as well.
Hans Passant
Yeah. Perhaps a bit misleading example. This peace is from code that writes international characters, like japanese kanji etc. That's why it uses scancodes instead of virtual keys. For tabs etc. vVk and KEYUP are needed.
Virne