代码的作用: 我有一个代码,可以在屏幕上移动鼠标,获取打印屏幕并将其粘贴到 excel。
问题: 由于某种原因,我的代码总是(绝对没有异常(exception))在每次运行后关闭 NUMLOCK 键。
到目前为止我尝试过的: 我四处搜索并找到了 SendKeys (NUMLOCK),它在理论上是有效的(尽管它对用户来说似乎很成问题)。
我想做什么: 我想在每次宏运行后打开 NUMLOCK,
Obs1: 我不知道是什么导致宏首先将其关闭。修复导致此问题的任何内容将是理想的,但由于我不知道问题是什么,我首先想让我的代码正常工作。我将尽快找到打开 NUMLOCK 键的方法。
问题: 我可以使用 SendKeys 执行此操作吗?我是否正确使用它?有没有更好的办法?
Obs2:因为它是一个更大的代码,所以一旦解决了这个问题,我将发布另一个问题以及整个代码,并讨论导致问题的原因。
代码 我试图起诉打开 numlock:
Application.Sendkeys (NUMLOCK)
还试过:
Application.Sendkeys ("NUMLOCK")
和
Application.Sendkeys {NUMLOCK}
最佳答案
您可以通过几个 Windows API 调用直接设置 key 状态。从 MSDN page for keybd_event function 移植:
#If VBA7 Then
Private Declare PtrSafe Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, _
ByVal dwFlags As LongPtr, ByVal dwExtraInfo As LongPtr)
Private Declare PtrSafe Function GetKeyboardState Lib "user32.dll" (ByVal lpKeyState As LongPtr) As Boolean
#Else
Private Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, _
ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Private Declare Function GetKeyboardState Lib "user32.dll" (ByVal lpKeyState As Long) As Boolean
#End If
Private Const KEYEVENTF_EXTENDEDKEY As Long = &H1
Private Const KEYEVENTF_KEYUP As Long = &H2
Private Const VK_NUMLOCK As Byte = &H90
Private Const NumLockScanCode As Byte = &H45
Private Sub ToggleNumlock(enabled As Boolean)
Dim keystate(255) As Byte
'Test current keyboard state.
GetKeyboardState (VarPtr(keystate(0)))
If (Not keystate(VK_NUMLOCK) And enabled) Or (keystate(VK_NUMLOCK) And Not enabled) Then
'Send a keydown
keybd_event VK_NUMLOCK, NumLockScanCode, KEYEVENTF_EXTENDEDKEY, 0&
'Send a keyup
keybd_event VK_NUMLOCK, NumLockScanCode, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0&
End If
End Sub
像这样调用它:
Sub Example()
'Turn Numlock off.
ToggleNumlock False
'Turn Numlock on.
ToggleNumlock True
End Sub