I need to emulate some keys, here the code:
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
private const int KEYEVENTF_EXTENDEDKEY = 1;
private const int KEYEVENTF_KEYUP = 2;
public static void KeyDown(Keys vKey)
{
keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
}
public static void KeyUp(Keys vKey)
{
keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
KeyboardSend.KeyDown(Keys.Z);
KeyboardSend.KeyUp(Keys.Z);
But in one specific application "KeyUp" method doesn't work and is depressed until i press key on keyboard.
What i'm doing wrong?
The only change I see in Ryan West's solution, is that he removed the
KEYEVENTF_EXTENDEDKEY
flag away from calling functionkeybd_event
in the third argument, in bothKeyDown
andKeyUp
methods, so as a result, inKeyDown
method, the third argument of callingkeybd_event
function is 0, and inKeyUp
method, it is onlyKEYEVENTF_KEYUP
. That only small change causedKeyUp
method to work and solve your problem.Read about
keybd_event
function in MSDN site properly, and even again, if you read before.They give information and details about that function and its arguments. They also explain all the flags that you can use in the third argument of
keybd_event
function, especially the case in your problemKEYEVENTF_EXTENDEDKEY
.If you will read properly and again, maybe you will understand why
KEYEVENTF_EXTENDEDKEY
flag causes yourKeyUp
method not to work, and why you have to remove that flag, in order to cause yourKeyUp
method to work.You may also learn how, in the future, to call
keybd_event
function correctly, so you won't get any problem with it.When I changed the code to the following it seemed to work just fine. I tested it by opening notepad, running the program, then holding down the 'a' key. It printed lowercase for 3 seconds, then started doing uppercase then went back to lowercase again.
Try checking out Windows Input Simulator for a good example of how to simulate key presses. It's an open source wrapper for the SendInput function in User32.dll.
One thing I've learned is that to simulate holding a key down, it usually isn't enough to send the keydown, wait a bit, then send the key up. If you want the key to repeat the key press like a normal keyboard does you have to keep sending the keyboard event and end it with a key up event.
http://inputsimulator.codeplex.com/