PDA

View Full Version : WPF keyboard input question



Kommi
May 25th, 2007, 11:47 AM
Ok I just started developing using Windows Presentation Foundation and have a little problem adding a shortcut key ability to my app. The problem is that I have my main panel throw a KeyDown event everytime a key is pressed. In the code for “keyDown” I then handle a few special conditions (user pressing crtl + a char).
I am using the code from a Kirupa article


public void keyDown(object sender, KeyEventArgs e)
{
// Ctrl + B
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.B))
{
MessageBox.Show("bold");
}
// Ctrl + U
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.U))
{
MessageBox.Show("underline");
}
// Ctrl + L
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.L))
{
MessageBox.Show("link");
}
// Ctrl + R
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.R))
{
MessageBox.Show("random");
}
}


The problem is that if my cursor is in a TextBox, and I press a crtl+b, it will get handled by the KeyDown and the ‘B’ will get inputed into the TextBox. How can I prevent this behavior. Obviously I do not want the ‘B’ to get typed into the TextBox if one of the special conditions in my keyboardEvents method is met.

kirupa
May 25th, 2007, 01:39 PM
Hi Kommi,
If you do not want the key you pressed to appear, you should place your above code into the function for handing theKeyUp. In the tutorial code, you will see that the KeyUpEventHandler is to handle key combinations.

Cheers!
Kirupa =)

Kommi
May 25th, 2007, 03:15 PM
Hi Kommi,
If you do not want the key you pressed to appear, you should place your above code into the function for handing theKeyUp. In the tutorial code, you will see that the KeyUpEventHandler is to handle key combinations.

Cheers!
Kirupa =)

Hey Kirupa, actually the correct solution that someone else told me was to include a
e.Handled = true;
statement. That way the keypress event never gets to the TextBox.

kirupa
May 25th, 2007, 03:24 PM
Kommi - I tried setting e.Handled = true, and that didn't seem to work. The textbox still displayed the letter that was pressed. Does it work for you, and if it does, would it be possible for you to post your code?

Thanks,
Kirupa :rambo: