ヘッダー
C# Sample Programs
 

Scroll Lock key detection

04/13/2024

→ Switch to Visual Basic → Switch to Python

 

Scroll Lock key detection for Windows from apps

if (Control.IsKeyLocked(Keys.Scroll))
{
    MessageBox.Show("Scroll Lock");
}
else
{
    MessageBox.Show("No Scroll Lock");
}

 

 

Scroll Lock key detection for WPF

if (Keyboard.IsKeyToggled(Key.Scroll))
{
    MessageBox.Show("Scroll Lock");
}
else
{
    MessageBox.Show("No Scroll Lock");
}

 

 

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 static extern short GetKeyState(int keyCode);

    ///<summary>
    ///Get whether Scroll Lock key is presses or not. If pressed return true.
    ///</summary>
    public static bool IsScrollLock()
    {
        //145 means Scroll Lock key
        if ((GetKeyState(145) & 0x8001) != 0)
        {
            return true; //Scroll Lock
        }
        else
        {
            return false; //No Scroll Lock
        }
    }
}

Next, you can use following code to detect scroll lock key.

if (KeyboardUtil.IsScrollLock())
{
    System.Diagnostics.Debug.WriteLine("ScrollLock");
}
else
{
    System.Diagnostics.Debug.WriteLine("No ScrollLock");
}

→ 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.

 


日本語版