Detect if the Shift, Ctrl, Alt or CMD key has been pressed

In Excel for Windows you can use the GetKeyState API to check this but on a Mac it is not so easy. Code like this can be very useful to run the code you want depending of the key status.

Thanks to DJ Bazzie Wazzie from the script forum i was able to create this VBA example. Note: it is not very fast.You can run the macro named TestKey below to test it, do not forget to copy the function KeyPressedCheck inside the same module because it is called by the macro. In the function call in the macro you see that I use argument 1 for testing the Shift key now, see the comments in the macro for using argument 2, 3 or 4.

Note: When you call the function from a userform button or button on a worksheet the Ctrl key test is not working, when you run the Ctrl test from the macro dialog it is working. Reason is that Ctrl + click is right click on a Mac so the Ctrl test is only working from the macro dialog.

Sub TestKey()
'1 = Shift.
'2 = Ctrl
'3 = Alt or Option
'4 = Command or CMD
If KeyPressedCheck(1) = True Then
MsgBox "Shift Key is pressed"
Else
MsgBox "Shift Key is not pressed"
End If
End Sub

Function KeyPressedCheck(KeyToCheck As Long) As Boolean
'Ron de Bruin 11-Aug-2014, working in OS X v10.0 and up.
'Thanks to DJ Bazzie Wazzie from the macscripter forum
Dim KeyConstant As String
Dim ScriptToRun As String

Select Case KeyToCheck
Case 1: KeyConstant = "NSShiftKeyMask" 'Shift key
Case 2: KeyConstant = "NSControlKeyMask" 'Ctrl key
Case 3: KeyConstant = "NSAlternateKeyMask" 'Alt or Option key
Case 4: KeyConstant = "NSCommandKeyMask" 'Command or CMD key
End Select

ScriptToRun = "do shell script ""/usr/bin/python -c 'import Cocoa; " & _
"print Cocoa.NSEvent.modifierFlags() & Cocoa." & KeyConstant & " > 1'"""

On Error Resume Next
KeyPressedCheck = MacScript(ScriptToRun)
On Error GoTo 0
End Function
26-February-2021
Web design by Will Woodgate