如何编译可以在按住同一个键时重复击键的程序?

How do I compile a program that can repeat a keystroke while the same key is held?

我已经尝试了一段时间来制作一个简单的程序,可以在按住同一个键的同时重复发送一个键。我尝试在下面使用带有“Windows Forms”的示例,但我收到错误“找不到类型或命名空间“Key””,即使我已经包含了 System.ComponentModel.DataAnnotations,如据我了解Key应该是其中的一部分。我以前从未制作过 Windows 形式的程序,但据我所知,它基本上包括一个 GUI 和你的代码?我使用 windows 表单的唯一原因是因为我看到的示例使用了它,但如果它可以在常规 C# 程序中完成,那也很棒。

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.ComponentModel.DataAnnotations;

namespace spamkey2
{
    public partial class Form1 : Form
    {
        bool keyHold = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (keyHold)
            {
                //Do stuff
            }
        }

        private void Key_up(object sender, KeyEventArgs e)
        {
            Key key = (Key)sender;
            if (key == Key.A) //Specify your key here !
            {
                keyHold = false;
            }
        }

        private void Key_down(object sender, KeyEventArgs e)
        {
            Key key = (Key)sender;
            if (key == Key.A) //Specify your key here !
            {
                keyHold = true;
            }
        }
    }
}

使用此代码

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.ComponentModel.DataAnnotations;

namespace spamkey2
{
    public partial class Form1 : Form
    {
        bool keyHold = false;
        public Form1()
        {
            InitializeComponent();
            this.KeyDown += Key_down;
            this.KeyUp += Key_up;
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += Timer_Elapsed;
            timer.Interval = 100;
            timer.Start();
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (keyHold)
            {
                //Do stuff
                Console.WriteLine("Key A is down");
            }
        }

        private void Key_up(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.A) //Specify your key here !
            {
                keyHold = false;
            }
        }

        private void Key_down(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.A) //Specify your key here !
            {
                keyHold = true;
            }
        }
    }
}