WPF向指定窗口发送键盘指令

本文介绍如何在WPF应用中使用System.Windows.Forms.SendKeys类来模拟发送键盘指令,解决VB库在WPF中不适用的问题。虽然此方法也可用于VB,但作者在寻找解决方案时遇到困扰。文中提到对相关API的深入理解留待日后探讨。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在网上的库大部分都是VB的那个发送键盘指令的库,那个在WPF里面是用不了的,WPF的话可以用System.Windows.Forms中的其实跟VB中的Microsoft.VisualBasic.Devices这个里面的SendKeys用法差不多一样,吐槽一下,新的这个也可以在VB中使用好像,我看MSDN中Forms中的SendKeys也能在 VB中用,真是这一个小问题浪费了我一下午的时间。贴上代码

[DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpClass, string lpszWindow);

        [DllImport("user32.dll ", EntryPoint = "SendMessage")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);


        const int WM_CHAR = 0x0102;
        const int WM_SETTEXT = 0x000C;
        const int VK_RETURN = 0x0d;


        private void xin(object sender, RoutedEventArgs e)
        {
            Thread.Sleep(3000);
            IntPtr handle = FindWindow(null, "vshost32.exe");
            handle = FindWindowEx(handle, IntPtr.Zero, "Edit", null);
            if (handle == IntPtr.Zero)
            {
                Console.WriteLine("没有找到句柄");
            //    return;
            }
            SendMessage(handle, WM_SETTEXT, IntPtr.Zero, "d");
  //          SendKeys.Send("{TAB}");
            //SendMessage(handle, WM_CHAR, (IntPtr)VK_RETURN, IntPtr.Zero);//Enter
            SendKeys.SendWait("{d}");
           // SendMessage(handle, WM_SETTEXT, IntPtr.Zero, "w");
        }

这里现在也还有很多我还不是很了解的地方,等以后有时间再说吧,现在要赶项目。
最后补充一下,它们其实就是很多个WIN32的API

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值