how not to allow multiple keystokes received at one key press?

后端 未结 3 1090
一向
一向 2020-12-20 20:31

when we press a key and keep pressing it the keypress and keydown event continuously fires. Is there a way to let these fire only after a complete cycle ,eg keydown and the

相关标签:
3条回答
  • 2020-12-20 21:08

    To prevent a key from firing multiple-times when held down : you must use the SuppressKeyPress property like so :

    bool isKeyRepeating = false;
    
    public void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if (isKeyRepeating)
        {
            e.SuppressKeyPress = true;
        }
        else
        {
            isKeyRepeating = true;
        }
    
    }
    
    public void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        isKeyRepeating = false;
    }
    

    See : KeyEventArgs..::.Handled Property ... and ... KeyEventArgs..::.SuppressKeyPress Property .... for relevant information

    0 讨论(0)
  • 2020-12-20 21:18

    You can do it application-wide by filtering the key down messages with IMessageFilter. Here's an example:

      public partial class Form1 : Form, IMessageFilter {
        public Form1() {
          InitializeComponent();
          Application.AddMessageFilter(this);
          this.FormClosed += (s, e) => Application.RemoveMessageFilter(this);
        }
    
        private Keys mLastKey = Keys.None;
    
        public bool PreFilterMessage(ref Message m) {
          if (m.Msg == 0x100 || m.Msg == 0x104) {
            // Detect WM_KEYDOWN, WM_SYSKEYDOWN
            Keys key = (Keys)m.WParam.ToInt32();
            if (key != Keys.Control && key != Keys.Shift && key != Keys.Alt) {
              if (key == mLastKey) return true;
              mLastKey = key;
            }
          }
          else if (m.Msg == 0x101 || m.Msg == 0x105) {
            // Detect WM_UP, WM_SYSKEYUP
            Keys key = (Keys)m.WParam.ToInt32();
            if (key == mLastKey) mLastKey = Keys.None;
          }
          return false;
        }
      }
    

    One thing I pursued is the repeat count in the WM_KEYDOWN message. Oddly this didn't work on my machine, it was 1 for repeating keys. Not sure why.

    0 讨论(0)
  • 2020-12-20 21:19

    Declare a boolean isKeyDown, in theKeyDown Event, set the boolean to true. In the KeyUp event, set the boolean to false.

    This is sample code

    bool isKeyDown=false;
    public void control_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if(isKeyDown)
          return;
        isKeyDown=true;
        // do what you want to do
    }
    
    public void control1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
    {
       isKeyDown=false;
       // do you key up event, if any. 
    }
    
    0 讨论(0)
提交回复
热议问题