views:

66

answers:

2

Hello everyone, my question is how to send some key's to any application from application that is running in background? Let's say that I made shortcut to LEFT ARROW key which is ALT+S, and than I want whenever I'm in any application and when I press ALT+S that background application response that shortcut and send to currently opened program LEFT ARROW key. Here is a code that I made in Embarcadero c++ 2010 to simulate arrow left when pressing alt+s every 200 milisecond's:

void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
     bool bBothPressed = GetAsyncKeyState(VK_MENU)  && GetAsyncKeyState(0x53);
    if(bBothPressed){
        // ShowMessage("control!");
        keybd_event(VK_LEFT, 0, 0, 0);
    }
} 

... and this work fine for my application, but what I want to know is how to include that code for global scope (any application), not just for this application.

A: 

I strongly encourage you to use RegisterHotKey instead of GetAsyncKeyState. That way you won't need a loop nor a Timer, thus making your application more reliable and responsive.

To simulate the keypresses to another application/window, you need to:

A) Focus the specific window:

BringWindowToTop(hwnd);
SetForegroundWindow(hwnd);
SetFocus(hwnd);

B) Send the keydown + keyup events:

keybd_event(keycode, 0, KEYEVENTF_KEYDOWN, 0);
keybd_event(keycode, 0, KEYEVENTF_KEYUP, 0);

This should suffice. However, keep in mind the user might be already pressing one of the keys you're simulating, thus the result might not be what you're expecting. To avoid that, you need to check if the keys are already being pressed (use GetAsyncKeyState here), then send a keyup before doing B.

UPDATE:

If you wish to send the keypresses to whatever application is currently on the foreground (being focused), you can skip A.

jweyrich
The main point is how to make application that run in background like service and wait when is ALT+S is pressed, and when is pressed that execute some command, in this case just ARROW LEFT, main thing is that shortcut alt+s must be executed like arrow left in any application. What I want to make is something like macro who is activate when alt+s is pressed. I know how to make handle to some particular application, but what I need here is that the alt+s shortcut have to be handled to every process which is currently opened.
raptor
@user468506: updated accordingly.
jweyrich
thnx man your answer is very helpful I'm beginner in programing so my testing will take a little time :), but theoretically this is it what I searching for ...:)
raptor
A: 

SendInput() looks like it may be useful to you.

jeffamaphone
in this case sendinput is good function for sending shortcut to another application, and i know how to handle it to particular application (like handle it to notepad), but is there some function that can be handled to all application, without specifying every application?
raptor