C#和C常用的API操作窗口的代码积累
生活随笔
收集整理的這篇文章主要介紹了
C#和C常用的API操作窗口的代码积累
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C#和C常用的API操作窗口的代碼積累
IntPtr awin = MouseHookHelper.FindWindow("WeChatMainWndForPC", "微信"); if (awin == IntPtr.Zero) {MessageBox.Show("沒有找到窗體");return; } 2.獲取窗體坐標(biāo)信息 MouseHookHelper.RECT rect = new MouseHookHelper.RECT(); MouseHookHelper.GetWindowRect(awin, ref rect); int width = rect.Right - rect.Left; //窗口的寬度 int height = rect.Bottom - rect.Top; //窗口的高度 int x = rect.Left; int y = rect.Top; 3.設(shè)置為當(dāng)前窗體 MouseHookHelper.SetForegroundWindow(awin); MouseHookHelper.ShowWindow(awin,MouseHookHelper.SW_SHOWNOACTIVATE);//4、5 4.點(diǎn)擊某個坐標(biāo) LeftMouseClick(new MouseHookHelper.POINT() {X = ppp.MsgX,Y = ppp.MsgY });private static void LeftMouseClick(MouseHookHelper.POINT pointInfo) {//先移動鼠標(biāo)到指定位置MouseHookHelper.SetCursorPos(pointInfo.X, pointInfo.Y);//按下鼠標(biāo)左鍵MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTDOWN,pointInfo.X * 65536 / Screen.PrimaryScreen.Bounds.Width,pointInfo.Y * 65536 / Screen.PrimaryScreen.Bounds.Height, 0, 0);//松開鼠標(biāo)左鍵MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTUP,pointInfo.X * 65536 / Screen.PrimaryScreen.Bounds.Width,pointInfo.Y * 65536 / Screen.PrimaryScreen.Bounds.Height, 0, 0);} 5.復(fù)制粘貼操作 //復(fù)制到剪貼板 Clipboard.SetText("test"); //從剪貼板獲取數(shù)據(jù) Clipboard.GetText(); //粘貼 SendKeys.SendWait("^V"); //回車鍵 SendKeys.Send("{Enter}"); 6.鉤子的使用 private void button1_Click(object sender, EventArgs e) {if (hHook == 0){MyProcedure = new MouseHookHelper.HookProc(this.MouseHookProc);//這里掛節(jié)鉤子hHook = MouseHookHelper.SetWindowsHookEx(WH_MOUSE_LL, MyProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);if (hHook == 0){MessageBox.Show("請以管理員方式打開");return;}button1.Text = "卸載鉤子";}else{bool ret = MouseHookHelper.UnhookWindowsHookEx(hHook);if (ret == false){MessageBox.Show("請以管理員方式打開");return;}hHook = 0;button1.Text = "安裝鉤子";} }private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) {MouseHookHelper.MouseHookStruct MyMouseHookStruct = (MouseHookHelper.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookHelper.MouseHookStruct));if (nCode < 0){return MouseHookHelper.CallNextHookEx(hHook, nCode, wParam, lParam);}else{String strCaption = "x = " + MyMouseHookStruct.pt.X.ToString("d") + " y = " + MyMouseHookStruct.pt.Y.ToString("d");this.Text = strCaption;return MouseHookHelper.CallNextHookEx(hHook, nCode, wParam, lParam);} } 7.MouseHookHelper代碼public class MouseHookHelper{#region 根據(jù)句柄尋找窗體并發(fā)送消息[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]//參數(shù)1:指的是類名。參數(shù)2,指的是窗口的標(biāo)題名。兩者至少要知道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; //最左坐標(biāo)public int Top; //最上坐標(biāo)public int Right; //最右坐標(biāo)public int Bottom; //最下坐標(biāo)}#endregion#region 設(shè)置窗體顯示形式public enum nCmdShow : uint{SW_NONE,//初始值SW_FORCEMINIMIZE,//:在WindowNT5.0中最小化窗口,即使擁有窗口的線程被掛起也會最小化。在從其他線程最小化窗口時(shí)才使用這個參數(shù)。SW_MIOE,//:隱藏窗口并激活其他窗口。SW_MAXIMIZE,//:最大化指定的窗口。SW_MINIMIZE,//:最小化指定的窗口并且激活在Z序中的下一個頂層窗口。SW_RESTORE,//:激活并顯示窗口。如果窗口最小化或最大化,則系統(tǒng)將窗口恢復(fù)到原來的尺寸和位置。在恢復(fù)最小化窗口時(shí),應(yīng)用程序應(yīng)該指定這個標(biāo)志。SW_SHOW,//:在窗口原來的位置以原來的尺寸激活和顯示窗口。SW_SHOWDEFAULT,//:依據(jù)在STARTUPINFO結(jié)構(gòu)中指定的SW_FLAG標(biāo)志設(shè)定顯示狀態(tài),STARTUPINFO 結(jié)構(gòu)是由啟動應(yīng)用程序的程序傳遞給CreateProcess函數(shù)的。SW_SHOWMAXIMIZED,//:激活窗口并將其最大化。SW_SHOWMINIMIZED,//:激活窗口并將其最小化。SW_SHOWMINNOACTIVATE,//:窗口最小化,激活窗口仍然維持激活狀態(tài)。SW_SHOWNA,//:以窗口原來的狀態(tài)顯示窗口。激活窗口仍然維持激活狀態(tài)。SW_SHOWNOACTIVATE,//:以窗口最近一次的大小和狀態(tài)顯示窗口。激活窗口仍然維持激活狀態(tài)。SW_SHOWNOMAL,//:激活并顯示一個窗口。如果窗口被最小化或最大化,系統(tǒng)將其恢復(fù)到原來的尺寸和大小。應(yīng)用程序在第一次顯示窗口的時(shí)候應(yīng)該指定此標(biāo)志。}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 控制鼠標(biāo)移動//移動鼠標(biāo) public const int MOUSEEVENTF_MOVE = 0x0001;//模擬鼠標(biāo)左鍵按下 public const int MOUSEEVENTF_LEFTDOWN = 0x0002;//模擬鼠標(biāo)左鍵抬起 public const int MOUSEEVENTF_LEFTUP = 0x0004;//模擬鼠標(biāo)右鍵按下 public const int MOUSEEVENTF_RIGHTDOWN = 0x0008;//模擬鼠標(biāo)右鍵抬起 public const int MOUSEEVENTF_RIGHTUP = 0x0010;//模擬鼠標(biāo)中鍵按下 public const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;//模擬鼠標(biāo)中鍵抬起 public const int MOUSEEVENTF_MIDDLEUP = 0x0040;//標(biāo)示是否采用絕對坐標(biāo) 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 獲取坐標(biāo)鉤子[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);//調(diào)用下一個鉤子[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);#endregion}第二段代碼
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.Runtime.InteropServices; //StructLayoutnamespace MouseAction {public partial class Form1 : Form{public Form1(){InitializeComponent();}//結(jié)構(gòu)體布局 本機(jī)位置[StructLayout(LayoutKind.Sequential)]struct NativeRECT{public int left;public int top;public int right;public int bottom;}//將枚舉作為位域處理[Flags]enum MouseEventFlag : uint //設(shè)置鼠標(biāo)動作的鍵值{Move = 0x0001, //發(fā)生移動LeftDown = 0x0002, //鼠標(biāo)按下左鍵LeftUp = 0x0004, //鼠標(biāo)松開左鍵RightDown = 0x0008, //鼠標(biāo)按下右鍵RightUp = 0x0010, //鼠標(biāo)松開右鍵MiddleDown = 0x0020, //鼠標(biāo)按下中鍵MiddleUp = 0x0040, //鼠標(biāo)松開中鍵XDown = 0x0080,XUp = 0x0100,Wheel = 0x0800, //鼠標(biāo)輪被移動VirtualDesk = 0x4000, //虛擬桌面Absolute = 0x8000}//設(shè)置鼠標(biāo)位置[DllImport("user32.dll")]static extern bool SetCursorPos(int X, int Y);//設(shè)置鼠標(biāo)按鍵和動作[DllImport("user32.dll")]static extern void mouse_event(MouseEventFlag flags, int dx, int dy,uint data, UIntPtr extraInfo); //UIntPtr指針多句柄類型[DllImport("user32.dll")]static extern IntPtr FindWindow(string strClass, string strWindow);//該函數(shù)獲取一個窗口句柄,該窗口雷鳴和窗口名與給定字符串匹配 hwnParent=Null從桌面窗口查找[DllImport("user32.dll")]static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,string strClass, string strWindow);[DllImport("user32.dll")]static extern bool GetWindowRect(HandleRef hwnd, out NativeRECT rect);//定義變量const int AnimationCount = 80;private Point endPosition;private int count;private void button1_Click(object sender, EventArgs e){NativeRECT rect;//獲取主窗體句柄// IntPtr ptrTaskbar = FindWindow("WindowsForms10.Window.8.app.0.2bf8098_r11_ad1", null);IntPtr ptrTaskbar = FindWindow("WindowsForms10.Window.8.app.0.141b42a_r10_ad1", null);//WindowsForms10.Window.8.app.0.141b42a_r10_ad1if (ptrTaskbar == IntPtr.Zero){MessageBox.Show("No windows found!");return;}//獲取窗體中"button1"按鈕//IntPtr ptrStartBtn = FindWindowEx(ptrTaskbar, IntPtr.Zero, null, "button1");//IntPtr ptrStartBtn = FindWindowEx(ptrTaskbar, IntPtr.Zero, null, "button1");//IntPtr ptrStartBtn = FindWindowEx(ptrTaskbar, IntPtr.Zero, null, "button1");IntPtr ptrStartBtn = FindWindowEx(ptrTaskbar, IntPtr.Zero, null, "開始");if (ptrStartBtn == IntPtr.Zero){MessageBox.Show("No button found!");return;}//獲取窗體大小GetWindowRect(new HandleRef(this, ptrStartBtn), out rect);endPosition.X = (rect.left + rect.right) / 2;endPosition.Y = (rect.top + rect.bottom) / 2;//判斷點(diǎn)擊按鈕if (checkBox1.Checked){MessageBox.Show("dasdas");//選擇"查看鼠標(biāo)運(yùn)行的軌跡"this.count = AnimationCount;movementTimer.Start();}else{SetCursorPos(endPosition.X, endPosition.Y);mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);textBox1.Text = String.Format("{0},{1}", MousePosition.X, MousePosition.Y);}}//Tick:定時(shí)器,每當(dāng)經(jīng)過多少時(shí)間發(fā)生函數(shù)private void movementTimer_Tick(object sender, EventArgs e){int stepx = (endPosition.X - MousePosition.X) / count;int stepy = (endPosition.Y - MousePosition.Y) / count;count--;if (count == 0){movementTimer.Stop();mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);}textBox1.Text = String.Format("{0},{1}", MousePosition.X, MousePosition.Y);mouse_event(MouseEventFlag.Move, stepx, stepy, 0, UIntPtr.Zero);}} }第三段代碼塊
#include <stdio.h> #include <stdlib.h> #include <Windows.h> //ShellExecuteA()//打開某個網(wǎng)址:website (使用默認(rèn)瀏覽器) void open_web(char *website) {ShellExecuteA(0,"open", website,0,0,1); }//模擬鼠標(biāo)點(diǎn)擊 (x,y)是要點(diǎn)擊的位置 void click(int x, int y) {//將鼠標(biāo)光標(biāo)移動到 指定的位置 例子中屏幕分辨率1600x900 在鼠標(biāo)坐標(biāo)系統(tǒng)中,屏幕在水平和垂直方向上均勻分割成65535×65535個單元mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE, x*65535/1600, y*65535/900, 0, 0);Sleep(50);//稍微延時(shí)50ms mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);//鼠標(biāo)左鍵按下 mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);//鼠標(biāo)左鍵抬起}//模擬鍵盤輸入 keybd_event(要按下的字符,0,動作,0);動作為0是按下,動作為2是抬起 void input() {char user[]="1234567890123";//賬號 char pwd[]="1234567890";//密碼 click(823,392); //點(diǎn)擊"用戶名輸入框"的位置 int i;//輸入賬號 for(i=0;i<sizeof(user);i++){keybd_event(user[i],0,0,0);keybd_event(user[i],0,2,0);Sleep(30); }//tab鍵 對應(yīng)的編號是0x09 讓密碼輸入框 獲取焦點(diǎn) keybd_event(0x09,0,0,0);//按下 keybd_event(0x09,0,2,0); //松開 Sleep(30); //輸入密碼 for(i=0;i<sizeof(pwd);i++){keybd_event(pwd[i],0,0,0);keybd_event(pwd[i],0,2,0);Sleep(30);}//模擬按下tab鍵 讓登錄按鈕獲取焦點(diǎn) click(824,530);//點(diǎn)擊"登錄按鈕" Sleep(30); }//將chrome.exe進(jìn)程殺掉,在例子中尚未使用 void close() {system("taskkill /f /im chrome.exe"); }int main(int argc,char *argv[]) {open_web("https://www.baidu.com/");//打開某個網(wǎng)址 Sleep(4000);//延時(shí)4秒,等待網(wǎng)頁打開完畢,再進(jìn)行其它操作。根據(jù)實(shí)際情況(瀏覽器打開速度,網(wǎng)速) click(1454, 126);//點(diǎn)擊"登錄"(1454,126) Sleep(150);click(712,658);//點(diǎn)擊"用戶名登錄"Sleep(150);input();//模擬鼠標(biāo)動作,鍵盤輸入 return 0; }#include <stdio.h> #include <windows.h> //ShellExecute() int main(int argc, char *argv[]) {ShellExecute(0, "open", "C:\\Users\\newuser\\Desktop\\串口助手.exe",0, 0, 1);//最后的參數(shù)是控制最大化、最小化printf("Hello World!\n");return 0; }//例子中屏幕分辨率1600x900 在鼠標(biāo)坐標(biāo)系統(tǒng)中,屏幕在水平和垂直方向上均勻分割成65535×65535個單元 mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE, x*65535/1600, y*65535/900, 0, 0);mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);//鼠標(biāo)左鍵按下 mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);//鼠標(biāo)左鍵抬起keybd_event('9',0,0,0);//按下按鍵 ‘9’ keybd_event('9',0,2,0);//抬起按鍵 ‘9’或 0x39keybd_event(0x39,0,0,0);//按下按鍵 ‘9’ keybd_event(0x39,0,2,0);//抬起按鍵 ‘9’總結(jié)
以上是生活随笔為你收集整理的C#和C常用的API操作窗口的代码积累的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java之文件流操作的文件读写
- 下一篇: C#关于文件夹遍历以及文件拷贝