按键时执行操作

本文关键字:操作 执行 | 更新日期: 2023-09-27 18:22:42

在我的程序中,我需要在按下键的同时执行一个操作。我已经搜索过了,但解决方案要么不适合c#,要么不适合表单,要么我无法理解它们。

有没有一个合适而简单的解决方案?

编辑:我正在使用WinForms,我希望在窗体集中并按下某个键时,重复执行一个操作。

按键时执行操作

首先,您需要提供更多信息,如果可能的话,还需要提供一些您已经尝试过的代码。但不管怎样,我还是会努力的
这个概念相对简单,您可以在表单中添加计时器,添加key_DOWN和key_UP事件(不按键)。若当前按下按键,则会生成一个类似于的bool,在keydown时将其值更改为true,在keyup时将其更改为false。当你拿着钥匙时,这将是真的。

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

**如果你试图在表单上制作一个简单的游戏,但你正在为窗口的输入延迟而挣扎(按住一个键,它会出现一次,等待,然后发送垃圾邮件)这个解决方案适用于此(第一次按下后没有暂停)。

你可以试试这个。


在Key down事件中,您将bool"buttonIsDown"设置为TRUE,并在Separate Thread中启动方法"DoIt"。只要bool"buttonIsDown"为true并且Form处于Focus上,"DoIt"方法内While循环中的代码就会运行。当Key Up事件被激发或Form失去焦点时,它停止。在那里你可以看到"buttonIsDown"被设置为false,这样While循环就停止了。


      //Your Button Status
      bool buttonIsDown = false;
      //Set Button Status to down
      private void button2_KeyDown(object sender, KeyEventArgs e)
        {
            Key key = sender as Key;
            if (key == Key.A)
            buttonIsDown = true;
            //Starts your code in an Separate thread.
            System.Threading.ThreadPool.QueueUserWorkItem(DoIt);
        }
      //Set Button Status to up
       private void button2_KeyUp(object sender, KeyEventArgs e)
        {
            Key key = sender as Key;
            if (key == Key.A)
            buttonIsDown = false;
        }
      //Method who do your code until button is up
      private void DoIt(object dummy)
      {
        While(buttonIsDown && this.Focused)
        {
            //Do your code
        }
      }