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

后端 未结 3 1109
一向
一向 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: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.

提交回复
热议问题