2

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!

Diverti
  • 765
  • 6
  • 10

2 Answers2

2

For counting Keypresses on Background you need Keyboard Hook. Have a look at these link:

https://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook

C# : Keyboard Hook

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • Now i can count the X and Y in the background but i can't use the two keys in another window. I can't type, i can't use it in game. Any idea? – Diverti Jan 27 '18 at 14:34
  • google **send keys** you can find useful information. also have a look at this link: [https://www.codeproject.com/Articles/18366/Sending-Keystrokes-to-another-Application-in-C](https://www.codeproject.com/Articles/18366/Sending-Keystrokes-to-another-Application-in-C) – Ashkan Mobayen Khiabani Jan 27 '18 at 15:04
2

Try this Global Mouse and Keyboard Library

I believe it contains all you need.

Mohammad Javad Noori
  • 1,187
  • 12
  • 23