I'm trying to use a variable in a Virtual-Key statement in VB.Net, but I keep getting errors. What is the correct syntax? Without the variable, the code looks like this:
Public Shared Sub keybd_event(bVk As Byte, bScan As Byte, dwFlags As UInteger, dwExtraInfo As UInteger)
Const VK_1 As Integer = &H31
keybd_event(VK_1, 0, 0, 0)
keybd_event(VK_1, 0, KEYEVENTF_KEYUP, 0)
keybd_event(digit, 0, 0, 0)
keybd_event(digit, 0, KEYEVENTF_KEYUP, 0)
Dim digit as Byte = "VK_" & 1
Dim digit as Integer = "VK_" & 1
Dim digit as String = "VK_" & 1
keybd_event(VK_digit, 0, 0, 0)
Variable names cannot be concatenated. What you're currently trying to do with the
digit variable is impossible, I'm afraid. You get the errors because in your attempts you are just taking a normal string and trying to convert that into a number (which doesn't work, since for example
"VK_1" contains letters and other non-numeric characters).
However if you want to dynamically specify a number key, there are a few ways.
For starters: All the
VK_ key codes can be found in the
System.Windows.Forms.Keys enumeration, so you don't have to lookup every key you want to use.
Secondly: The numbers' key codes follows each other. Number
0 has the key code
1 has the key code
50, and so on...
Thanks to the second thing I mentioned we can make it easy for ourselves by just taking the key code for
0, and to that add the number that we want.
The simple solution:
Dim digit As Integer = 3 'Cannot go below 0 nor above 9. keybd_event(Keys.D0 + digit, 0, 0, 0) keybd_event(Keys.D0 + digit, 0, KEYEVENTF_KEYUP, 0)
The second, more complicated, solution is to parse a string into an enum value:
Dim digit As Integer = 3 Dim Key As Keys = [Enum].Parse(GetType(Keys), "D" & digit, True) keybd_event(Key, 0, 0, 0) keybd_event(Key, 0, KEYEVENTF_KEYUP, 0)
The good thing with the second solution is that it works for more than just numbers:
Dim Letter As String = "F" Dim Key As Keys = [Enum].Parse(GetType(Keys), Letter, True) keybd_event(Key, 0, 0, 0) 'Presses "F". keybd_event(Key, 0, KEYEVENTF_KEYUP, 0)