按键检测并在C#中发送

时间:2018-07-24 19:44:37

标签: c# visual-studio keypress onkeypress

因此,我想做的是查找是否完全按下了空格键,而我想放开空格键,然后以大约10毫秒的延迟再次按下多个键。我已尝试阅读并理解此链接(https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx),但它仍在混淆帮助吗?我是C#的新手,但是我对Pascal有一些经验,我发现它非常相似 (由于我的计算机不允许我更新到Windows 8.1,因此使用Visual Studio 2015)

1 个答案:

答案 0 :(得分:-1)

10ms delay表示每秒100次,没人能做到。

关键事件按以下顺序发生:

  1. KeyDown
  2. KeyPress
  3. KeyUp

事件KeyDownKeyUp使用KeyEventArgs,而KeyPressKeyPressEventArgs

KeyEventArgs可以详细说明同时按下多少键。 KeyEventArgs.KeyCodeKeys,它是一个[Flags]枚举,它可以包含多个键,例如CTRL + SHift + F + G

如果您的热键是Ctrl + Shift + Space,则可以使用以下命令进行检查:

var hotkeyPressed = e.Control && e.Shift && e.KeyCode == Keys.Space;

如果您的热键是Ctrl + F10 + Space,则可以使用以下命令进行检查:

var hotkeyPressed = e.Control && e.KeyCode == (Keys.Space | Keys.F10);

但不要使用:

var hotkeyPressed = e.Control && e.KeyCode.HasFlag(Keys.F10) && e.KeyCode.HasFlag(Keys.Space); // e.KeyCode probably contains other flags

KeyPressEventArgs.KeyChar是一个字符串,请查看源代码,重点关注其注释

  [ComVisible(true)]
  public class KeyPressEventArgs : EventArgs
  {
    ...
    /// <summary>Gets or sets the character corresponding to the key pressed.</summary>
    /// <returns>The ASCII character that is composed. For example, if the user presses SHIFT + K, this property returns an uppercase K.</returns>
    public char KeyChar { get; set; }
    ...
  }

要使用哪个事件,取决于您的要求。 这是KeyDown中的示例代码:

    private int counting = 0, limit = 10;
    private void txt_KeyDown(object sender, KeyEventArgs e)
    {
        if (!e.KeyCode.HasFlag(Keys.Space)) //check if your expected key is pressed
        {
            counting = 0;
            return;
        }
        //start counting
        counting++;

        if (counting > limit)
        {
            e.Handled = true;
            //do you business work, like: Send something somewhere

        }
        else
        {
            //do something else, like: show the number 'counting' in GUI
        }
    }

如果要限制下一个空格的时间跨度,请使用Timer

    private void txt_KeyDown(object sender, KeyEventArgs e)
    {
        timer1.Stop();
        if (!e.KeyCode.HasFlag(Keys.Space))
        {
            counting = 0;
            return;
        }
        //start counting
        timer1.Start();
        counting++;

        if (counting > limit)
        {
            e.Handled = true;
            //do you business work, like: Send something somewhere

        }
        else
        {
            //do something else, like: show the number 'counting' in GUI
        }
    }

    //timer1.Interval = 100; //100ms timeout. user has to press space again within 100ms
    private void timer1_Tick(object sender, EventArgs e)
    {
        counting = 0;
    }