Jf *_*lac 0 .net c# keyboard wpf automation
是否有相当于WPF的SendInput?我看过AutomationPeer课,但没有成功.
我只想发送一个Keydown(Enter键).简单地引发event(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;
Run Code Online (Sandbox Code Playgroud)
小智 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);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用它:
SendKey(myComboBox, Key.Enter);
Run Code Online (Sandbox Code Playgroud)
我想你可以把它放在static class某个地方,甚至可以把extension method它拿出来.但是,我认为在大多数情况下,有一种更优雅的方法来实现这一目标.
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
2604 次 |
| 最近记录: |