How can I programmatically create an event that would simulate a key being pressed on the keyboard?
This question is related to
c#
.net
wpf
keyboard-events
Easily! (because someone else already did the work for us...)
After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:
Install the package, can be done or from the NuGet package manager or from the package manager console like:
Install-Package InputSimulator
Use this 2 lines of code:
inputSimulator = new InputSimulator()
inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)
And that's it!
-------EDIT--------
The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.
To produce key events without Windows Forms Context, We can use the following method,
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
sample code is given below:
const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28; //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
//Press the key
keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
return 0;
}
List of Virtual Keys are defined here.
To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
I've not used it, but SendKeys may do what you want.
Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.
System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");
Microsoft has some more usage examples here.
Windows SendMessage API with send WM_KEYDOWN.
Source: Stackoverflow.com