Link to home
Start Free TrialLog in
Avatar of gamesmeister
gamesmeisterFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Capturing the correct keys in a User Control KeyDown event

Hi,

I have a User Control containing a text box, and I'd like to capture a Ctrl-X key press on that text box. However, whatever I try with regards to capturing the keys doesn't seem to work.

My code currently looks like this:

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
      if ((e.KeyData == Keys.X) && (e.Modifiers == Keys.Control))
            Console.Write("Ctrl-X pressed");
}

I know the event is being fired correctly, but it's not successfully matching both the X key and the Ctrl key when pressed together.

I've tried other combinations but nothing seems to work - can anyone help please

Thanks
Gerry
ASKER CERTIFIED SOLUTION
Avatar of Thunder_scream
Thunder_scream

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Thunder_scream
Thunder_scream

actually the "key preiview" seems not to be needed.

hope this solves your problem.
Avatar of gamesmeister

ASKER

No, unfortunately that didn't work either.

However, I've just noticed something really bizarre. When I press Ctrl-Z, the above conditional is regarded as true: i.e., "Ctrl-X pressed" is written to the console. The same thing happens if I press Ctrl-Y

Haven't a clue what's going on here - my keyboard is mapped normally

Btw, your code works fine if I put it in a KeyDown event in a textbox directly on a Form. It's only on my user control that it's not working. Any ideas why that might be?

Thanks for your help
Gerry
gamesmeister,

could you perhaps post the rest of the code?
SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Most like they key you are trying to capture is being captured by something else. Confirm this easily by trying to trap another key that isn't already being captured, such as Ctrl-L.

To get around the problem you'll probably have to turn Key Preview off (maybe on more than one control).
Doh...schoolboy error - I thought I'd cleared all the Ctrl-X events from the menu but missed one

Thanks for the help everyone