如何在Visual Basic 6中打开或关闭Caps Lock键?
答案 0 :(得分:4)
由于 keybd_event 功能已被取代, SendInput (MSDN)是一种可行的方法。顺便说一句,如果您要在VB6中使用键盘做一些严肃的事情,请务必在此处查看Carl E. Peterson的文章和代码:http://vb.mvps.org/samples/SendInput/
要设置CapsLock状态,可以使用以下代码(可选择放入标准模块)。 SetCapsLockState (True)启用CapsLock, SetCapsLockState (False)禁用它。
Option Explicit
Private Declare Function GetKeyState Lib "user32" _
(ByVal nVirtKey As Long) As Integer
Private Declare Function MapVirtualKey Lib "user32" _
Alias "MapVirtualKeyA" _
(ByVal uCode As Long, ByVal uMapType As Long) As Long
Private Declare Function SendInput Lib "user32" _
(ByVal nInputs As Long, pInputs As Any, ByVal cbSize As Long) As Long
Private Type KeyboardInput ' typedef struct tagINPUT {
dwType As Long ' DWORD type;
wVK As Integer ' union {MOUSEINPUT mi;
wScan As Integer ' KEYBDINPUT ki;
dwFlags As Long ' HARDWAREINPUT hi;
dwTime As Long ' };
dwExtraInfo As Long ' }INPUT, *PINPUT;
dwPadding As Currency '
End Type
'SendInput constants
Private Const INPUT_KEYBOARD As Long = 1
Private Const KEYEVENTF_KEYUP As Long = 2
Private Const VK_CAPITAL = &H14
Public Function CapsLock() As Boolean
' Determine whether CAPSLOCK key is toggled on.
CapsLock = CBool(GetKeyState(VK_CAPITAL) And 1)
End Function
Public Sub SetCapsLockState(bEnabled As Boolean)
'CapsLock is already in desired state. Nothing to do.
If CapsLock = bEnabled Then Exit Sub
PressCapsLock
End Sub
Private Sub PressCapsLock()
GenerateKeyboardEvent VK_CAPITAL, 0
GenerateKeyboardEvent VK_CAPITAL, KEYEVENTF_KEYUP
End Sub
Private Sub GenerateKeyboardEvent(VirtualKey As Long, Flags As Long)
Dim kevent As KeyboardInput
With kevent
.dwType = INPUT_KEYBOARD
.wScan = MapVirtualKey(VirtualKey, 0)
.wVK = VirtualKey
.dwTime = 0
.dwFlags = Flags
End With
SendInput 1, kevent, Len(kevent)
End Sub
可以从这样的表单模块中调用它:
Option Explicit
Private Sub cmdCapsLockOff_Click()
SetCapsLockState False
End Sub
Private Sub cmdCapsLockOn_Click()
SetCapsLockState True
End Sub
Private Sub cmdShowState_Click()
MsgBox "CapsLock is " & IIf(CapsLock, "ON", "OFF")
End Sub
答案 1 :(得分:2)