简体   繁体   中英

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.

在此处输入图片说明

Any ideas?

 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.

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#

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM