Search code examples
c#datagridviewkeypress

How to capture keystroke(s) pressed in certain time period for DataGridView keypress event?


I need to capture keystroke(s) that are pressed in certain time period for example say 300 ms. So when i press 'a' and within 300 ms i press 'b' then i need string "ab". But if i press key 'c' after 300 ms of pressed 'b' then i want "c".

I need this for quick jump to DataGridView's cell that starts with quick pressed key(s).


Solution

  • I'm not entirely sure I understand your question, but I believe you want a way to execute one block of code if two keys were pressed, or another block of code if three keys were pressed. Additionally, you want each key press to be within 300ms of one another. If I've understood, then this code should do what you want:

    private System.Diagnostics.Stopwatch Watch = new System.Diagnostics.Stopwatch();
    private string _KeysPressed;
    public string KeysPressed
    {
        get { return _KeysPressed; }
        set 
        {
            Watch.Stop();
            if (Watch.ElapsedMilliseconds < 300)
                _KeysPressed += value;
            else
                _KeysPressed = value;
            Watch.Reset();
            Watch.Start();
        }
    }        
    private void KeyUpEvent(object sender, KeyEventArgs e)
    {
        KeysPressed = e.KeyCode.ToString();
        if (KeysPressed == "AB")
            lblEventMessage.Text = "You've pressed A B";
        else if (KeysPressed == "ABC")
            lblEventMessage.Text = "You've pressed A B C";
        else
            lblEventMessage.Text = "C-C-C-COMBOBREAKER!!!";
    }
    

    This code assumes a label, lblEventMessage, and something to trigger the KeyUp event (I went with a textbox).