How can I find the state of NumLock, CapsLock and ScrollLock in .NET?

后端 未结 4 1314
忘掉有多难
忘掉有多难 2020-11-27 18:41

How can I find the state of NumLock, CapsLock and ScrollLock keys in .NET?

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 19:04

    Import the WinAPI function GetKeyState

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    public static extern short GetKeyState(int keyCode);
    

    and then you can use it like that

    bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
    bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
    bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
    

    EDIT: the above is for framework 1.1, for framework 2.0 + you can use

    Control.IsKeyLocked

提交回复
热议问题