Search code examples
c#countbackgroundkeypress

How can i count the number of keypress in the background in C#


I am using C# and .NET 4 to make a little program for my friend. I am a bengineer in coding. I want to count the number of pressing X and Y on the keyboard. I managed to make it running in the background, but i have problem with counting. I tried searching for functions that may help me, but i didn't find anyting. The program now running and if X or Y is pressed down, the counter just spinning.

Here's what i have:

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.Threading;
using System.Windows.Input;

namespace gombszamlalo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        bool fut = true;

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread TH = new Thread(billentyuzet);
            CheckForIllegalCrossThreadCalls = false;
            TH.SetApartmentState(ApartmentState.STA);
            TH.Start();
        }
        public int x = 0;
        public int y = 0;

        void billentyuzet()
        {
            while (fut)
            {
                if ((Keyboard.GetKeyStates(Key.X) & KeyStates.Down) > 0)
                {
                    x++;
                    label4.Text = x.ToString();
                }
                if ((Keyboard.GetKeyStates(Key.Y) & KeyStates.Down) > 0)
                {
                    y++;
                    label5.Text = y.ToString();
                }
                if ((Keyboard.GetKeyStates(Key.F6) & KeyStates.Down) > 0)
                {
                    fut = false;
                }
            }
        }

I would be very happy, if somebody can help me to fix this code. Thank you very much!


Solution

  • Try this Global Mouse and Keyboard Library

    I believe it contains all you need.