c#控制windows 鼠标移动、点击和输入

首先可以使用ViewWizard获取窗口的类名和Title

ViewWizard下载地址:https://download.csdn.net/download/th_num/10737076
在这里插入图片描述

图中:窗口标题和窗口类名,可以使用下面的程序获取窗口的句柄。

MouseHookHelper 鼠标相关的函数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing; //Point

namespace FDTDControl
{

    public class MouseHookHelper
    {

        #region 根据句柄寻找窗体并发送消息

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        //参数1:指的是类名。参数2,指的是窗口的标题名。两者至少要知道1个
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);

        [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hwnd, uint wMsg, int wParam, string lParam);

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


      
        #endregion

        #region 获取窗体位置
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;                             //最左坐标
            public int Top;                             //最上坐标
            public int Right;                           //最右坐标
            public int Bottom;                        //最下坐标
        }
        #endregion

        #region 设置窗体显示形式

        public enum nCmdShow : uint
        {
            SW_NONE,//初始值
            SW_FORCEMINIMIZE,//:在WindowNT5.0中最小化窗口,即使拥有窗口的线程被挂起也会最小化。在从其他线程最小化窗口时才使用这个参数。
            SW_MIOE,//:隐藏窗口并激活其他窗口。
            SW_MAXIMIZE,//:最大化指定的窗口。
            SW_MINIMIZE,//:最小化指定的窗口并且激活在Z序中的下一个顶层窗口。
            SW_RESTORE,//:激活并显示窗口。如果窗口最小化或最大化,则系统将窗口恢复到原来的尺寸和位置。在恢复最小化窗口时,应用程序应该指定这个标志。
            SW_SHOW,//:在窗口原来的位置以原来的尺寸激活和显示窗口。
            SW_SHOWDEFAULT,//:依据在STARTUPINFO结构中指定的SW_FLAG标志设定显示状态,STARTUPINFO 结构是由启动应用程序的程序传递给CreateProcess函数的。
            SW_SHOWMAXIMIZED,//:激活窗口并将其最大化。
            SW_SHOWMINIMIZED,//:激活窗口并将其最小化。
            SW_SHOWMINNOACTIVATE,//:窗口最小化,激活窗口仍然维持激活状态。
            SW_SHOWNA,//:以窗口原来的状态显示窗口。激活窗口仍然维持激活状态。
            SW_SHOWNOACTIVATE,//:以窗口最近一次的大小和状态显示窗口。激活窗口仍然维持激活状态。
            SW_SHOWNOMAL,//:激活并显示一个窗口。如果窗口被最小化或最大化,系统将其恢复到原来的尺寸和大小。应用程序在第一次显示窗口的时候应该指定此标志。
        }

        public const int SW_HIDE = 0;
        public const int SW_SHOWNORMAL = 1;
        public const int SW_SHOWMINIMIZED = 2;
        public const int SW_SHOWMAXIMIZED = 3;
        public const int SW_MAXIMIZE = 3;
        public const int SW_SHOWNOACTIVATE = 4;
        public const int SW_SHOW = 5;
        public const int SW_MINIMIZE = 6;
        public const int SW_SHOWMINNOACTIVE = 7;
        public const int SW_SHOWNA = 8;
        public const int SW_RESTORE = 9;

        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        #endregion

        #region 控制鼠标移动

        //移动鼠标 
        public const int MOUSEEVENTF_MOVE = 0x0001;
        //模拟鼠标左键按下 
        public const int MOUSEEVENTF_LEFTDOWN = 0x0002;
        //模拟鼠标左键抬起 
        public const int MOUSEEVENTF_LEFTUP = 0x0004;
        //模拟鼠标右键按下 
        public const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
        //模拟鼠标右键抬起 
        public const int MOUSEEVENTF_RIGHTUP = 0x0010;
        //模拟鼠标中键按下 
        public const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
        //模拟鼠标中键抬起 
        public const int MOUSEEVENTF_MIDDLEUP = 0x0040;
        //标示是否采用绝对坐标 
        public const int MOUSEEVENTF_ABSOLUTE = 0x8000;

        [Flags]
        public enum MouseEventFlag : uint
        {
            Move = 0x0001,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            RightDown = 0x0008,
            RightUp = 0x0010,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            XDown = 0x0080,
            XUp = 0x0100,
            Wheel = 0x0800,
            VirtualDesk = 0x4000,
            Absolute = 0x8000
        }

        //[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        [DllImport("user32.dll")]
        public static extern bool SetCursorPos(int X, int Y);
        [DllImport("user32.dll")]
        public static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        #endregion

        #region 获取坐标钩子

        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int X;
            public int Y;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }

        public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        //安装钩子
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        //卸载钩子
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        //调用下一个钩子
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);


        /// <summary>   
        /// 获取鼠标的坐标   
        /// </summary>   
        /// <param name="lpPoint">传址参数,坐标point类型</param>   
        /// <returns>获取成功返回真</returns>   
        [DllImport("User32")]
        public extern static bool GetCursorPos(ref Point lpPoint);


        #endregion

    }
}

主函数调用MouseHookHelper实现鼠标点击和字符输入

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing; //Point


namespace FDTDControl
{
    class Program
    {


        private static void LeftMouseClick(MouseHookHelper.POINT pointInfo)
        {

            //先移动鼠标到指定位置
            MouseHookHelper.SetCursorPos(pointInfo.X, pointInfo.Y);

            //按下鼠标左键
            MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTDOWN,
                        pointInfo.X,
                        pointInfo.Y, 0, 0);

            //松开鼠标左键
            MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTUP,
                        pointInfo.X ,
                        pointInfo.Y , 0, 0);

        }

        //实时打印鼠标的相对(x,y)位置
        private static void PrintMousePoint(int x,int y)
        {
            int x1 = x;
            int y1 = y;
            while (true)
            {

                Point p = new Point(1, 1);//定义存放获取坐标的point变量   
                MouseHookHelper.GetCursorPos(ref p);

                if (x1 != p.X && y1 != p.Y)
                {
                    System.Console.WriteLine("相对于父类窗口 dx:");
                    System.Console.WriteLine(p.X - x);
                    System.Console.WriteLine("相对于父类窗口 dy:");
                    System.Console.WriteLine(p.Y - y);
                    x1 = p.X;
                    y1 = p.Y;
                }


            }
        }

        static void Main(string[] args)
        {

            IntPtr awin = MouseHookHelper.FindWindow("HwndWrapper[DefaultDomain;;6e277d51-7be9-45b5-879e-37e195024ec9]", 
                "FDTDControl - Microsoft Visual Studio(管理员)");
            if (awin == IntPtr.Zero)
            {
                MessageBox.Show("没有找到窗体");

         
                return;
            }
            else
            {
                //MessageBox.Show(String.Format("{0:D}",awin));

                MouseHookHelper.RECT rc = new MouseHookHelper.RECT();

                MouseHookHelper.GetWindowRect(awin,ref rc);

                int width = rc.Right - rc.Left;  //窗口的宽度
                int height = rc.Bottom - rc.Top; //窗口的高度
                int x = rc.Left;
                int y = rc.Top;



                MouseHookHelper.SetForegroundWindow(awin);  // 设置当前窗口置前
                MouseHookHelper.ShowWindow(awin, MouseHookHelper.SW_SHOWNOACTIVATE);//4、5

                LeftMouseClick(new MouseHookHelper.POINT()  //点击鼠标
                {
                    X = x,
                    Y = y,
                });

             
                /*
                IntPtr editBtn= MouseHookHelper.FindWindowEx(awin, IntPtr.Zero, null, null);
                MouseHookHelper.RECT rc2 = new MouseHookHelper.RECT();
                MouseHookHelper.GetWindowRect(editBtn, ref rc2);
                int x2 = rc2.Left;
                int y2 = rc2.Top;
                LeftMouseClick(new MouseHookHelper.POINT()  //点击鼠标
                {
                    X = x2,
                    Y = y2,
                });
                */


                
                // 实时获取鼠标的位置
                //PrintMousePoint(x, y);

                LeftMouseClick(new MouseHookHelper.POINT()  //点击鼠标(x+466,y+466)
                {
                    X = x+466,
                    Y = y+466,
                });

                // 在鼠标点击的地方打印数字
                SendKeys.SendWait("12");
                return;

            }
        }
    }
}

可能遇到的问题

  • 找不到using System.Windows.Forms;
    在这里插入图片描述
    在上图中,引用右键点击 --》“添加引用”
    在这里插入图片描述
WinAPI-Wrapper 模拟鼠标点击 用于模拟鼠标移动点击、窗口操作等的Windows API包装器类。 API 下面是一些可用的方法的总结。有更多的方法和类,比下面列出的要多,但目的是要大致了解包装器能做什么。要查看关于特定方法的详细信息和参数的详细信息,请查看代码本身,因为它的注释很好。 Mouse.cs public static void LeftClick(); public static void RightClick(); public static void MiddleClick(); public static void LeftDown(); public static void LeftUp(); public static void RightDown(); public static void RightUp(); public static void MiddleDown(); public static void MiddleUp(); public static void Move(int x, int y); public static void LeftDrag(Point point1, Point point2, int interval, int lag); Window.cs public static bool DoesExist(string windowTitle); public static IntPtr Get(string windowTitle); public static IntPtr GetFocused(); public static void SetFocused(IntPtr hWnd); public static bool IsFocused(IntPtr hWnd); public static void Move(IntPtr hWnd, int x, int y); public static void Resize(IntPtr hWnd, int width, int height); public static void Hide(IntPtr hWnd); public static void Show(IntPtr hWnd); public static Rectangle GetDimensions(IntPtr hWnd); public static Size GetSize(IntPtr hWnd); public static Point GetLocation(IntPtr hWnd); public static string GetTitle(IntPtr hWnd); public static void SetTitle(IntPtr hWnd, string title); public static void Maximize(IntPtr hWnd); public static void Minimize(IntPtr hWnd); public static void Normalize(IntPtr hWnd); public static Bitmap Screenshot(IntPtr hWnd); public static void RemoveMenu(IntPtr hWnd); public static void Close(IntPtr hWnd); public static void DisableCloseButton(IntPtr hWnd); public static void DisableMaximizeButton(IntPtr hWnd); public static void DisableMinimizeButton(IntPtr hWnd); public static void EnableMouseTransparency(IntPtr hWnd); public static Point ConvertToWindowCoordinates(IntPtr hWnd, int x, int y); public static Point GetCoordinateRelativeToWindow(IntPtr hWnd); Desktop.cs public static Bitmap Screenshot(); public static void HideTaskBar(); public static void ShowTaskBar(); public static int GetWidth(); public static int GetHeight(); 使用 在windows api文件夹中编译代码会产生一个.dll文件。任何引用这个.dll的ccode都可以使用包装器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝鲸123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值