user3165438
user3165438

Reputation: 2661

C# Cannot handle Ctrl+K event of textbox

I would like to perform some actions when the user presses Ctrl + K on a textbox.

 private void subject_TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.K)
                  MessageBox.Show("!");
        }  

Nothing happens when I run it.

When I debug I can see that e.Control is true (this means I pressed Ctrl) but the e.KeyCode is not equivalent to K.

enter image description here

Any ideas?

Upvotes: 0

Views: 100

Answers (3)

Brendon
Brendon

Reputation: 334

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.K) && focusedTextbox == subject_TextBox)
        {
           //Some Code
        }
    }
private TextBox focusedTextbox = null;


 private void subject_TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            MethodName(e.KeyCode)
        } 
 private void MethodName(Keys keys)
    {
        focusedTextbox = (TextBox)sender;
    }

Use this code, this should work i have tested it myself and it will work, you will want to run the 'MethodName' method in each textbox, or if you can find a better way to change the 'focusedTextBox' field then do that hope this helped.

Upvotes: 1

user3165438
user3165438

Reputation: 2661

Really don't know what is the problem reason.
May the event is fired as soon as the Ctrl is pressed, without waiting to the K to be pressed as well.

However, when I use the same code in the TextBox_KeyUp event, it works fine.

Upvotes: 0

Proliges
Proliges

Reputation: 361

In the KeyDown event, you just ask for the 'state' of the keyboard.

You might want to check out this topic:

Capture multiple key downs in C#

Upvotes: 0

Related Questions