当前位置:   article > 正文

c#模拟键盘鼠标操作_c# sendmessage模拟鼠标键盘

c# sendmessage模拟鼠标键盘
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace HeavenBenchmarkTest
{
    public class FromInfo
    {
        public FromInfo(string title, int handle)
        {
            this.title = title;
            this.handle = handle;
        }
        private string title;
        private int handle;
        public string Title
        {
            get { return title; }
            set { title = value; }
        }
        public int Handle
        {
            get { return handle; }
            set { handle = value; }
        }
    }
    public delegate bool CallBack(int hwnd, int lParam);
    public static class SendMouseEvent
    {
        [DllImport("user32.dll")]
        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
        [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
        }


        public static void Send(MouseEventFlag mouseEventFlag, int dx, int dy, uint dwData)
        {
            mouse_event(mouseEventFlag | MouseEventFlag.Absolute, dx, dy, dwData, UIntPtr.Zero);
        }


        public static void MoveTo(uint scceenTop, uint screenLeft)
        {
            int x = scceenTop == 0 ? 0 : (int)((float)scceenTop / (float)Screen.PrimaryScreen.Bounds.Height * (float)65535);
            int y = screenLeft == 0 ? 0 : (int)((float)screenLeft / (float)Screen.PrimaryScreen.Bounds.Width * (float)65535);
            mouse_event(MouseEventFlag.Move | MouseEventFlag.Absolute, x, y, 0, UIntPtr.Zero);
        }


        public static void Click()
        {
            LeftDown(); LeftUp();
        }


        public static void DoubleClick()
        {
            Click(); Click();
        }


        public static void LeftDown()
        {
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
        }


        public static void LeftUp()
        {
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
        }


        public static void RightDown()
        {
            mouse_event(MouseEventFlag.RightDown, 0, 0, 0, UIntPtr.Zero);
        }


        public static void RightUp()
        {
            mouse_event(MouseEventFlag.RightUp, 0, 0, 0, UIntPtr.Zero);
        }


        public static void MiddleDown()
        {
            mouse_event(MouseEventFlag.RightDown, 0, 0, 0, UIntPtr.Zero);
        }


        public static void MiddleUp()
        {
            mouse_event(MouseEventFlag.RightUp, 0, 0, 0, UIntPtr.Zero);
        }
    }




    public partial class Form1 : Form
    {
        //获取类的名字 
        [DllImport("user32.dll")]
        private static extern int GetClassName(
            IntPtr hWnd,//句柄 
            StringBuilder lpString, //类名 
            int nMaxCount //最大值 
            );


        //根据坐标获取窗口句柄 
        [DllImport("user32")]
        private static extern IntPtr WindowFromPoint(
        Point Point  //坐标 
        );


        [DllImport("user32", SetLastError = true)]
        public static extern int GetWindowText(
            IntPtr hWnd,//窗口句柄 
            StringBuilder lpString,//标题 
            int nMaxCount //最大值 
            );
        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImport("user32.dll")]
        private static extern bool SetCursorPos(int X, int Y);
        [DllImport("user32.dll")]
        private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
        [DllImport("user32.dll")]
        private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
        [DllImport("user32.dll")]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);
        //ShowWindow参数
        private const int SW_SHOWNORMAL = 1;
        private const int SW_RESTORE = 9;
        private const int SW_SHOWNOACTIVATE = 4;
        //SendMessage参数
        private const int WM_KEYDOWN = 0X100;
        private const int WM_KEYUP = 0X101;
        private const int WM_SYSCHAR = 0X106;
        private const int WM_SYSKEYUP = 0X105;
        private const int WM_SYSKEYDOWN = 0X104;
        private const int WM_CHAR = 0X102;


        private const int WS_VISIBLE = 268435456;//窗体可见
        private const int WS_MINIMIZEBOX = 131072;//有最小化按钮
        private const int WS_MAXIMIZEBOX = 65536;//有最大化按钮
        private const int WS_BORDER = 8388608;//窗体有边框
        private const int GWL_STYLE = (-16);//窗体样式
        private const int GW_HWNDFIRST = 0;
        private const int GW_HWNDNEXT = 2;
        private const int SW_HIDE = 0;
        private const int SW_SHOW = 5;
        [DllImport("User32.dll")]
        private extern static int GetWindow(int hWnd, int wCmd);
        [DllImport("User32.dll")]
        private extern static int GetWindowLongA(int hWnd, int wIndx);
        [DllImport("user32.dll")]
        private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private extern static int GetWindowTextLength(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern int ShowWindow(int hwnd, int nCmdShow);


        [DllImport("user32")]
        public static extern int EnumWindows(CallBack x, int y);
        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.None;//设置窗体无边框样式
        }


        string[] Config = { "RunPorgramName", "RunTimer", "Terminator1", "Terminator2", "CoordinateY", "CoordinateX", "CheckTheTime", "CheckRunPorgram", "CheckFilePathName", "CoordinateY2", "CoordinateX2","FindPathName"};
        int TestToalTimer = 0;
        int bootTm2 = 1;
        int SeelpTm2 = 1;
        private void Form1_Load(object sender, EventArgs e)
        {
            if(RedCfg("config.ini")==false)
            {
                WriteFile("FAIL.TXT");
                MessageBox.Show("Config.ini Read Err!!","系统提示");
                Application.Exit();
            }
            CallBath(Config[0]);
            label1.BackColor = Color.Green;
            label1.ForeColor = Color.GreenYellow;
            label1.Font = new Font("宋体",20f,FontStyle.Bold);
            label1.Text = "测试倒计时:" + Config[1] + "秒";
            TestToalTimer = Convert.ToInt32(Config[1]);
            timer2.Enabled = true;
            timer3.Enabled = false;
        }
        public void CallBath(string CallBathName)
        {
            string targetDir = string.Empty;
            targetDir = System.IO.Directory.GetCurrentDirectory() + @"\";
            Process proc = null;
            try
            {
                proc = new Process();
                proc.StartInfo.WorkingDirectory = targetDir;
                proc.StartInfo.FileName = CallBathName;
                proc.Start();
                proc.WaitForExit();
            }
            catch(Exception ex)
            {
                MessageBox.Show("批处理执行出错"+ex.Message+ex.StackTrace.ToString());
                WriteFile("FAIL.TXT");
                Application.Exit();
            }
        }
        public void WriteFile(string CfgFileNmae)
        {
            try
            {
                FileStream fs = new FileStream(CfgFileNmae,FileMode.Create,FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs,Encoding.Default);
                sw.WriteLine(CfgFileNmae);
                sw.Close();
                fs.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Write File Err!!"+ex.Message);
                Application.Exit();
            }
        }


        public bool RedCfg(string CfgFileName)
        {
            bool Flag = false;
            string[] KeyWord = { "RunPorgramName", "RunTimer", "Terminator1", "Terminator2", "CoordinateY", "CoordinateX", "CheckTheTime", "CheckRunPorgram", "CheckFilePathName", "CoordinateY2", "CoordinateX2", "FindPathName" };
            FileStream fs = new FileStream(CfgFileName,FileMode.Open,FileAccess.Read);
            StreamReader sr = new StreamReader(fs,Encoding.Default);//默认读取文件可识别中文
            try
            {
                string Temp = string.Empty;
                while((Temp=sr.ReadLine())!=null)
                {
                    string[] Array = Temp.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    int n = 0;
                    foreach(string k in KeyWord)
                    {
                        if(k==Array[0])
                        {
                            Config[n] = Array[1];
                            break;
                        }
                        n++;
                    }
                }
                sr.Close();
                fs.Close();
                Flag = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Flag = false;
                return Flag;
            }
            return Flag;
        }


        public void KillProcess(string RunBathName)
        {
            Process[] pro = Process.GetProcesses(); //获取已开启的所有进程
            for(int i=0;i<pro.Length;i++)
            {
                //判断此进程是否是要查看的进程
                if(pro[i].ProcessName.ToString().ToString()==RunBathName)
                {
                    pro[i].Kill();//结束进程
                }
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if(File.Exists(Config[8]))
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                KillProcess(Config[2]);
                KillProcess(Config[3]);
                WriteFile("FAIL.TXT");
                Application.Exit();
            }
            if (IsSetBoolXY ==true)
            {
                timer3.Enabled = true;   
            }
            if(TestToalTimer==0)
            {
                 timer1.Enabled = false;
                 timer2.Enabled = false;
                 KillProcess(Config[2]);
                 KillProcess(Config[3]);
                 WriteFile("PASS.TXT");
                 Application.Exit();
            }
            TestToalTimer--;
            label1.Text = "测试倒计时:" + Convert.ToString(TestToalTimer) + "秒";
        }
        bool IsSetBoolXY = false;
        private void timer2_Tick(object sender, EventArgs e)
        {
            if(bootTm2==1)
            {
                uint x = 0, y = 0;
                x = Convert.ToUInt32(Config[4]);
                y = Convert.ToUInt32(Config[5]);
                SendMouseEvent.MoveTo(x, y);
                SendMouseEvent.Click();
                timer1.Enabled = true;
                bootTm2 = 2;
                this.timer2.Interval = 1000;
            }
           if(SeelpTm2==Convert.ToUInt32(Config[6]))
           {
                CallBath(Config[7]);
                SeelpTm2 = 1;
                IsSetBoolXY = true;
            }
            SeelpTm2++;
            
        }
        private void timer3_Tick(object sender, EventArgs e)
        {
            /*uint x2 = 0, y2 = 0;
            x2 = Convert.ToUInt32(Config[9]);
            y2 = Convert.ToUInt32(Config[10]);
            SendMouseEvent.MoveTo(x2, y2);
            SendMouseEvent.Click();
            IsSetBoolXY = false;*/
            IntPtr myIntPtr = new IntPtr(0);
            myIntPtr = FindWindow(null, "Unigine Heaven Benchmark 4.0 Basic (Direct3D11)");
            if (myIntPtr != IntPtr.Zero)
            {
                ShowWindow(myIntPtr, 3);
                SetForegroundWindow(myIntPtr);
            }
            else
            {
                MessageBox.Show("没找到窗口");
            } 
            if (File.Exists(Config[11])) File.Delete(Config[11]);
            timer3.Enabled = false;
        }
    }
}
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号