版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/yangyisen0713/article/details/18355375
Winform中如果想模拟键盘录入可以用SendKeys类,在WPF中一样可以,只需引用WpfSendKeys.dll即可。
1.添加WpfSendKeys.dll的引用;
2.MainWindow.xaml代码如下:
<Window x:Class="WPFKey.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Loaded="Window_Loaded"
x:Name="mainWin" Height="301" Width="237">
<Grid>
<TextBox x:Name="textbox1" FontSize="20" Margin="2,10,0,219" />
<Button x:Name="Change" Content="Button" HorizontalAlignment="Left" Margin="56,159,0,0" VerticalAlignment="Top" Width="121" Height="32" Click="Change_Click" />
</Grid>
</Window>
3.MainWindow.xaml.cs代码如下:
using System;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Input.Test;
using System.Windows.Media;
using System.Windows.Threading;
namespace WPFKey
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void SendToUIThread(UIElement element, string text)
{
element.Dispatcher.BeginInvoke(
new Action(() => { SendKeys.Send(element, text); }),
DispatcherPriority.Input
);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(_ =>
{
SendToUIThread(textbox1, "Happy");
Thread.Sleep(1000);
SendToUIThread(textbox1, " N");
Thread.Sleep(1000);
SendToUIThread(textbox1, "e");
Thread.Sleep(1000);
SendToUIThread(textbox1, "w");
Thread.Sleep(1000);
SendToUIThread(textbox1, " Year!");
Thread.Sleep(1000);
SendToUIThread(Change, "{ENTER}");
});
}
private void Change_Click(object sender, RoutedEventArgs e)
{
textbox1.Foreground = new SolidColorBrush(Colors.Red);
}
}
}
效果如图: