Mantas Daškevičius
Mantas Daškevičius

Reputation: 324

How to endlessly check if key was pressed?

I was making a small program that shows if numlock or capslock was on or off (because my laptop doesn't have those LEDs so I touhgt it would be interesting to make something like this). What I was trying to achieve is that text would change if key was pressed or not. What I have so far is program showing if they was on or off before running the program it self. How to make program react to changes?

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";
        }
    }
}

Upvotes: 2

Views: 120

Answers (2)

Gabriel Negut
Gabriel Negut

Reputation: 13960

You should implement a global keyboard hook, as described in this article. Compare vkCode to VK_NUMLOCK, VK_CAPITAL and VK_SCROLL and call your relevant update function.

Upvotes: 2

Jens Meinecke
Jens Meinecke

Reputation: 2940

Create a timer object, give it a reasonable interval (For most 'responsive' UI issues 300 msec is appropriate), and set the Tick handler to call the looper method:

Timer checkState;

public Form1()
{
    InitializeComponent();

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

Upvotes: 1

Related Questions