Reputation: 11
I am writing a WPF app that allows a user to press a key on their keyboard and then store the virtual key code for later execution currently, my code only captures the KeyChar
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
System.Windows.MessageBox.Show("Key char : " + e.Key);
}
At a later stage, the code is executed, in something similar to this...
else if(e.Result.Text.Equals("windows"))
{
//windows key down
keybd_event((byte)VK_LWIN, 0x5B, 0, 0);
//windows key up
keybd_event((byte)VK_LWIN, 0x5B, KEYEVENTF_KEYUP, 0);
}
The keybd_event method uses virtual key codes to identify which key the program is required to execute on the system.
I can easily capture and execute these separate variables
but how do I convert the keyChar to Virtual key code for storing and then executing in the separate window?
User 32 DLL method.. https://www.pinvoke.net/default.aspx/user32.keybd_event
Upvotes: 0
Views: 2454
Reputation: 16609
You can us the KeyInterop
class. This contains static methods to convert between .Net Keys and VKeys:
int vkey;
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
vkey = System.Windows.Input.KeyInterop.VirtualKeyFromKey(e.Key);
System.Windows.MessageBox.Show("Key char : " + e.Key);
}
{
keybd_event((byte)vkey, 0x5B, 0, 0);
}
Upvotes: 1