VB.Net 如何在 Virtual-Key 语句中使用变量

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

我试图在 VB.Net 的 Virtual-Key 语句中使用变量,但我不断收到错误。正确的语法是什么?没有变量,代码如下所示:

<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)

我正在尝试做:

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

其中 "digit" 是变量。我试过:

Dim digit as Byte = "VK_" & 1

Dim digit as Integer = "VK_" & 1

Dim digit as String = "VK_" & 1

但我收到错误消息:"Conversion from string "VK_1" to type 'Byte' is not valid."并且 "Conversion from string "VK_1" 键入 'Integer' 无效。"

我试过:

keybd_event(VK_digit, 0, 0, 0)

但是报错"VK_digit is not declared. It may be inaccessible due to its protection level."

我还尝试将字符串转换为字节并在字符串上使用 Integer.Parse 但这也导致了错误。

不能连接变量名。恐怕您目前尝试使用 digit 变量进行的操作是不可能的。你得到错误是因为在你的尝试中你只是采用一个普通的字符串并试图将它转换成一个数字(这是行不通的,因为例如 "VK_1" 包含字母和其他非数字字符)。

但是如果你想动态指定一个数字键,有几种方法。

对于初学者:所有VK_键代码都可以在System.Windows.Forms.Keys enumeration中找到,因此您不必查找所需的每个键使用。

其次:号码的键码是相继的。数字 0 有键码 481 有键码 49250,依此类推...

多亏了我提到的第二件事,我们可以通过获取 0 的关键代码并在其中添加我们想要的数字来简化我们自己的工作。

简单的解决方案:

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)

第二种更复杂的解决方案是将字符串解析为枚举值:

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)

第二种解决方案的好处在于它不仅适用于数字:

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)