C# 模拟键盘、鼠标操作外部程式(模拟用户操作3DMARK)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013934107/article/details/84110260

1.FROM1 CLASS SOURCE CODE:

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.Data.SqlClient;
using System.Collections;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;//启动模拟鼠标键盘操作

namespace _3DMARK_Test
{
    public delegate bool CallBack(int hwnd, int lParam);
    public partial class Form1 : Form
    {
        public List<String> cfg=new List<String>();
        public int Windows_X = 0;//设置X座标
        public int Windows_Y = 0;//设置Y座标
        public int TestTime = 0;

        #region bVk参数 常量定义

        public const byte vbKeyLButton = 0x1;    // 鼠标左键
        public const byte vbKeyRButton = 0x2;    // 鼠标右键
        public const byte vbKeyCancel = 0x3;     // CANCEL 键
        public const byte vbKeyMButton = 0x4;    // 鼠标中键
        public const byte vbKeyBack = 0x8;       // BACKSPACE 键
        public const byte vbKeyTab = 0x9;        // TAB 键
        public const byte vbKeyClear = 0xC;      // CLEAR 键
        public const byte vbKeyReturn = 0xD;     // ENTER 键
        public const byte vbKeyShift = 0x10;     // SHIFT 键
        public const byte vbKeyControl = 0x11;   // CTRL 键
        public const byte vbKeyAlt = 18;         // Alt 键  (键码18)
        public const byte vbKeyMenu = 0x12;      // MENU 键
        public const byte vbKeyPause = 0x13;     // PAUSE 键
        public const byte vbKeyCapital = 0x14;   // CAPS LOCK 键
        public const byte vbKeyEscape = 0x1B;    // ESC 键
        public const byte vbKeySpace = 0x20;     // SPACEBAR 键
        public const byte vbKeyPageUp = 0x21;    // PAGE UP 键
        public const byte vbKeyEnd = 0x23;       // End 键
        public const byte vbKeyHome = 0x24;      // HOME 键
        public const byte vbKeyLeft = 0x25;      // LEFT ARROW 键
        public const byte vbKeyUp = 0x26;        // UP ARROW 键
        public const byte vbKeyRight = 0x27;     // RIGHT ARROW 键
        public const byte vbKeyDown = 0x28;      // DOWN ARROW 键
        public const byte vbKeySelect = 0x29;    // Select 键
        public const byte vbKeyPrint = 0x2A;     // PRINT SCREEN 键
        public const byte vbKeyExecute = 0x2B;   // EXECUTE 键
        public const byte vbKeySnapshot = 0x2C;  // SNAPSHOT 键
        public const byte vbKeyDelete = 0x2E;    // Delete 键
        public const byte vbKeyHelp = 0x2F;      // HELP 键
        public const byte vbKeyNumlock = 0x90;   // NUM LOCK 键

        //常用键 字母键A到Z
        public const byte vbKeyA = 65;
        public const byte vbKeyB = 66;
        public const byte vbKeyC = 67;
        public const byte vbKeyD = 68;
        public const byte vbKeyE = 69;
        public const byte vbKeyF = 70;
        public const byte vbKeyG = 71;
        public const byte vbKeyH = 72;
        public const byte vbKeyI = 73;
        public const byte vbKeyJ = 74;
        public const byte vbKeyK = 75;
        public const byte vbKeyL = 76;
        public const byte vbKeyM = 77;
        public const byte vbKeyN = 78;
        public const byte vbKeyO = 79;
        public const byte vbKeyP = 80;
        public const byte vbKeyQ = 81;
        public const byte vbKeyR = 82;
        public const byte vbKeyS = 83;
        public const byte vbKeyT = 84;
        public const byte vbKeyU = 85;
        public const byte vbKeyV = 86;
        public const byte vbKeyW = 87;
        public const byte vbKeyX = 88;
        public const byte vbKeyY = 89;
        public const byte vbKeyZ = 90;

        //数字键盘0到9
        public const byte vbKey0 = 48;    // 0 键
        public const byte vbKey1 = 49;    // 1 键
        public const byte vbKey2 = 50;    // 2 键
        public const byte vbKey3 = 51;    // 3 键
        public const byte vbKey4 = 52;    // 4 键
        public const byte vbKey5 = 53;    // 5 键
        public const byte vbKey6 = 54;    // 6 键
        public const byte vbKey7 = 55;    // 7 键
        public const byte vbKey8 = 56;    // 8 键
        public const byte vbKey9 = 57;    // 9 键


        public const byte vbKeyNumpad0 = 0x60;    //0 键
        public const byte vbKeyNumpad1 = 0x61;    //1 键
        public const byte vbKeyNumpad2 = 0x62;    //2 键
        public const byte vbKeyNumpad3 = 0x63;    //3 键
        public const byte vbKeyNumpad4 = 0x64;    //4 键
        public const byte vbKeyNumpad5 = 0x65;    //5 键
        public const byte vbKeyNumpad6 = 0x66;    //6 键
        public const byte vbKeyNumpad7 = 0x67;    //7 键
        public const byte vbKeyNumpad8 = 0x68;    //8 键
        public const byte vbKeyNumpad9 = 0x69;    //9 键
        public const byte vbKeyMultiply = 0x6A;   // MULTIPLICATIONSIGN(*)键
        public const byte vbKeyAdd = 0x6B;        // PLUS SIGN(+) 键
        public const byte vbKeySeparator = 0x6C;  // ENTER 键
        public const byte vbKeySubtract = 0x6D;   // MINUS SIGN(-) 键
        public const byte vbKeyDecimal = 0x6E;    // DECIMAL POINT(.) 键
        public const byte vbKeyDivide = 0x6F;     // DIVISION SIGN(/) 键


        //F1到F12按键
        public const byte vbKeyF1 = 0x70;   //F1 键
        public const byte vbKeyF2 = 0x71;   //F2 键
        public const byte vbKeyF3 = 0x72;   //F3 键
        public const byte vbKeyF4 = 0x73;   //F4 键
        public const byte vbKeyF5 = 0x74;   //F5 键
        public const byte vbKeyF6 = 0x75;   //F6 键
        public const byte vbKeyF7 = 0x76;   //F7 键
        public const byte vbKeyF8 = 0x77;   //F8 键
        public const byte vbKeyF9 = 0x78;   //F9 键
        public const byte vbKeyF10 = 0x79;  //F10 键
        public const byte vbKeyF11 = 0x7A;  //F11 键
        public const byte vbKeyF12 = 0x7B;  //F12 键

        #endregion

        public struct Rect
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

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

        [DllImport("user32.dll")]
        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
        [DllImport("user32.dll")]
        private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
        [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 static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("User32.dll")]

        private extern static int GetWindow(int hWnd, int wCmd);
        [DllImport("User32.dll")]

        private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]

        private static extern bool SetCursorPos(int X, int Y);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
        public Form1()
        {
            InitializeComponent();

            this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
            this.Location = new System.Drawing.Point(100,100);
            //获取当前工作宽度和高度(工作区不包含状态栏)
            int ScreenWidth = Screen.PrimaryScreen.WorkingArea.Width;
            int ScreenHeight = Screen.PrimaryScreen.WorkingArea.Height;

            //计算窗体显示的坐标值,可以根据需要微调几个像素
            int x = ScreenWidth - this.Width - 5;
            int y = ScreenHeight - this.Height - 5;
            this.Location = new Point(x,y);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            const int WM_QUIT = 0x12;
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(@"3DMARK_Test");
            if (File.Exists(@"C:\Program Files\AMD GPU Clock Tool\samples.csv"))
                File.Delete(@"C:\Program Files\AMD GPU Clock Tool\samples.csv");//删除日志文件
            if (myProcesses.Length > 1)
            {
                MessageBox.Show("程式已启动", "系统提醒", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(1);
            }
            else
            {
                if (ReadCFG("3DMARK_Test.config") == true)
                {
                    KillProcess("3DMarkICFWorkload");
                    KillProcess(cfg[4]);//判断是否启动进程,启动进程关闭
                    timer2.Enabled = true;
                    if (CallBath("3DMARK.BAT") == true)
                    {
                        if (RedProcess(cfg[4]) == true)
                        {
                            textBox1.Text = cfg[1];
                            TestTime = Convert.ToInt32(cfg[1].Trim());
                            textBox2.Text = "N/A";
                            timer1.Enabled = true;
                        }
                        else
                        {
                            MessageBox.Show("无法找到启动程式3DMark.exe","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
                            System.Environment.Exit(1);
                        }
                    }
                }
            }
        }

        public void BoolMouse(int x, int y)//执行模拟鼠标操作
        {
            SetCursorPos(x,y);
            SendMouseEvent.Click();
        }
        public Boolean SetWindowsXY(String TitleName)
        {
            Boolean Flag = false;
            IntPtr hwnd = FindWindow(null,TitleName);
            if (hwnd != IntPtr.Zero)
            {
                Rect rect = new Rect();
                GetWindowRect(hwnd, out rect);
                int x1 = 0, y1 = 0;
                x1 = Convert.ToInt32(Convert.ToInt32(rect.Right) / 1.322);
                y1 = Convert.ToInt32(Convert.ToInt32(rect.Bottom)/2.862);
                //Windows_X = rect.Left;//获取窗体弹出的X座标
                //Windows_Y = rect.Top;//获取窗体弹出的Y座标
                Windows_X = rect.Left + x1;//获取窗体弹出的X座标+按钮在窗体位置
                Windows_Y = rect.Top + y1;//获取窗体弹出的Y座标+按钮在窗体位置
                Errlog("x=" + Windows_X.ToString() + ",y=" + Windows_Y.ToString() + ",Right=" + rect.Right.ToString() + ",Bottom=" + rect.Bottom.ToString(), "X_Y.LOG");
                Flag = true;
            }
            return Flag;
        }
        //调用执行文件
        public Boolean CallBath(String CallBathName)
        {
            Process proc = null;
            string targetDir = string.Empty;
            targetDir = System.IO.Directory.GetCurrentDirectory() + @"\";
            Boolean Flag = false;
            try
            {
                proc = new Process();
                proc.StartInfo.WorkingDirectory = targetDir;
                proc.StartInfo.FileName = CallBathName;
                proc.Start();
                proc.WaitForExit();
                Flag = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(1);
                Flag = false;
            }
            return Flag;
        }

        //判断进程是否启动
        public Boolean RedProcess(String RunBathName)
        {
            Boolean Flag = false;
            Process[] pro = Process.GetProcesses();//获取已开启的所有进程
            for (int i = 0; i < pro.Length; i++)
            {
                if (pro[i].ProcessName.ToString().ToString() == RunBathName)
                {
                    Flag = true;
                    break;
                }
            }
            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();//结束进程
                }
            }
        }

        //读取配置
        public Boolean ReadCFG(String CfgName)
        {
            Boolean Flag = false;
            try
            {
                FileStream fs = new FileStream(CfgName,FileMode.Open,FileAccess.Read);
                StreamReader sr = new StreamReader(fs,Encoding.Default);
                String Temp = String.Empty;
                while ((Temp = sr.ReadLine()) != null)
                {
                    if (Temp[0] != '#')
                    {
                        String[] ArrayStr = Temp.Split(new String[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                        if (ArrayStr.Length > 1)
                        {
                            cfg.Add(ArrayStr[1].Trim());
                        }
                    }
                }
                sr.Close();
                fs.Close();
                Flag = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(),"系统提醒",MessageBoxButtons.OK,MessageBoxIcon.Error);
                System.Environment.Exit(1);
            }
            return Flag;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (SetWindowsXY(cfg[3]) == true)
            {
                if (File.Exists(cfg[5]) == true)
                {
                    int x = 0, y = 0;
                    //x = Windows_X + Convert.ToInt32(cfg[6]);
                    //y = Windows_Y + Convert.ToInt32(cfg[7]); 
                    x = Windows_X;
                    y = Windows_Y;
                    BoolMouse(x, y);
                    timer1.Enabled = false;
                    timer3.Enabled = true;
                }
                else
                {
                    timer1.Enabled = false;
                    timer2.Enabled = false;
                    timer3.Enabled = false;
                    timer4.Enabled = false;
                    KillProcess(cfg[4]);//关闭执行程式进程
                    KillProcess("3DMarkICFWorkload");
                    MessageBox.Show("Not Executed AMDGPUClockTool.exe Program","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    System.Environment.Exit(1);
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (TestTime <= 0)
            {
                textBox1.Text = "0";
                KillProcess(cfg[4]);//关闭执行程式进程
                KillProcess("3DMarkICFWorkload");
                timer2.Enabled = false;
                System.Environment.Exit(0);
            }
            else
            {
                TestTime--;
                textBox1.Text = TestTime.ToString();
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            if (ReadRecordFcc(cfg[5].Trim()) == false)
            {
                KillProcess(cfg[4]);//关闭执行程式进程
                KillProcess("3DMarkICFWorkload");
                timer2.Enabled = false;
                timer3.Enabled = false;
                System.Environment.Exit(1);
            }
        }

        public static String Sple = "N/A";
        public Boolean ReadRecordFcc(String PathFileName)
        {
            Boolean Flag = false;
            try
            {
                FileStream fs = new FileStream(PathFileName,FileMode.Open,FileAccess.Read);
                StreamReader sr = new StreamReader(fs,Encoding.Default);
                String Temp = String.Empty;
                while ((Temp = sr.ReadLine()) != null)
                {
                    if (Temp[0] != 't')
                    {
                        String[] ArrayStr = Temp.Split(new String[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                        if (ArrayStr.Length > 3)
                        {
                            Sple = ArrayStr[1];
                            if (ArrayStr[1].Trim()[0] != '-')
                            {
                                if (Convert.ToDouble(ArrayStr[1].Trim()) >= Convert.ToDouble(cfg[2].Trim()))
                                {
                                    Flag = false;
                                    return Flag;
                                }
                            }
                        }
                    }
                }
                //textBox2.Text = Sple;//设置读取的值
                Flag = true;
                sr.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                Errlog(ex.ToString(), "Err.log");
                Flag = true;
            }
            return Flag;
        }

        public void Errlog(String Str, String FileName)
        {
            FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            StreamWriter sr = new StreamWriter(fs, Encoding.Default);
            sr.WriteLine(Str);
            sr.Close();
            fs.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            KillProcess(cfg[4]);//判断是否启动进程,启动进程关闭
            KillProcess("3DMarkICFWorkload");
            System.Environment.Exit(1);
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            textBox2.Text = Sple;//设置读取的值
        }
    }
}
 

2._3DMARK_Test CLASS SOURCE CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace _3DMARK_Test
{
    public class SendMouseEvent : Form1
    {
        [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 class FromInfo : Form1
    {
        private String title;
        private int handle;

        public FromInfo(String title, int handle)
        {
            this.title = title;
            this.handle = handle;
        }

        public String Title
        {
            get { return title; }
            set { title = value; }
        }
        public int Handle
        {
            get { return handle; }
            set { handle = value; }
        }
    }
}

 

3.配置文件:

5.启动界面:

猜你喜欢

转载自blog.csdn.net/u013934107/article/details/84110260
今日推荐