首页 > 编程语言 >c# 通过win32控制窗口

c# 通过win32控制窗口

时间:2024-11-13 23:30:15浏览次数:1  
标签:IntPtr 窗口 c# 句柄 WM win32 int Zero public

  1. 引入需要的接口

        /// <summary>
        /// 查找窗口
        /// </summary>
        /// <param name="hwnd">窗口句柄</param>
        /// <param name="title">窗口标题</param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(IntPtr hwnd, string title);

        /// <summary>
        /// 移动窗口
        /// </summary>
        /// <param name="hwnd">窗口句柄</param>
        /// <param name="x">起始位置X</param>
        /// <param name="y">起始位置Y</param>
        /// <param name="nWidth">窗口宽度</param>
        /// <param name="nHeight">窗口高度</param>
        /// <param name="rePaint">是否重绘</param>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern void MoveWindow(IntPtr hwnd, int x, int y, int nWidth, int nHeight, bool rePaint);

        /// <summary>
        /// 获取窗口矩形
        /// </summary>
        /// <param name="hwnd">窗口句柄</param>
        /// <param name="rect"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetWindowRect(IntPtr hwnd, out Rectangle rect);

        /// <summary>
        /// 向窗口发送信息
        /// </summary>
        /// <param name="hwnd">窗口句柄</param>
        /// <param name="msg">信息</param>
        /// <param name="wParam">高字节</param>
        /// <param name="lParam">低字节</param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hwnd, int msg, uint wParam, uint lParam);

        public const int WM_CLOSE = 0x10; //关闭命令
        public const int WM_KEYDOWN = 0x0100;//按下键
        public const int WM_KEYUP = 0x0101;//按键起来
        public const int VK_RETURN = 0x0D;//回车键
        public const int WM_SETTEXT = 0x000C;//发送消息
        public const int WM_INITDIALOG = 0x0110;//初始化
        public const int WM_LBUTTONDOWN = 0x0201;//按下鼠标左键 
        public const int WM_LBUTTONUP = 0x0202;//释放鼠标左键
        public const int WM_LBUTTONDBLCLK = 0x203; //双击鼠标左键
        public const int WM_RBUTTONDOWN = 0x204;//按下鼠标右键
        public const int WM_RBUTTONUP = 0x205;//释放鼠标右键
        public const int WM_RBUTTONDBLCLK = 0x206;//双击鼠标右键
        public static bool IsWorking = false;
        /// <summary>
        /// 对话框标题
        /// </summary>
        public static string[] titles = new string[4] { "Error", "提示", "错误", "警告" };



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

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

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
      
  1. 封装的常用方法
 /// <summary>
 /// 查找和移动窗口
 /// </summary>
 /// <param name="title">窗口标题</param>
 /// <param name="x">起始位置X</param>
 /// <param name="y">起始位置Y</param>
 public static void FindAndMoveWindow(string title, int x, int y)
 {
     Thread t = new Thread(() =>
     {
         IntPtr msgBox = IntPtr.Zero;
         while ((msgBox = FindWindow(IntPtr.Zero, title)) == IntPtr.Zero) ;
         Rectangle r = new Rectangle();
         GetWindowRect(msgBox, out r);
         MoveWindow(msgBox, x, y, r.Width - r.X, r.Height - r.Y, true);
     });
     t.Start();
 }
 /// <summary>
 /// 查找和关闭窗口
 /// </summary>
 /// <param name="title">标题</param>
 public static void FindAndKillWindow(string title)
 {
     IntPtr ptr = FindWindow(IntPtr.Zero, title);
     if (ptr != IntPtr.Zero)
     {
         int ret = PostMessage(ptr, WM_CLOSE, 0, 0);
         Thread.Sleep(1000);
         ptr = FindWindow(IntPtr.Zero, title);
         if (ptr != IntPtr.Zero)
         {
             PostMessage(ptr, WM_KEYDOWN, VK_RETURN, 0);
             PostMessage(ptr, WM_KEYUP, VK_RETURN, 0);
         }
     }
 }

 /// <summary>
 /// 查找和关闭窗口
 /// </summary>
 public static void FindAndKillWindow()
 {
     Thread t = new Thread(() =>
     {
         while (IsWorking)
         {
             //按标题查找
             foreach (string title in titles)
             {
                 FindAndKillWindow(title);
             }
             Thread.Sleep(3000);
         }
     });
     t.Start();
 }
 /// <summary>
 /// 查找窗口
 /// </summary>
 /// <param name="title">窗口标题</param>
 /// <returns>True表示找到窗口,false则未找到</returns>
 public static IntPtr? FindWindows(string title)
 {
     IntPtr ptr = FindWindow(IntPtr.Zero, title);
     if (ptr != IntPtr.Zero)
     {
         return ptr;
     }
     return null;
 }
 public static bool FindWindows()
 {
     Thread t = new Thread(() =>
     {
         while (IsWorking)
         {
             //按标题查找
             foreach (string title in titles)
             {
                 FindWindows(title);
             }
             Thread.Sleep(3000);
         }
     });
     t.Start();
     return false;
 }
  1. 根据窗口的关系获取控件
    可以通过spy++获取控件的类型名称
  var ptr=FindWindows("打开");

  //IntPtr hwnd = FindWindow("#32770 (对话框)", "MainWindow");     //FindWindow只查找顶层窗口
  //IntPtr htextbox = FindWindowEx(ptr.Value, IntPtr.Zero, "wxWindowClassNR", null);//(当前为第一层)IntPtr.Zero则表示获得第一个子窗口。第三个参数表示你需要找的子窗口的类型,第四个参数一般为null。
  //IntPtr htextbox2 = FindWindowEx(hwnd, IntPtr.Zero, "wxWindowClassNR", null);//(当前为第一层)IntPtr.Zero则表示获得第一个子窗口。第三个参数表示你需要找的子窗口的类型,第四个参数一般为null。
  //IntPtr htextbox2 = FindWindowEx(hwnd, htextbox, "EDIT", null);//填上次获得的句柄,可以得到下一个的句柄。

  //SendMessage(ptr.Value, WM_SETTEXT, IntPtr.Zero, "123232");//发送消息

   IntPtr htextbox2 = FindWindowEx(ptr.Value, IntPtr.Zero, "ComboBoxEx32", null);//填上次获得的句柄,可以得到下一个的句柄。
  IntPtr htextbox22 = FindWindowEx(htextbox2, IntPtr.Zero, "ComboBox", null);//填上次获得的句柄,可以得到下一个的句柄。
  IntPtr edit = FindWindowEx(htextbox22, IntPtr.Zero, "Edit", null);//填上次获得的句柄,可以得到下一个的句柄。
  //SendMessage(edit, WM_SETTEXT, IntPtr.Zero, "D:\\work\\code");//发送消息
  //SendMessage(edit, WM_SETTEXT, IntPtr.Zero, "C:\\Users\\xx\\Desktop\\t\\WeChat_20241109200005.mp4");//发送消息
  SendMessage(edit, WM_SETTEXT, IntPtr.Zero, "C:\\Users\\xx\\Desktop\\t\\test.mp4");//发送消息

  IntPtr openBtn = FindWindowEx(ptr.Value, IntPtr.Zero, "Button", null);//填上次获得的句柄,可以得到下一个的句柄。

  //SendMessage(openBtn, WM_KEYDOWN, IntPtr.Zero, "D:\\work\\code");//发送消息

  SendMessage(openBtn, WM_LBUTTONDOWN, IntPtr.Zero, null);//鼠标按下按钮
  SendMessage(openBtn, WM_LBUTTONUP, IntPtr.Zero, null);//释放鼠标

[参考]
c#获取句柄,并对第三方软件的输入框和按钮进行控制

标签:IntPtr,窗口,c#,句柄,WM,win32,int,Zero,public
From: https://www.cnblogs.com/ives/p/18545071

相关文章

  • Proj. CDeepFuzz Paper Reading: Checker Bug Detection and Repair in Deep Learning
    3.TensorGuard:ARAG-BasedMulti-agentframeworktodetectandfixDLCheckerBugsRAGDesignrelevantcontextualinformationfromalargecorpusofcodechangesInput:therootcauseofthecheckerbugqueriedOutput:codechangeBasedon:Sentence-tra......
  • Ubuntu VNC
    局域网和没网情况用VNC,没网时用一根网线连接主机和被控端同时设置ip为同一网段。其他情况用向日葵。VNC主控端装Viewer,被控端装Server。Viewer有很多,也很容易装,推荐https://www.realvnc.com/en/connect/download/viewer/Server也有很多,但是网上很多教程一远程,什么鬼系统界面(对......
  • vscode + typora + picgo 搭建高效博客(cnblog)工作流
    vscode+typora+picgo搭建高效博客(cnblog)工作流笔者最初在cnblog上面发了很多随笔(水文),后面感觉广告有点多,并且难于管理文章,于是破罐破摔(不要学我)搭建了自己的博客。后来,我折腾过wordpress、jeklly、githubPages(hexo)和giteePages等等,既放不下cnblog上的流量与互动(......
  • Linux cpu hotplug
    背景Readthefuckingsourcecode!--By鲁迅Apictureisworthathousandwords.--By高尔基说明:Kernel版本:4.14ARM64处理器使用工具:SourceInsight3.5,Visio1.介绍LinuxCPU热插拔,支持在系统启动后,关闭任意一个secondarycpu(在ARM架构中,CPU0为bootcpu,不能被......
  • C++中的方法宏定义
    #defineCORE_INIT(fn)__define_core_initcall(fn)这一行代码是一个宏定义,用于将fn传递给__define_core_initcall宏或函数。具体解释如下:#define:定义一个宏,用于将宏名替换为对应的代码片段。CORE_INIT(fn):这是宏的名称和参数。CORE_INIT是宏名,fn是参数,表示函数或代......
  • LeetCode 3341. Find Minimum Time to Reach Last Room I
    原题链接在这里:https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/description/题目:Thereisadungeonwith nxm roomsarrangedasagrid.Youaregivena2Darray moveTime ofsize nxm,where moveTime[i][j] representsthe minimum ......
  • C语言编程 1.11 寻找素数对
     #include<stdio.h>#include<math.h>intsushu(longlongn)        {            longlongsqrt_n=sqrt(n);            for(longlongi=2;i<=sqrt_n;i++)                {                 ......
  • 基于华为云FunctionGraph和ModelArts的智能动漫头像生成:从自拍到AI风格化的编程
    文章目录1引言2背景介绍2.1华为云FunctionGraph与ModelArts简介3项目准备3.1注册与登录华为云账号4实验步骤4.1首先我们配置云主机4.2安装FunctionGraph插件4.3创建函数4.4部署函数4.5函数配置委托4.6函数配置触发器4.7函数添加依赖包4.8订阅模型并部署A......
  • css2D变换用法
    文章目录CSS2D变换详解与代码案例一、CSS2D变换的基本属性二、transform属性的使用三、变换原点的设置四、代码案例1.移动元素2.旋转元素3.缩放元素4.倾斜元素5.多重变换五、CSS2D变换的应用场景CSS2D变换详解与代码案例CSS2D变换是CSS3引入的一组功能......
  • 24.11.12 JavaScript2
    prompt()confirm()这些函数会阻止js解析器(js解析器执行引擎读取运行js)执行不要使用2history对象历史记录对象对应浏览器前进后退按钮history在历史记录里back前进forward后退go0当前文档负数后......