Home
Tutorials
Code Snippets
Code Samples
Downloads
Links

The Blog
Our Projects
About
Contact

::Add RageStorm to Favorites!::

The Blog | Our Projects | Guest Book | About | Contact

 
Code Snippet - Simulate Key Press
Author:Arkon
Category:Win32API
File Size:~ 1.50 KB
Uploaded at:27-Nov-02 03:28:46 pm
Description:
  Simulate key press for a macro system or whatever.
  
Sending key pressings.

KEYBDINPUT ki;
ki.wVk = VK_RETURN;
ki.wScan = MapVirtualKeyEx(VK_RETURN, 0, GetKeyboardLayout(0));
ki.dwFlags = KEYEVENTF_EXTENDEDKEY; // or KEYEVENTF_KEYUP, one of those must work :)
ki.time = 0;
ki.dwExtraInfo = 0;
INPUT ipEvent;
ipEvent.type = INPUT_KEYBOARD;
ipEvent.ki = ki;
UINT nNumEvents = SendInput(1, &ipEvent, sizeof(INPUT));

BTW-You can get the window HWND, and then 
SendMessage(hWnd, WM_KEYDOWN, VK_RETURN, 0);
SendMessage(hWnd, WM_KEYUP, VK_RETURN, 0);


Send ALT+SPACE to current focused window:
 keybd_event(VK_MENU, 0, 0, 0);
 keybd_event(VK_SPACE, 0, 0, 0);
 keybd_event(VK_SPACE, 0, KEYEVENTF_KEYUP, 0);
 keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);


This is an example for console window:
Sends "CLS" and then ENTER.. Guess what it does
 char sc = 0;

 sc = MapVirtualKey(/*VK_C*/0x43, 0);
 SendMessage(hWnd, WM_KEYDOWN, sc, 1 | (1 << 30) | (sc << 16));
 SendMessage(hWnd, WM_KEYUP, sc, 1 | (3 << 30) | (sc << 16));

 sc = MapVirtualKey(/*VK_L*/0x4c, 0);
 SendMessage(hWnd, WM_KEYDOWN, sc, 1 | (1 << 30) | (sc << 16));
 SendMessage(hWnd, WM_KEYUP, sc, 1 | (3 << 30) | (sc << 16));

 sc = MapVirtualKey(/*VK_S*/0x53, 0);
 SendMessage(hWnd, WM_KEYDOWN, sc, 1 | (1 << 30) | (sc << 16));
 SendMessage(hWnd, WM_KEYUP, sc, 1 | (3 << 30) | (sc << 16));

 sc = MapVirtualKey(VK_RETURN, 0);
 SendMessage(hWnd, WM_KEYDOWN, sc, 1 | (1 << 30) | (sc << 16));
 SendMessage(hWnd, WM_KEYUP, sc, 1 | (3 << 30) | (sc << 16));

(Did the target window) Get it?
User Contributed Comments(2)
 [1] kai | 2006-10-04 08:40:43

Exactly what I need. ThanX a lot, man! After hours of testing and searching, you've mad me a happy man.
 [2] Keith Pastorek | 2010-09-29 11:04:16

Hi, I am trying to something similar in Unity3D. Does this code work for that? If not do you have an example or link to an example that has the same type of thing for Unity3D? Thanks.
NOTE:
Comments that will hurt anyone in any way will be deleted.
Don't ask for features, advertise or curse.
If you want to leave a message to the author use the contacts,
if you have any question in relation to your comments please use the forum.
Comments which violate any of these requests will be deleted without further
notice. Use the comment system decently.

Post your comment:
Name:
email:
Comment:
::Top 5 Tutorials::
Embedded Python[106236]
2D Rotated Rectangles Collision Detection[79394]
Keyboard Hook[68784]
UDP[52867]
HTTP Proxy[36098]

::Top 5 Samples::
2D ColDet Rotated Rectangles[10613]
PS2 Mouse Driver[6098]
Wave Format Player[4984]
Reading FAT12[4870]
CodeGuru[4561]


All rights reserved to RageStorm © 2009