user3080392 user3080392 - 4 months ago 14
Vb.net Question

How to use a variable in a Virtual-Key statement in VB.Net

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:

<DllImport("user32.dll")> _
Public Shared Sub keybd_event(bVk As Byte, bScan As Byte, dwFlags As UInteger, dwExtraInfo As UInteger)
End Sub

Const VK_1 As Integer = &H31

keybd_event(VK_1, 0, 0, 0)
keybd_event(VK_1, 0, KEYEVENTF_KEYUP, 0)


I'm trying to do:

keybd_event(digit, 0, 0, 0)
keybd_event(digit, 0, KEYEVENTF_KEYUP, 0)


where "digit" is the variable. I've tried:

Dim digit as Byte = "VK_" & 1

Dim digit as Integer = "VK_" & 1

Dim digit as String = "VK_" & 1


But I get the error: "Conversion from string "VK_1" to type 'Byte' is not valid." and "Conversion from string "VK_1" to type 'Integer' is not valid."

I've tried:

keybd_event(VK_digit, 0, 0, 0)


But got the error "VK_digit is not declared. It may be inaccessible due to its protection level."

I also tried converting the sting to bytes and using Integer.Parse on the string but that caused errors too.

Answer

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 48, 1 has the key code 49, 2 has 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)
Comments