C# 模擬鼠鍵操作
1.Form1.cs 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.Collections;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;//啟動模擬滑鼠鍵盤操作
namespace Audo_AmdGpuClockTool.V1._00
{
public partial class Form1 : Form
{
public List<String> Cfg = new List<String>();//儲存配置檔案資訊
//獲取類的名字
[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);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
public Form1()
{
InitializeComponent();
}
public struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
private void Form1_Load(object sender, EventArgs e)
{
System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(@"Audo_AmdGpuClockTool.V1.00");
if (myProcesses.Length > 1)
{
MessageBox.Show("程式已啟動");
System.Environment.Exit(1);
}
else
{
if (ReadCfg("GPUCLOCKTOOL.CONFIG") == true)
{
KillProcess(Cfg[2]);//關閉當前程式程序
KillProcess("GPU-Z.2.9.0");//關閉當前程式程序
if (File.Exists(Cfg[1]) == true)
File.Delete(@"C:\Program Files\AMD GPU Clock Tool\samples.csv");//刪除日誌檔案
if (CallBath(Cfg[0]) == true)
{
timer1.Enabled = true;
}
else
{
MessageBox.Show("Run AMDGPUClockTool.exe Program Err!!","系統提醒",MessageBoxButtons.OK,MessageBoxIcon.Error);
System.Environment.Exit(1);
}
}
else
{
MessageBox.Show("Read Config GPUCLOCKTOOL.CONFIG Err!!","系統提醒",MessageBoxButtons.OK,MessageBoxIcon.Error);
System.Environment.Exit(1);
}
}
}
public void BoolMouse(uint x, uint y)//執行模擬滑鼠操作
{
SetCursorPos(Convert.ToInt32(x),Convert.ToInt32(y));
SendMouseEvent.Click();
}
//判斷是否啟動程序
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 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 ReadCfg(String FileName)
{
Boolean Flag = false;
try
{
FileStream fs = new FileStream(FileName,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);
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 Form1_Shown(object sender, EventArgs e)
{
this.Hide();
}
public int index = 0;
public int Windows_X = 0, Windows_Y = 0;
public double []Windows_Multiple_X={6.8883,4.2274,4.4491,3.2541,2.7637,2.0044};
public double []Windows_Multiple_Y={17.06,5.4331,1.5973,1.7232,1.5259,65.615};
int[] FromWindows_X = { 197,321,305,417,491,677};
int[] FromWindows_Y = { 50, 157, 534, 495,559,13};
public void SetWindowsXY(String TitleName)
{
IntPtr hwnd = FindWindow(null, TitleName);
if (hwnd != IntPtr.Zero)
{
Rect rect = new Rect();
GetWindowRect(hwnd, out rect);
Windows_X = rect.Left;//獲取窗體的X座標
Windows_Y = rect.Top;//獲取窗體的Y座標
Errlog("x="+Windows_X.ToString()+",y="+Windows_Y.ToString()+",Right="+rect.Right.ToString()+",Bottom="+rect.Bottom.ToString(),"X_Y.LOG");
for (int i = 0; i < Windows_Multiple_X.Length; i++)
{
FromWindows_X[i] = Convert.ToInt32(Convert.ToInt32(rect.Right)/Windows_Multiple_X[i]);
FromWindows_Y[i] = Convert.ToInt32(Convert.ToInt32(rect.Bottom)/Windows_Multiple_Y[i]);
}
}
}
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 timer1_Tick(object sender, EventArgs e)
{
SetWindowsXY(Cfg[3]);
uint x = 0, y = 0;
x = Convert.ToUInt32(Windows_X + FromWindows_X[index]);
y = Convert.ToUInt32(Windows_Y + FromWindows_Y[index]);
BoolMouse(x, y);
index++;
timer1.Enabled = false;
timer2.Enabled = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
uint x = 0, y = 0;
x = Convert.ToUInt32(Windows_X + FromWindows_X[index]);
y = Convert.ToUInt32(Windows_Y + FromWindows_Y[index]);
BoolMouse(x, y);
index++;
timer2.Enabled = false;
timer3.Enabled = true;
}
private void timer3_Tick(object sender, EventArgs e)
{
if (index < FromWindows_X.Length)
{
uint x = 0, y = 0;
x = Convert.ToUInt32(Windows_X + FromWindows_X[index]);
y = Convert.ToUInt32(Windows_Y + FromWindows_Y[index]);
BoolMouse(x, y);
index++;
}
else
{
timer3.Enabled = false;
System.Environment.Exit(0);
}
}
}
}
2.Keyboard_Mouse.cs 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 Audo_AmdGpuClockTool.V1._00
{
public delegate bool CallBack(int hwnd,int lParam);
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; }
}
}
}