| Visual Basic Sample Programs |
Site Top > Visual Basic Sample Programs > Visual Basic Sample Programs >
Scroll Lock key detection
4/13/2024
→ Switch to C# → Switch to Python
TOC
Scroll Lock key detection for Windows from apps
![]()
If Control.IsKeyLocked(Keys.Scroll) Then
MessageBox.Show("Scroll Lock")
Else
MessageBox.Show("No Scroll Lock")
End If
Another solution.
![]()
If My.Computer.Keyboard.ScrollLock Then
MessageBox.Show("Scroll Lock")
Else
MessageBox.Show("No Scroll Lock")
End If
Scroll Lock key detection for WPF
![]()
If Keyboard.IsKeyToggled(Key.ScrollLock) Then
MessageBox.Show("Scroll Lock")
Else
MessageBox.Show("No Scroll Lock")
End If
Scroll Lock key detection for any case
First, you have to code KeyboardUtil class as following.
![]()
Public Class KeyboardUtil
<System.Runtime.InteropServices.DllImport("User32.dll")>
Private Shared Function GetKeyState(keyCode As Integer) As Short
'Keep empty
End Function
'''<summary>
'''Get whether Scroll Lock key is presses or not. If pressed return true.
'''</summary>
Public Shared Function IsScrollLock() As Boolean
'145 means Scroll Lock key
If (GetKeyState(145) And &H8001) <> 0 Then
Return True 'Scroll Lock
Else
Return False 'No Scroll Lock
End If
End Function
End Class
Next, you can use following code to detect scroll lock key.
![]()
If KeyboardUtil.IsScrollLock() Then
Debug.WriteLine("Scroll Lock")
Else
Debug.WriteLine("No Scroll Lock")
End If
→ Where Debug.WriteLine appear
Note: This program will only work on Windows. On Linux, it will raise System.DllNotFoundException.
Note: The basis for 0x8001 is the implementation of System.Windows.Forms.Control.IsKeyLocked. I don't understand the meaning of the high order bits.
Reference:Comparison of how to get the status of the lock key
| Console class | Control class (Windows Form) |
Keyboard class (WPF) |
WindowsAPI GetKeyState |
|
|---|---|---|---|---|
| sample | sample | sample | ||
| Target key | ||||
| NumLock | ✔ | ✔ | ✔ | ✔ |
| CapsLock | ✔ | ✔ | ✔ | ✔ |
| ScrollLock | ❌ | ✔ | ✔ | ✔ |
| Insert | ❌ | ✔ | ✔ | ✔ |
| Supported application type | ||||
| Console | ✔ | ❌ | ❌ | ✔ |
| Windows Form | ✔ | ✔ | ❌ | ✔ |
| WPF | ✔ | ❌ | ✔ | ✔ |
| Class Library | ✔ | ❌ | ❌ | ✔ |
| Supported OS | ||||
| Windows | ✔ | ✔ | ✔ | ✔ |
| Others | ❌ | ❌ | ❌ | ❌ |
There is no way to work on all cases. You have to choice the way case by case.
Hint
- You can call Control class and Keyboard class from both Windows Form and WPF with special configuration → how to do it
- Windows API GetKeyState is the most versatile way. But it's tiresome. You can write utility code in your original class library, it will help you.
- It is unclear for me how to determine the key on an OS other than Windows.