【.Net码农】WPF 模拟UI 键盘录入

WPF 模拟UI 键盘录入

     开发WinForm 应用程序时可以利用SendKeys 类方便的模拟键盘录入操作。那么在WPF 中如何为控件实现键盘模拟呢?本篇将使用WPF SendKeys 实现和WinForm 中相同的效果。

     首先将WpfSendKeys.dll 加入到项目References 中,在XAML 中加入两个Textbox 和一个Button 如下代码。

<Window x:Class="WpKeyboard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Loaded="Window_Loaded" KeyDown="Window_KeyDown"  
        x:Name="mainWin" Height="350" Width="525">
    <Grid>
        <TextBox x:Name="tb1" FontSize="50" Margin="73,12,84,218" />
        <TextBox x:Name="tb2" FontSize="50" Margin="73,119,84,117" />
        <Button x:Name="btn" Content="Auto Click and Change Font Color" 
                Click="btn_Click"  Margin="73,229,84,36" />
    </Grid>
</Window>

     打开C#程序,添加System.Windows.Input.Test 命名空间。定义SendToUIThread 方法用于将键盘指令发送到WPF 控件上。在Window_Loaded 中通过调用SendToUIThread 方法向Textbox 中逐一写入"Hello World!" 字符,并对字符进行拷贝,最后实现自动点击Button 完成更换字体颜色的操作。其中字符串拷贝工作是通过判断模拟键盘输入的内容为"Control+C",即将字符串拷贝到第二个Textbox 中。

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 WpKeyboard
{
    /// <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 btn_Click(object sender, RoutedEventArgs e)
        {
            tb1.Foreground = new SolidColorBrush(Colors.Red);
            tb2.Foreground = new SolidColorBrush(Colors.Blue);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(3000);

                SendToUIThread(tb1, "Hello");
                Thread.Sleep(1000);

                SendToUIThread(tb1, " W");
                Thread.Sleep(1000);

                SendToUIThread(tb1, "o");
                Thread.Sleep(1000);

                SendToUIThread(tb1, "r");
                Thread.Sleep(1000);

                SendToUIThread(tb1, "ld!");
                Thread.Sleep(1000);

                SendToUIThread(mainWin, "^c");
                Thread.Sleep(1000);

                SendToUIThread(btn, "{ENTER}");
            });
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Control) && e.Key == Key.C)
            {
                tb2.Text = tb1.Text;
            }
        }
    }
}

动态演示

程序运行后无需点击任何按键,程序自动完成图中操作。

Capture

源代码下载

WpKeyboard.zip
作者:李敬然(Gnie)
出处: {GnieTech} (http://www.cnblogs.com/gnielee/)
版权声明:本文的版权归作者与博客园共有。转载时须注明本文的详细链接,否则作者将保留追究其法律责任。




https://social.msdn.microsoft.com/forums/onedrive/zh-CN/ef67e6b1-677b-41ea-866e-61a73b907df8/wpf

  • 问题

  • 用Win32的API么?

            //发送消息方法
            [DllImport("User32.dll", EntryPoint = "SendMessage")]
            public static extern int SendMessage(IntPtr hwnd, int msg, int wParam, int sb);

    这样去使用么?WPF没有自己的发送消息给指定窗口的方法么?

     

    我现在想在自己的WPF窗口中发送上下左右的箭头按键消息给指定的应用程序,比如“PowerPoint.exe”。


    jakeyjia

答案

  • 1)如果你想触发窗口里的keyDown事件,你可以使用RaiseEvent,比如:

    KeyEventArgs keyEventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.A);
    keyEventArgs.RoutedEvent = UIElement.KeyDownEvent;
    RaiseEvent(keyEventArgs);
    

    这样就会触发你想要的KeyDown事件,传递的参数相当于你按下了键盘的A键。

    2)如果你是想要模拟键盘的输入,你可以用UI Automation,这个是可以做到的,但是这个不是WPF特有的。

    3)在CodePlex上有些library实现了SendKeys,你可以参考:

    http://wpfsendkeys.codeplex.com/

    http://testapi.codeplex.com/

    http://blogs.msdn.com/b/kirillosenkov/archive/2010/07/09/wpf-sendkeys-or-mocking-the-keyboard-in-wpf.aspx

    在我就不知道WPF有什么特殊的方法了。


    Sheldon _Xiao[MSFT]
    MSDN Community Support |  Feedback to us
     Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值