4
votes

I've written a WPF touchscreen application. Within this application I've written a user control which is a touch screen keyboard.

I have all the keys working apart from the backspace. Obviously all the keys are buttons and on the backspace button click I'd like to send the back space key to the focused textbox.

I've tried the following but this just inserts a square character in my textbox:

private void buttonBackSpace_Click(object sender, RoutedEventArgs e)
{
    PresentationSource source = PresentationSource.FromDependencyObject(CurrentControl);
    //CurrentControl is my Textbox
    KeyEventArgs ke = new KeyEventArgs(Keyboard.PrimaryDevice, source, 0, Key.Back)
    {
        RoutedEvent = UIElement.KeyDownEvent
    };
    System.Windows.Input.InputManager.Current.ProcessInput(ke);
}

Any ideas? I'm using Visual Studio 2012 & Windows 8.

1
just guessing, what is the purpose of the 3rd timestamp parameter? Does it help if you increment it with every key press. - Jodrell
To be honest I don't know what that parameter is. Nothing different happens if I change or increment it. - Sun
presumably its used to synchronise KeyPress Events in some way. I was just clutching at straws in absence of an answer. - Jodrell

1 Answers

1
votes

I'm not sure if this is a typo or not, but I think your issue is that

KeyEventArgs ke = new KeyEventArgs(Keyboard.PrimaryDevice, source, 0, Key.Back)

Should actually be:

KeyEventArgs ke = new KeyEventArgs(Keyboard.PrimaryDevice, source, 0, Keys.Back)

I think the Keys enumeration is what you're actually looking for here.

EDIT: The above answer does not work. The below answer should, however, solve the problem.

private void buttonBackSpace_Click(object sender, RoutedEventArgs e)
{
    CurrentControl.Focus();
    keybd_event(BACK, 0, KEYEVENTF_KEYDOWN, 0);
    keybd_event(BACK, 0, KEYEVENTF_KEYUP, 0);
}
// Virtual Keypress Function
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public const int KEYEVENTF_KEYDOWN = 0x0001; //Key down flag
public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag
public const int BACK = 0x08; // Backspace keycode.