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

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

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

4条回答
  •  被撕碎了的回忆
    2020-11-27 18:53

    Check State

    To check state of CapsLock, NumLock and ScrollLock keys you can use Control.IsKeyLocked method:

    var capsLockIsOn = Control.IsKeyLocked(Keys.CapsLock);
    

    Actively Show The State in UI in status bar

    Since the lock keys can be turn on or turn off when your application doesn't have focus handling keyboard events of the form is not enough to detect changes on the key lock state and you should also put your logic in some other places like activation event of your form or you need to register a global keyboard hook.

    As a simple and reliable solution you can check their status in Application.Idle event. You must detach your idle event handler when your form closed.

    public Form1()
    {
        InitializeComponent();
        Application.Idle += Application_Idle;
    }
    
    void Application_Idle(object sender, EventArgs e)
    {
        if (Control.IsKeyLocked(Keys.CapsLock))
            toolStripStatusLabel1.Text = "CapsLock is On";
        else
            toolStripStatusLabel1.Text = "";
    }
    
    protected override void OnFormClosed(FormClosedEventArgs e)
    {
        Application.Idle -= Application_Idle;
        base.OnFormClosed(e);
    }
    

提交回复
热议问题