Kendall Frey
Kendall Frey

Reputation: 44316

Simulating Key Presses in WPF

I am developing an on-screen numpad for a WPF touch app. This will appear in a Popup. When a button is pressed, it should send a keystroke to the application, making it look as though the user was typing into a TextBox. This is my code:

// 'key' is set beforehand
InputManager.Current.ProcessInput(new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, Environment.TickCount, key) { RoutedEvent = Control.KeyDownEvent });

This is called within the Button.Click event handler.

So far only Key.Back has worked. None of the digit keys work, and neither does Key.Decimal.

EDIT: I thought using SendKeys would solve the problem, but it just does the same thing.

Why aren't my digit buttons working? I have verified that the correct Key is being passed.

Upvotes: 4

Views: 11113

Answers (2)

Following our discussions in comments, I suggest you consider an approach like this. I don't know the full requirement, but splitting the functionality up and making the application less monolithic is always a good approach!

First up, a pseudo-UML diagram would be this:

Class depedendency diagram

Your three functions would be implemented as follows (pseudocode):

UserControl1.InsertCharacter(string character)
{
    textBox1.Text = textBox1.Text.Insert(textBox1.CaretIndex, character); 
    this.ValidateInput();
}

UserControl1.ValidateInput()
{
    // Perform validation
}

UserControl1.OnKeyDown()
{
    // Perform validation
    this.ValidateInput();
}

UserControl2.AppendCharacter(string clickedCharacter)
{
    this.userControl1.InsertCharacter(clickedCharacter); 
}

To further decouple UserControl2 from UserControl1 as I mentioned you could use eventing patterns such as .NET events or EventAggregator.

Upvotes: 1

Raj Ranjhan
Raj Ranjhan

Reputation: 3917

Take a look at http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b657618e-7fc6-4e6b-9b62-1ffca25d186b/. WPF text box has issues handling certain keys.

From the article:

var eventArgs = new TextCompositionEventArgs(Keyboard.PrimaryDevice, 
new TextComposition(InputManager.Current, Keyboard.FocusedElement, key));  
eventArgs.RoutedEvent = TextInputEvent;  

InputManager.Current.ProcessInput(eventArgs); 

Upvotes: 0

Related Questions