1

WPF 是否有与 SendInput 等效的方法?我研究过AutomationPeer课程,但没有成功。

我只是想发送一个 Keydown(回车键)。在我的场景中,简单地引发事件 ( 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;
4

1 回答 1

7

您可以模拟这样的击键:

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它。但是,我认为在大多数情况下,有一种更优雅的方式来实现这一点。

我希望这有帮助。

于 2012-11-23T21:36:53.400 回答