当我做一些研究时,同样的资源出现在我身上,所以我认为你在回答中所做的事情是非常有效的。
我看了看,发现了另一种方法,使用 Win32 API。我不得不引入一些线程和小的延迟,因为由于某种原因,关键事件没有按正确的顺序重播。总的来说,我认为这个解决方案更简单,而且我还想出了如何包含修饰键(通过使用 Get/SetKeyboardState 函数)。大写字母正在工作,键盘快捷键也应如此。
启动演示应用程序,按 键1 space 2 space 3 tab 4 space 5 space 6
,然后单击按钮会产生以下结果:
xml:
<UserControl x:Class="WpfApplication1.KeyEventQueueDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" >
<StackPanel>
<TextBox x:Name="tbOne" Margin="5,2" />
<TextBox x:Name="tbTwo" Margin="5,2" />
<Button x:Name="btn" Content="Replay key events" Margin="5,2" />
</StackPanel>
</UserControl>
后面的代码:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
namespace WpfApplication1
{
/// <summary>
/// Structure that defines key input with modifier keys
/// </summary>
public struct KeyAndState
{
public int Key;
public byte[] KeyboardState;
public KeyAndState(int key, byte[] state)
{
Key = key;
KeyboardState = state;
}
}
/// <summary>
/// Demo to illustrate storing keyboard input and playing it back at a later stage
/// </summary>
public partial class KeyEventQueueDemo : UserControl
{
private const int WM_KEYDOWN = 0x0100;
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[DllImport("user32.dll")]
static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
static extern bool SetKeyboardState(byte[] lpKeyState);
private IntPtr _handle;
private bool _isMonitoring = true;
private Queue<KeyAndState> _eventQ = new Queue<KeyAndState>();
public KeyEventQueueDemo()
{
InitializeComponent();
this.Focusable = true;
this.Loaded += KeyEventQueueDemo_Loaded;
this.PreviewKeyDown += KeyEventQueueDemo_PreviewKeyDown;
this.btn.Click += (s, e) => ReplayKeyEvents();
}
void KeyEventQueueDemo_Loaded(object sender, RoutedEventArgs e)
{
this.Focus(); // necessary to detect previewkeydown event
SetFocusable(false); // for demo purpose only, so controls do not get focus at tab key
// getting window handle
HwndSource source = (HwndSource)HwndSource.FromVisual(this);
_handle = source.Handle;
}
/// <summary>
/// Get key and keyboard state (modifier keys), store them in a queue
/// </summary>
void KeyEventQueueDemo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (_isMonitoring)
{
int key = KeyInterop.VirtualKeyFromKey(e.Key);
byte[] state = new byte[256];
GetKeyboardState(state);
_eventQ.Enqueue(new KeyAndState(key, state));
}
}
/// <summary>
/// Replay key events from queue
/// </summary>
private void ReplayKeyEvents()
{
_isMonitoring = false; // no longer add to queue
SetFocusable(true); // allow controls to take focus now (demo purpose only)
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); // set focus to first control
// thread the dequeueing, because the sequence of inputs is not preserved
// unless a small delay between them is introduced. Normally the effect this
// produces should be very acceptable for an UI.
Task.Run(() =>
{
while (_eventQ.Count > 0)
{
KeyAndState keyAndState = _eventQ.Dequeue();
Application.Current.Dispatcher.BeginInvoke((Action)(() =>
{
SetKeyboardState(keyAndState.KeyboardState); // set stored keyboard state
PostMessage(_handle, WM_KEYDOWN, keyAndState.Key, 0);
}));
System.Threading.Thread.Sleep(5); // might need adjustment
}
});
}
/// <summary>
/// Prevent controls from getting focus and taking the input until requested
/// </summary>
private void SetFocusable(bool isFocusable)
{
tbOne.Focusable = isFocusable;
tbTwo.Focusable = isFocusable;
btn.Focusable = isFocusable;
}
}
}