我尝试在 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
但我收到错误:“从字符串“VK_1”到类型“Byte”的转换无效。”和“从字符串“VK_1”到类型“Integer”的转换无效。”
我已经尝试过:
keybd_event(VK_digit, 0, 0, 0)
但收到错误“VK_digit 未声明。由于其保护级别,它可能无法访问。”
我还尝试将字符串转换为字节并在字符串上使用 Integer.Parse,但这也导致了错误。
最佳答案
变量名称不能串联。恐怕您当前尝试使用 digit
变量执行的操作是不可能的。您会收到错误,因为在您的尝试中,您只是采用普通字符串并尝试将其转换为数字(这是行不通的,因为例如 "VK_1"
包含字母和其他非数字字符)。
但是,如果您想动态指定数字键,有几种方法。
对于初学者:所有VK_
键代码都可以在 System.Windows.Forms.Keys
enumeration 中找到。 ,因此您不必查找要使用的每个键。
其次:数字的键码彼此跟随。数字 0
的 key 代码为 48
,1
的 key 代码为 49
,2
> 有 50
,依此类推...
感谢我提到的第二件事,我们只需获取 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)
关于vb.net - 如何在 VB.Net 的 Virtual-Key 语句中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38340342/