WPF - Send Keys Redux

不问归期 提交于 2019-12-05 16:01:08

问题


So, I'm using a third-part wpf grid control that is hard-coded to only accept certain keystrokes to perform short-cut reactions and one of those is Shift-Tab. However, my user-base is used to hitting up arrow and down arrow and telling them 'no' isn't an option right now. So my only option I think is to intercept the preview key down and send a different key stroke combination.

Now, I am using the following code that I found on here to send a Tab when the user presses the Down arrow:

if (e.Key == Key.Down)
{
    e.Handled = true;
    KeyEventArgs eInsertBack = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab);
    eInsertBack.RoutedEvent = UIElement.KeyDownEvent;
    InputManager.Current.ProcessInput(eInsertBack);
}

However, this method is limited in that you don't seem to be able to simulate a press of the Shift Button? WPF seems to look at the Keyboard.Modifiers to be able to 'read' a Shift or Ctrl, but there doesn't seem to be any facility to Set the Keyboard.Modifiers programatically. Any help out there?


回答1:


I've created a little library that might probably help you out with mocking the Shift key:

http://wpfsendkeys.codeplex.com/

http://blogs.msdn.com/b/kirillosenkov/archive/2010/07/09/wpf-sendkeys-or-mocking-the-keyboard-in-wpf.aspx




回答2:


try this

System.Windows.Forms.SendKeys.SendWait("{Tab}");

In WPF Application, SendKeys.Send not working, But SendWait is working fine.




回答3:


Create a MockKeyboardDevice like this (kudos to Jared Parsons):

https://github.com/jaredpar/VsVim/blob/master/Test/VimCoreTest/Mock/MockKeyboardDevice.cs

Usage:

var modKey = ModifierKeys.Shift;
var device = new MockKeyboardDevice(InputManager.Current)
    {
        ModifierKeysImpl = modKey
    };
var keyEventArgs = device.CreateKeyEventArgs(Key.Tab, modKey);
...

A usage example:

https://github.com/jaredpar/VsVim/blob/master/Test/VimWpfTest/VimKeyProcessorTest.cs




回答4:


I simulate what you say fine using the following is this not what you mean?

public Window1()
{
    InitializeComponent();


    Loaded += new RoutedEventHandler(Window1_Loaded);
}

void Window1_Loaded(object sender, RoutedEventArgs e)
{
    WebBrowser1_PreviewKeyDown(this, new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 1, Key.LeftShift));
    WebBrowser1_PreviewKeyDown(this, new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 1, Key.Tab));
}

private void WebBrowser1_PreviewKeyDown(object sender, KeyEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.Key);
}

OUTPUT:

LeftShift
Tab


来源:https://stackoverflow.com/questions/1263006/wpf-send-keys-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!