WPF等效于SendInput?

时间:2012-11-23 19:14:17

标签: c# .net wpf keyboard automation

是否有相当于WPF的SendInput?我查看了AutomationPeer课程,但没有成功。

我只想发送一个Keydown(Enter键)。简单地提升事件(RaiseEvent)在我的方案中不起作用。

这就是我所拥有的,这是有效的。我更喜欢使用托管代码替代。

    private void comboSelectionChanged(object sender, SelectionChangedEventArgs args)
    {
        ((ComboBox)sender).Focus();
        // send keydown
        INPUT input = new INPUT();
        input.type = INPUT_KEYBOARD;
        input.union.keyboardInput.wVk = 0x0D;
        input.union.keyboardInput.time = 0;
        SendInput(1, ref input, Marshal.SizeOf(input));
    }

    [DllImport("user32.dll", SetLastError = true)]
    private static extern int SendInput(int nInputs, ref INPUT mi, int cbSize);

    [StructLayout(LayoutKind.Sequential)]
    private struct INPUT
    {
        public int type;
        public INPUTUNION union;
    };

    [StructLayout(LayoutKind.Explicit)]
    private struct INPUTUNION
    {
        [FieldOffset(0)]
        public MOUSEINPUT mouseInput;
        [FieldOffset(0)]
        public KEYBDINPUT keyboardInput;
    };

    [StructLayout(LayoutKind.Sequential)]
    private struct MOUSEINPUT
    {
        public int dx;
        public int dy;
        public int mouseData;
        public int dwFlags;
        public int time;
        public IntPtr dwExtraInfo;
    };

    [StructLayout(LayoutKind.Sequential)]
    private struct KEYBDINPUT
    {
        public short wVk;
        public short wScan;
        public int dwFlags;
        public int time;
        public IntPtr dwExtraInfo;
    };

    private const int INPUT_MOUSE = 0;
    private const int INPUT_KEYBOARD = 1;

1 个答案:

答案 0 :(得分:6)

你可以模仿这样的按键:

public void SendKey(UIElement sourceElement, Key keyToSend)
    {

        KeyEventArgs args = new KeyEventArgs(InputManager.Current.PrimaryKeyboardDevice, PresentationSource.FromVisual(sourceElement), 0, keyToSend);

        args.RoutedEvent = Keyboard.KeyDownEvent;
        InputManager.Current.ProcessInput(args);

    }

然后您可以这样称呼它:

SendKey(myComboBox, Key.Enter);

我想你可以把它放在static class的某个地方,甚至可以用它来extension method。但是,我认为在大多数情况下,有一种更优雅的方法可以实现这一目标。

我希望这会有所帮助。