Question

I want to Recognize Ctrl+E keys pressed on a TextBox which is inside a UserControl ,For this am using the textbox_KeyDown(object sender, KeyEventArgs e) event and checking for the following condition

    if(e.KeyCode == Keys.E && Control.ModifierKeys == Keys.Control) 
    {
        //Code
    }

For some reason the first part of the if condition i.e (e.KeyCode == Keys.E) is returning false as e.keycode has Lbutton|ShifKey as its value.

1>Why is it not detecting the 'E' key press down ? 2>Should we handle this event diffrently as it as a UserConrol?

*Note:Above Code Worked fine if it is a normal Form.I also tried toggling the KeyPreview value of the form that hosts the userControl nothing seems to me working.

Can anybody please help me out on this. Thanks in Advance

Was it helpful?

Solution

You are just getting confusing information from the debugger. The Keys enum has the [Flags] attribute but it doesn't actually use bits to identify keys consistently. LButton|ShiftKey == 0x01|0x10 == 0x11 = Keys.ControlKey. And that's expected since you hit the Ctrl key first. It is the next keystroke that you want, when you press E while holding down Ctrl. But that won't come because the debugger break messed that up.

The best way is:

if (e.KeyData == (Keys.E | Keys.Control)) {
    // etc...
}

OTHER TIPS

It should be:

if (((e.KeyCode & Keys.E) == Keys.E) && e.Control)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top