C#和C常用的API操作窗口的代码积累
生活随笔
收集整理的這篇文章主要介紹了
C#和C常用的API操作窗口的代码积累
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#和C常用的API操作窗口的代碼積累
IntPtr awin = MouseHookHelper.FindWindow("WeChatMainWndForPC", "微信"); if (awin == IntPtr.Zero) {MessageBox.Show("沒有找到窗體");return; } 2.獲取窗體坐標信息 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.設置為當前窗體 MouseHookHelper.SetForegroundWindow(awin); MouseHookHelper.ShowWindow(awin,MouseHookHelper.SW_SHOWNOACTIVATE);//4、5 4.點擊某個坐標 LeftMouseClick(new MouseHookHelper.POINT() {X = ppp.MsgX,Y = ppp.MsgY });private static void LeftMouseClick(MouseHookHelper.POINT pointInfo) {//先移動鼠標到指定位置MouseHookHelper.SetCursorPos(pointInfo.X, pointInfo.Y);//按下鼠標左鍵MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTDOWN,pointInfo.X * 65536 / Screen.PrimaryScreen.Bounds.Width,pointInfo.Y * 65536 / Screen.PrimaryScreen.Bounds.Height, 0, 0);//松開鼠標左鍵MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTUP,pointInfo.X * 65536 / Screen.PrimaryScreen.Bounds.Width,pointInfo.Y * 65536 / Screen.PrimaryScreen.Bounds.Height, 0, 0);} 5.復制粘貼操作 //復制到剪貼板 Clipboard.SetText("test"); //從剪貼板獲取數據 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);//這里掛節鉤子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 根據句柄尋找窗體并發送消息[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);#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();}//結構體布局 本機位置[StructLayout(LayoutKind.Sequential)]struct NativeRECT{public int left;public int top;public int right;public int bottom;}//將枚舉作為位域處理[Flags]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")]static extern bool SetCursorPos(int X, int Y);//設置鼠標按鍵和動作[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);//該函數獲取一個窗口句柄,該窗口雷鳴和窗口名與給定字符串匹配 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;//判斷點擊按鈕if (checkBox1.Checked){MessageBox.Show("dasdas");//選擇"查看鼠標運行的軌跡"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:定時器,每當經過多少時間發生函數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()//打開某個網址:website (使用默認瀏覽器) void open_web(char *website) {ShellExecuteA(0,"open", website,0,0,1); }//模擬鼠標點擊 (x,y)是要點擊的位置 void click(int x, int y) {//將鼠標光標移動到 指定的位置 例子中屏幕分辨率1600x900 在鼠標坐標系統中,屏幕在水平和垂直方向上均勻分割成65535×65535個單元mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE, x*65535/1600, y*65535/900, 0, 0);Sleep(50);//稍微延時50ms mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);//鼠標左鍵按下 mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);//鼠標左鍵抬起}//模擬鍵盤輸入 keybd_event(要按下的字符,0,動作,0);動作為0是按下,動作為2是抬起 void input() {char user[]="1234567890123";//賬號 char pwd[]="1234567890";//密碼 click(823,392); //點擊"用戶名輸入框"的位置 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鍵 對應的編號是0x09 讓密碼輸入框 獲取焦點 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鍵 讓登錄按鈕獲取焦點 click(824,530);//點擊"登錄按鈕" Sleep(30); }//將chrome.exe進程殺掉,在例子中尚未使用 void close() {system("taskkill /f /im chrome.exe"); }int main(int argc,char *argv[]) {open_web("https://www.baidu.com/");//打開某個網址 Sleep(4000);//延時4秒,等待網頁打開完畢,再進行其它操作。根據實際情況(瀏覽器打開速度,網速) click(1454, 126);//點擊"登錄"(1454,126) Sleep(150);click(712,658);//點擊"用戶名登錄"Sleep(150);input();//模擬鼠標動作,鍵盤輸入 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);//最后的參數是控制最大化、最小化printf("Hello World!\n");return 0; }//例子中屏幕分辨率1600x900 在鼠標坐標系統中,屏幕在水平和垂直方向上均勻分割成65535×65535個單元 mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE, x*65535/1600, y*65535/900, 0, 0);mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);//鼠標左鍵按下 mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);//鼠標左鍵抬起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’總結
以上是生活随笔為你收集整理的C#和C常用的API操作窗口的代码积累的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java之文件流操作的文件读写
- 下一篇: C++模拟键盘操作窗口入门