mohammed sameeh
mohammed sameeh

Reputation: 5089

how to detect two hot key in win form app like CTRL +C , CTRL+ W

my question is how to detect two hot keys in win form application CTRL +C,CTRL,K like visual studio commenting command

I need to simulate VS hot key For commenting a line of code

Upvotes: 1

Views: 1845

Answers (4)

mohammed sameeh
mohammed sameeh

Reputation: 5089

private bool _isFirstKeyPressedW = false;

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control & e.KeyCode == Keys.W) 
    {
        _isFirstKeyPressedW = true;
    }
    if (_isFirstKeyPressedW) 
    {
        if (e.Control & e.KeyCode == Keys.S) 
        {
            //write your code 
        } 
        else 
        {
            _isFirstKeyPressedW = e.KeyCode == Keys.W;
        }
    }
}

Upvotes: 1

Kirk
Kirk

Reputation: 5077

Simple way is... There is a Windows API Function called ProcessCmdKey, by overriding this function we can achieve what we want

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
   if (keyData == (Keys.Control | Keys.C)) {
      MessageBox.Show("You have pressed the shortcut Ctrl+C");
      return true;
   }
   return base.ProcessCmdKey(ref msg, keyData);
}

Microsoft Documentation can be found here

source

Upvotes: 1

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

if you want to handle Ctrl + C followed by Ctrl+ K you need to maintain a state variable.

Set the Form KeyPreview property to true and handle the Form KeyDown event.

Try This:

   this.KeyPreview=true;
   private bool isFirstKeyPressed= false;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.C)
        {               
            isFirstKeyPressed = true;                
        }


        if (isFirstKeyPressed)
        {
            if (e.Control && e.KeyCode == Keys.K)
            {
                MessageBox.Show("Ctrl+C and Ctrl+K pressed Sequentially");
                /*write your code here*/
                isFirstKeyPressed= false;
            }
        }
    }

Upvotes: 0

Kurubaran
Kurubaran

Reputation: 8902

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
   {

   }
}

Upvotes: 1

Related Questions