WPF Equivalent to SendInput?

2019-06-10 01:54发布

Is there an equivalent to SendInput for WPF? I've looked into AutomationPeer classes but was not successfull.

I simply want to send a Keydown (the Enter Key). Simply raising the event (RaiseEvent) does not work in my scenario.

Here is what I have, which is working. I'd prefer to have a managed code alternative.

    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条回答
▲ chillily
2楼-- · 2019-06-10 02:16

You can emulate a keystroke like this:

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);

    }

You could then call it like this:

SendKey(myComboBox, Key.Enter);

I suppose you can put this in a static class somewhere, or even make an extension method out of it. However, I would argue that in most cases there is a more elegant way to accomplish this.

I hope this helps.

查看更多
登录 后发表回答