如何无休止地检查按键是否被按下?

时间:2016-01-13 12:02:51

标签: c# winforms key

我正在制作一个小程序,显示numlock或capslock是打开还是关闭(因为我的笔记本电脑没有那些LED,所以我觉得制作这样的东西会很有趣)。我试图实现的是,如果按键被按下,文本就会改变。到目前为止,我所拥有的程序显示它们是否在运行程序之前打开或关闭。如何让程序对变化作出反应?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {

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


        public Form1()
        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            looper();
        }

        public void looper()
        {
            cLock_check();
            nLock_check();
            sLock_check();
        }

        public void cLock_check()
        {
            bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;

            if (CapsLock)
                lbl_cLock_onOff.Text = "ON";
            else
                lbl_cLock_onOff.Text = "OFF";
        }
        public void nLock_check()
        {
            bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
            if (NumLock)
                lbl_nLock_onOff.Text = "ON";
            else
                lbl_nLock_onOff.Text = "OFF";
        }
        public void sLock_check()
        {
            bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;
            if (ScrollLock)
                lbl_sLock_onOff.Text = "ON";
            else
                lbl_sLock_onOff.Text = "OFF";
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您应该实现全局键盘挂钩,如this article中所述。将vkCodeVK_NUMLOCKVK_CAPITALVK_SCROLL进行比较,然后调用您的相关更新功能。

答案 1 :(得分:1)

创建一个计时器对象,给它一个合理的间隔(对于大多数'响应' UI问题300毫秒是合适的),并设置Tick处理程序以调用looper方法:

Timer checkState;

public Form1()
{
    InitializeComponent();

    checkState = new Timer { Interval = 300};
    checkState.Tick += (o,e) => looper();
    chechState.Start();
}