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(bBothPresse开发者_JS百科d){
// 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.
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.
SendInput() looks like it may be useful to you.
精彩评论