WPF problem with KeyEventArgs

A

Arne Garvander

The code below does not work. When I enter a $ sign, e.Key = 'D4' !
private void item_KeyUp(object sender, KeyEventArgs e)
{
char dollar = '$';
if (e.Key.Equals( dollar))
{
find();
}
}
 
D

Dr. WPF

Handle the KeyPress event instead. KeyDown and KeyUp return specific
key/scan code data; that is, exactly which key was pressed.

I think you're talking about Windows Forms, Pete. There is no KeyPress
event in WPF. You also don't get scan codes in WPF key events.
 
D

Dr. WPF

Agreed. The only thing in the post that indicated the OP was working with
the WPF version of KeyEventArgs was the title. They could have been much
clearer.
Hmm. Well, I just assumed that since the KeyEventArgs class isn't
Forms-specific (it's in System.Windows.Input, not System.Windows.Forms),
that it was shared between Forms and WPF, and had the same semantics
wherever it was used.

There are actually two very different KeyEventArgs classes, one in the Input
namespace and one in the Forms namespace. (This overlapping of class names
is pretty common between WPF and Windows Forms... especially in core areas
like input.)

A general rule is that if the namespace is System.Windows.Forms, then it is
WinForms specific, but if it is System.Windows.%AnythingElse%, then it is
WPF-specific. So the System.Windows.Input.KeyEventArgs class is WPF-specific.
I admit, I don't know enough about WPF to know why, if you "don't get scan
codes in WPF key events", the KeyEventArgs class would even be used.

The Key member of KeyEventArgs is used in other methods throughout the Input
namespace. It is simply an enum with friendly names for known keyboard keys.

There is a KeyInterop class with static methods that can be used to
translate a Key value to its Win32 virtual key and vice versa, but that is
about the extent of its usefulness.

There is no mechanism for translating a key event to its representative
character mapping (taking into consideration the current modifiers, etc).
Most input handling in WPF happens under the covers.

The KeyEventArgs class does have an internal member that identifies the scan
code, if someone cares to use reflection, but that comes with all the usual
warnings, of course. If someone really needs scan codes, they can process
input directly by specifying a handler for the InputManager's PreNotifyInput
and/or PostNotifyInput events.

This is an area where WPF could arguably be enhanced quite a bit. It would
be great to have a static interop method to which you could supply a
KeyEventArgs object and get back the simple char that results from the key
event and its currently active modifiers. Maybe we'll get something like that
in 4.0.

Cheers,
-dw
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top