简体   繁体   English

我如何在C#中计算背景中的按键数

[英]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. 我正在使用C#和.NET 4为我的朋友制作一个小程序。 I am a bengineer in coding. 我是一名编码工程师。 I want to count the number of pressing X and Y on the keyboard. 我想计算键盘上按X和Y的次数。 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. 程序现在正在运行,如果按下X或Y,则计数器只会旋转。

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! 非常感谢你!

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 https://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook

C# : Keyboard Hook C#:键盘钩

Try this Global Mouse and Keyboard Library 试试这个全局鼠标和键盘库

I believe it contains all you need. 我相信它包含您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM