获取当前鼠标所在的窗口句柄
- 格式:docx
- 大小:16.65 KB
- 文档页数:2
vb获取句柄的几种方式获取句柄是在VB中常见的操作之一,句柄可以用于标识和操作窗口、控制界面元素等。
下面将介绍几种常见的获取句柄的方式。
1. 使用FindWindow函数FindWindow函数可以根据窗口类名和窗口标题来查找窗口句柄。
可以使用以下代码获取窗口句柄:```vbDim hwnd As Longhwnd = FindWindow("窗口类名", "窗口标题")```其中,窗口类名是指窗口所属的类的名称,窗口标题是窗口上显示的文本。
2. 使用FindWindowEx函数FindWindowEx函数可以在指定窗口下查找符合条件的子窗口句柄。
可以使用以下代码获取子窗口句柄:```vbDim hwndParent As LongDim hwndChild As LonghwndParent = FindWindow("父窗口类名", "父窗口标题") hwndChild = FindWindowEx(hwndParent, 0, "子窗口类名", "子窗口标题")```其中,hwndParent是父窗口的句柄,hwndChild是子窗口的句柄。
3. 使用GetForegroundWindow函数GetForegroundWindow函数可以获取当前活动窗口的句柄。
可以使用以下代码获取当前活动窗口句柄:```vbDim hwnd As Longhwnd = GetForegroundWindow()```该函数不需要任何参数,直接调用即可。
4. 使用GetDesktopWindow函数GetDesktopWindow函数可以获取桌面窗口的句柄。
可以使用以下代码获取桌面窗口句柄:```vbDim hwnd As Longhwnd = GetDesktopWindow()```该函数不需要任何参数,直接调用即可。
如何获得窗口句柄和改变窗口属性要获得窗口句柄(HWND),可以使用WinAPI中的FindWindow函数或FindWindowEx函数。
1. 使用FindWindow函数:```HWND hWnd = FindWindow(NULL, L"窗口标题");```这个函数会在当前活动的桌面窗口中查找指定标题的窗口,并返回窗口句柄。
2. 使用FindWindowEx函数:```HWND hParent = FindWindow(NULL, L"父窗口标题");HWND hWnd = FindWindowEx(hParent, NULL, NULL, L"子窗口标题");```这个函数会在指定父窗口中查找指定标题的子窗口,并返回子窗口句柄。
要改变窗口属性,可以使用WinAPI中的SetWindowLong函数或SetWindowPos函数。
1. 使用SetWindowLong函数:```LONG_PTR dwStyle = GetWindowLongPtr(hWnd, GWL_STYLE);dwStyle &= ~WS_CAPTION; // 移除标题栏SetWindowLongPtr(hWnd, GWL_STYLE, dwStyle);SetWindowPos(hWnd, NULL, x, y, width, height,SWP_FRAMECHANGED); // 重新绘制窗口```这个函数可以改变窗口的样式,如移除标题栏、调整窗口大小等。
2. 使用SetWindowPos函数:```SetWindowPos(hWnd, NULL, x, y, width, height,SWP_FRAMECHANGED);```这个函数可以重新设置窗口的位置、大小,并且可以实时更新窗口的样式。
需要注意的是,对于不属于当前进程创建的窗口,可能需要通过其他技术手段获取窗口句柄并改变属性,如使用钩子函数或其他进程间通信的方式。
Hwnd = Plugin.Window.Find(0, title)If Hwnd = 0 ThenRunApp ("c:\Program Files\SanGuoShaAIR\三国杀online桌面版\三国杀online桌面版.exe") Hwnd = Plugin.Window.Find(0, title)End IfDelay 4000// 移动到左上角Call Plugin.Window.Move(Hwnd, 0, 0)Plugin.Window.Active(Hwnd)// 等待 进入大厅 按钮的出现Call FindPicIn(432, 438, 589, 487, "Attachment:\enterhall.bmp", 0)/*Do While intX <= 0 And intY <= 0Plugin.Window.Active(Hwnd)Delay 1000FindPic 432, 438, 589, 487, "Attachment:\enterhall.bmp", 0.5, intX, intYLoop*/If intX > 0 And intY > 0 ThenMoveTo intX + 60, intY + 10LeftClick 1Delay 1000End If// 查找 登录游戏 按钮Call FindPicIn(363, 372, 490, 407, "Attachment:\login.bmp", 0)If intX > 0 And intY > 0 ThenMoveTo intX + 50, intY + 10LeftClick 1End If// 查找 脸谱,以确定是否已进入场区选择界面Call FindPicIn(114, 228, 185, 419, "Attachment:\face.bmp", 0)// 进入国战MoveTo 231, 455LeftClick 1Delay 1000MoveTo 444, 491LeftClick 1Delay 3000// 签到窗口// 点击 签到MoveTo 750, 145LeftClick 1/*// 关闭 签到成功 窗口MoveTo 517, 132LeftClick 1// 关闭 签到 窗口MoveTo 873, 101LeftClick 1*/Sub OnScriptExit()Call Plugin.Web.Tips("脚本停止运行") End Sub。
C#写个类操作窗口(句柄操作)实现过程:过程一:找到当前鼠标位置的句柄您的使用2个WinAPI(俺喜欢自己封装下来用):View Code[DllImport("user32.dll", EntryPoint = "GetCursorPos")] public static extern bool GetCursorPos(out Point pt);[DllImport("user32.dll", EntryPoint = "WindowFromPoint")] public static extern IntPtr WindowFromPoint(Point pt);//鼠标位置的坐标public static Point GetCursorPosPoint(){Point p = new Point();if (GetCursorPos(out p)){return p;}return default(Point);}///<summary>///找到句柄///</summary>///<param name="p">坐标</param>///<returns></returns>public static IntPtr GetHandle(Point p){return WindowFromPoint(p);}过程二:改变窗口的Text您的使用1个WinAPI:View Code[DllImport("user32.dll", EntryPoint = "SendMessage")]private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);///<summary>///给窗口发送内容///</summary>///<param name="hWnd">句柄</param>///<param name="lParam">要发送的内容</param>public static void SetText(IntPtr hWnd, string lParam){SendMessage(hWnd, WM_SETTEXT, IntPtr.Zero, lParam);}private const int WM_SETTEXT = 0x000C;通过这个方法就能改变Text的值了。
如何通过句柄获取外部程序的窗口的内容要通过句柄获取外部程序的窗口内容,可以使用Windows API函数来实现。
具体步骤如下:
1. 使用Windows API函数`FindWindow`或`FindWindowEx`来查找目标窗口的句柄。
`FindWindow`可以根据窗口类名或窗口标题查找句柄,`FindWindowEx`可以根据父窗口句柄和窗口类名查找句柄。
如果获取到了目标窗口的句柄,继续下一步;否则,表示未找到目标窗口。
2. 使用Windows API函数`GetWindowTextLength`和
`GetWindowText`来获取目标窗口的文本内容。
`GetWindowTextLength`用于获取文本内容的长度,`GetWindowText`用于获取实际文本内容。
可以先使用`GetWindowTextLength`来获取文本长度,然后创建一个对应长度的缓冲区,再使用`GetWindowText`来获取文本内容。
3. 可以使用其他Windows API函数来获取窗口的其他信息,如
`GetClassName`获取窗口的类名,`GetWindowRect`获取窗口的位置和大小等。
需要注意的是,使用Windows API函数需要导入`user32.dll`库,并且可以使用C++、C#、Python等编程语言进行开发。
使用不同编程语言,具体API函数的调用方式会有所差异。
VC++编程获取窗⼝句柄的⽅法⼩结
本⽂实例讲述了VC++编程获取窗⼝句柄的⽅法。
分享给⼤家供⼤家参考,具体如下:
在VC++编程中常需获取控件或窗体句柄,下⾯总结了⼏种⽅法,还希望⼤家能多多补充。
1、⾃⾝窗⼝句柄可⽤AfxGetMainWnd获取。
2、系统中其他APP的窗⼝句柄可⽤FindWindow获取(⽤SPY帮⼀下忙).
HWND hBtnClose;
HWND hWnd=::FindWindow(NULL,"腾讯QQ系统⼴播");
if(hWnd)
{
hBtnClose=GetDlgItem(hWnd,2);
if(hBtnClose)
PostMessage(hBtnClose,BM_CLICK,NULL,NULL);
}
3、通过指针获取窗⼝句柄
HWND hwnd = pwnd->m_hwnd; //得到它的HWND,对象或指针都可以
4、当我们想得到⼀个窗⼝对象(CWnd的派⽣对象)指针的句柄(HWND)时,最安全的⽅法是使⽤GetSafeHwnd()函数;
5、
HWND GetDlgltem(HWND hDlg,int nlDDlgltem);
6、通过控件ID号获取。
CListCtrl* pleftList = (CListCtrl* )GetDlgItem(IDC_LIST1);
pleftList->GetSafeHandl();
希望本⽂所述对⼤家VC++程序设计有所帮助。
c#获取鼠标处窗口句柄,程序嵌入桌面using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices; namespace WindowsApplication1{public partial class Form1 : Form{public Form1(){InitializeComponent();}const int GW_HWNDFIRST = 0; //{同级别 Z 序最上} const int GW_HWNDLAST = 1; //{同级别 Z 序最下} const int GW_HWNDNEXT = 2; //{同级别 Z 序之下} const int GW_HWNDPREV = 3; //{同级别 Z 序之上} const int GW_OWNER = 4; //{属主窗口}const int GW_CHILD = 5; //{子窗口中的最上} [DllImport("user32.dll", EntryPoint = "FindWindow")] public static extern int FindWindow(string lpClassName,string lpWindowName);[DllImport("user32.dll", EntryPoint = "GetWindow")]//获取窗体句柄,hwnd为源窗口句柄/*wCmd指定结果窗口与源窗口的关系,它们建立在下述常数基础上:GW_CHILD寻找源窗口的第一个子窗口GW_HWNDFIRST为一个源子窗口寻找第一个兄弟(同级)窗口,或寻找第一个顶级窗口GW_HWNDLAST为一个源子窗口寻找最后一个兄弟(同级)窗口,或寻找最后一个顶级窗口GW_HWNDNEXT为源窗口寻找下一个兄弟窗口GW_HWNDPREV为源窗口寻找前一个兄弟窗口GW_OWNER寻找窗口的所有者*/public static extern int GetWindow(int hwnd,int wCmd);[DllImport("user32.dll", EntryPoint = "SetParent")]//设置父窗体public static extern int SetParent(int hWndChild,int hWndNewParent);[DllImport("user32.dll", EntryPoint = "GetCursorPos")]//获取鼠标坐标public static extern int GetCursorPos(ref POINTAPI lpPoint);[StructLayout(LayoutKind.Sequential)]//定义与API相兼容结构体,实际上是一种内存转换public struct POINTAPI{public int X;public int Y;}[DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定坐标处窗体句柄public static extern int WindowFromPoint(int xPoint,int yPoint);private void timer1_Tick(object sender, EventArgs e){POINTAPI point = new POINTAPI();//必须用与之相兼容的结构体,类也可以GetCursorPos(ref point);//获取当前鼠标坐标int hwnd = WindowFromPoint(point.X, point.Y);//获取指定坐标处窗口的句柄bel1.Text =point.X.T oString() + ":" + point.Y.ToString() + "-" + hwnd.T oString();//显示效果,此时窗口已经嵌入桌面了}const int GW_CHILD = 5;//定义窗体关系private void Form1_Load(object sender, EventArgs e){int hDesktop = FindWindow("Progman", null);//获取系统句柄hDesktop = GetWindow(hDesktop, GW_CHILD);//获取其子窗口句柄,就是桌面的句柄SetParent((int)this.Handle, hDesktop);//设置父窗体,第一个为要被设置的窗口,第二个参数为指定其父窗口句柄}}}。
c#获取当前活动窗⼝句柄,获取窗⼝⼤⼩及位置需调⽤API函数需在开头引⼊命名空间using System.Runtime.InteropServices;获取当前窗⼝句柄:GetForegroundWindow()[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]public static extern IntPtr GetForegroundWindow();返回值类型是IntPtr,即为当前获得焦点窗⼝的句柄使⽤⽅法 : IntPtr myPtr=GetForegroundWindow();获取到该窗⼝句柄后,可以对该窗⼝进⾏操作.⽐如,关闭该窗⼝或在该窗⼝隐藏后,使其显⽰[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);其中ShowWindow(IntPtr hwnd, int nCmdShow);nCmdShow的含义0 关闭窗⼝1 正常⼤⼩显⽰窗⼝2 最⼩化窗⼝3 最⼤化窗⼝使⽤实例: ShowWindow(myPtr, 0);获取窗⼝⼤⼩及位置:需要调⽤⽅法GetWindowRect(IntPtr hWnd, ref RECT lpRect)[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]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; //最下坐标}⽰例:InPtr awin = GetForegroundWindow(); //获取当前窗⼝句柄RECT rect = new RECT();GetWindowRect(awin, ref rect);int width = rc.Right - rc.Left; //窗⼝的宽度int height = rc.Bottom - rc.Top; //窗⼝的⾼度int x = rc.Left;int y = rc.Top;------------------------------------------------------------------------C#中的FindWindow[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint="FindWindow")]public static extern int FindWindow (string lpClassName,string lpWindowName);已知窗⼝标题"abc",怎么得到窗⼝句柄?IntPtr hWnd = FindWindow(null, "abc");-------------------------------------------------------C#使⽤FindWindow()函数:[DllImport("coredll.dll", EntryPoint = "FindWindow")]private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);这个函数有两个参数,第⼀个是要找的窗⼝的类,第⼆个是要找的窗⼝的标题。
获得桌面所有窗口句柄的方法总结第一种方法:1.先获得桌面窗口CWnd* pDesktopWnd = CWnd::GetDesktopWindow();2.获得一个子窗口CWnd* pWnd = pDesktopWnd->GetWindow(GW_CHILD);3.循环取得桌面下的所有子窗口while(pWnd != NULL){//获得窗口类名CString strClassName = _T("");//应该用TCHAR,用CStrting没有测试通过.::GetClassName(pWnd->GetSafeHwnd(),strClassName.GetB uffer(256),256);//获得窗口标题CString strWindowText = _T("");::GetWindowT ext(pWnd->GetSafeHwnd(),strWindowT ext.Ge tBuffer(256),256);//继续下一个子窗口pWnd = pWnd->GetWindow(GW_HWNDNEXT);}第二种方法:1.定义存放窗口句柄变量,和下标计数器HWND m_hWndFind[1000]; int m_Index;2.先写一个BOOL CALLBACK EnumWndProc(HWND hwnd,LPARAM lParam) 的回调函数.BOOL CAllwindowsDlg::EnumWindowsProc(HWND hWnd, LPARAM lParam){//查找可见的窗口if(::GetWindowLong(hWnd,GWL_STYLE)& WS_VISIBLE){m_hwndFind[m_Index] = hWnd;//record the HWND handle into arraym_Index++;//count start}return 1;}3.调用(这个回调函数回自动递归的便利所有可见窗口,直到完毕)::EnumWindows(CAllwindowsDlg::EnumWindowsProc,NULL);4.取得窗口名称和类名for(int i = 0;i <=m_Index;i++){HWND m_wnd = m_hwndFind[i];::GetWindowT ext(m_wnd,m_store,128);::GetClassName(m_wnd,m_strClass,MAX_PATH-1);//获得窗口类名CString strClassName = _T("");::GetClassName(m_wnd,strClassName.GetBuffer(256),256);//获得窗口标题CString strWindowText = _T("");::GetWindowT ext(m_wnd,strWindowText.GetBuffer(256),256);}。
VBWindowsAPI获取窗口句柄由于一个特殊问题和一个特殊目的,我打算写一个比较“evil”的程序(不许联想-__-),虽然以前并没有搞过类似的东东,但凭直觉判断(可能相当不准)使用 VB 和 Windows API 搞起来会比较容易。
这个东东的第一步需要获取某个窗口的句柄,在网上找了相关资料,先照家猫画华南虎写了个可以获取鼠标所指的窗口句柄的小程序,现将代码分享如下,这么短注释我就不写了,相信都能看得懂:Private Declare Function SetWindowPos Lib "user32"(ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long)As LongPrivate Declare Function GetCursorPos Lib "user32"(lpPoint As POINTAPI)As LongPrivate Declare Function WindowFromPointXY Lib "user32" Alias "WindowFromPoint"(ByVal xPoint As Long, ByVal yPoint As Long)As LongPrivate Declare Function GetFocus Lib "user32"()As LongPrivate Declare Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)Private Type POINTAPIx As Longy As LongEnd TypePrivate Sub Form_Load()SetWindowPos Me.hwnd, -1, 0, 0, 200, 0, conSwpNoActivate Or conSwpShowWindowEnd SubPrivate Sub Timer1_Timer()Dim xy As POINTAPIGetCursorPos xyahwnd = WindowFromPointXY(xy.x, xy.y) Me.Caption = "Handler : " & ahwnd End Sub。
java selenium 句柄Java Selenium是一个自动化测试工具,它可以模拟用户在浏览器中的操作,并自动进行验证。
其中句柄(Handle)也是一个重要的概念,它是指浏览器窗口的唯一标识。
在使用Java Selenium进行自动化测试时,常常需要使用句柄来切换浏览器窗口。
以下是关于Java Selenium句柄的详细介绍:1.获取当前窗口句柄在Java Selenium中,可以使用以下代码来获取当前窗口的句柄:```javaString handle = driver.getWindowHandle();```此代码将返回一个字符串,该字符串是当前窗口的句柄。
2.获取所有窗口句柄如果需要获取当前浏览器中所有已打开的窗口的句柄,则可以使用以下代码:```javaSet<String> handles = driver.getWindowHandles();```此代码将返回一个Set集合类型,其中包含了所有当前浏览器中已打开窗口的句柄。
3.切换窗口切换窗口在Java Selenium中也是一个重要的操作,例如在测试一个在线商城时,需要从主页跳转到商品详情页,就需要使用句柄来进行窗口切换。
以下代码是如何使用句柄来切换窗口:```javaSet<String> handles = driver.getWindowHandles();for (String handle : handles) {driver.switchTo().window(handle);}```以上代码将循环切换所有窗口句柄,并使用switchTo()方法将当前焦点切换到指定窗口。
4.关闭窗口在测试结束后,需要关闭所有打开的窗口。
在Java Selenium中,以下代码可以关闭当前窗口:```javadriver.close();```使用以上代码之前,我们需要先使用switchTo()方法将焦点切换到需要关闭的窗口。
C# 实现过程:过程一:找到当前鼠标位置的句柄您的使用2个WinAPI(俺喜欢自己封装下来用):View Code[DllImport("", EntryPoint = "GetCursorPos")]public static extern bool GetCursorPos(out Point pt);[DllImport("", EntryPoint = "WindowFromPoint")]public static extern IntPtr WindowFromPoint(Point pt);ndexOf;}public override string ToString(){StringBuilder result = new StringBuilder();for (WinHWND winHandle = this; winHandle != null; winHandle ={("{0}:{1};"if == -1) break;}return ().TrimEnd(';');}private static string GetBaseMark(string sMark){string[] sMarks = (';');return sMarks[ - 1].Split(':')[0];}private static string[] GetChildMarks(string sMark) {string[] sMarks = (';');string[] sChildMarks = new string[ - 1];for (int i = 0; i < ; i ++ ){sChildMarks[i] = sMarks[i ];}return sChildMarks;}.是不是都匹配foreach (IntPtr baseHwnd in baseHwnds){IntPtr handle = baseHwnd;for (int i = - 1; i >= 0; i--){string[] sChildMark = sChildMarks[i].Split(':');try{handle = (handle, UnEscape(sChildMark[0]))[(sChildMark[1])]; }catch{break;}if (i == 0) return new WinHWND(handle);}continue;}return null;}#region转义private static string Escape(string arg){return (":", "\\:").Replace(";","\\;");}private static string UnEscape(string arg){return ("\\:", ":").Replace("\\;", ";");}#endregionpublic static WinHWND GetWinHWND(){return new WinHWND()));}}上全部代码,里面加了窗口的部分属性,扩展其他的属性,自己发挥吧,就是搞WinAPI View Codeusing System;usingusing ;using ;usingusing ;using ;namespace InformationCollectionDataFill{public class WinAPI{#region WinodwsAPI[DllImport("", EntryPoint = "FindWindow")]private static extern IntPtr FindWindow(string IpClassName, string IpWindowName);[DllImport("", EntryPoint = "FindWindowEx")]private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);[DllImport("", EntryPoint = "SendMessage")]private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);[DllImport("", EntryPoint = "GetParent")]public static extern IntPtr GetParent(IntPtr hWnd);[DllImport("", EntryPoint = "GetCursorPos")]public static extern bool GetCursorPos(out Point pt);[DllImport("", EntryPoint = "WindowFromPoint", CharSet = , ExactSpelling = true)] public static extern IntPtr WindowFromPoint(Point pt);[DllImport("", CharSet = ]public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCoun t);[DllImport("", CharSet = ]public static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs] StringBuilder lpString, int nMaxCount);[DllImport("", CharSet = ]public static extern int GetWindowRect(IntPtr hwnd, ref Rectangle rc);[DllImport("", CharSet = ]public static extern int GetClientRect(IntPtr hwnd, ref Rectangle rc);[DllImport("", CharSet = ]public static extern int MoveWindow(IntPtr hwnd, int x, int y, int nWidth, int nHeight, bool bRepaint);[DllImport("", CharSet = , SetLastError = true, ExactSpelling = true)]public static extern int ScreenToClient(IntPtr hWnd, ref Rectangle rect);#endregion#region封装API方法ndexOf;}private Rectangle GetRect(){if == null) return default(Rectangle);Rectangle clientSize = ;Rectangle clientPoint = );return new Rectangle, , , ;}public static WinHWND GetWinHWND(){return new WinHWND()));}public override string ToString(){StringBuilder result = new StringBuilder();for (WinHWND winHandle = this; winHandle != null; winHandle = {("{0}:{1};"if == -1) break;}return ().TrimEnd(';');}private static string GetBaseMark(string sMark){string[] sMarks = (';');return sMarks[ - 1].Split(':')[0];}private static string[] GetChildMarks(string sMark){string[] sMarks = (';');string[] sChildMarks = new string[ - 1];for (int i = 0; i < ; i ++ ){sChildMarks[i] = sMarks[i];}return sChildMarks;}.是不是都匹配foreach (IntPtr baseHwnd in baseHwnds){IntPtr handle = baseHwnd;for (int i = - 1; i >= 0; i--){string[] sChildMark = sChildMarks[i].Split(':');try{handle = (handle, UnEscape(sChildMark[0]))[(sChildMark[1])]; }catch{break;}if (i == 0) return new WinHWND(handle);}continue;}return null;}#region转义private static string Escape(string arg){return (":", "\\:").Replace(";","\\;"); }private static string UnEscape(string arg) {return ("\\:", ":").Replace("\\;", ";"); }#endregion}}效果:Post subject: Dll InjectionThis is my old tutorial on dll injection...people have been asking about this topic a bit recently, so...here it is:Dll Injection Tutorialby DarawkIntroductionThe CreateRemoteThread methodThe SetWindowsHookEx methodThe code cave methodAppendix A - Methods of obtaining a process IDAppendix B - Methods of obtaining a thread IDAppendix C - Complete CreateRemoteThread example source codeAppendix D - Complete SetWindowsHookEx example source codeAppendix E - Complete code cave example source codeIntroductionIn this tutorial i'll try to cover all of the known methods(or at least, those that I know =p) of injecting dll's into a process.Dll injection is incredibly useful for TONS of stuff(game hacking, function hooking, code patching, keygenning, unpacking, etc..). Though there are scattered tutorials on these techniques available throughout the web, I have yet to see any complete tutorials detailing all of them(there may even be more out there than I have here, of course), and comparing their respective strength's and weakness's. This is precisely what i'll attempt to do for you in this paper. You are free to reproduce or copy this paper, so long as propercredit is given and you don't modify it without speaking to me first.The CreateRemoteThread methodI've used this in tons of stuff, and I only recently realized that a lot of people have never seen it, or know how to do it.I can't take credit for thinking it up...I got it from an article on codeproject, but it's a neat trick that I think morepeople should know how to use.The trick is simple, and elegant. The windows API provides us with a function called CreateRemoteThread(). This allows youto start a thread in another process. For our purposes, i'll assume you know how threading works, and how to use functions like CreateThread(if not, you can go here ). The main disadvantage of this method is that it will work only on windows NT and above.To prevent it from crashing, you should use this function to check to make sure you're on an NT-based system(thanks to CatID for pointing this out):bool IsWindowsNT(){Now, normally we would want to start the thread executing on some internal function of the process that we are interacting with. However, to inject a dll, we have to do something a little bit different.BOOL InjectDLL(DWORD ProcessID){HANDLE Proc;char buf[50]={0};LPVOID RemoteString, LoadLibAddy;if(!ProcessID)return false;Proc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, ProcessID);if(!Proc){sprintf(buf, "OpenProcess() failed: %d", GetLastError());MessageBox(NULL, buf, "Loader", NULL);return false;}LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle(""), "LoadLibraryA");RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, strlen(DLL_NAME), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(Proc, (LPVOID)RemoteString, DLL_NAME,strlen(DLL_NAME), NULL);CreateRemoteThread(Proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL); ??CloseHandle(Proc);return true;}HHOOK SetWindowsHookEx( ?int idHook,HOOKPROC lpfn,HINSTANCE hMod,DWORD dwThreadId);LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam){return CallNextHookEx(0, nCode, wParam, lParam);};HMODULE hDll;unsigned long cbtProcAddr;hDll = LoadLibrary("");cbtProcAddr = GetProcAddress(hDll, "CBTProc");BOOL InjectDll(char *dllName){HMODULE hDll;unsigned long cbtProcAddr;hDll = LoadLibrary(dllName);cbtProcAddr = GetProcAddress(hDll, "CBTProc");?SetWindowsHookEx(WH_CBT, cbtProcAddr, hDll, GetTargetThreadIdFromWindow("targetApp")); ?return TRUE;}__declspec(naked) loadDll(void){_asm{We needVirtualProtect(loadDll, stubLen, PAGE_EXECUTE_READWRITE, &oldprot); ?#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)?BOOL WriteProcessBYTES(HANDLE hProcess,LPVOID lpBaseAddress,LPCVOID lpBuffer,SIZE_T nSize);BOOL LoadDll(char *procName, char *dllName);BOOL InjectDLL(DWORD ProcessID, char *dllName);unsigned long GetTargetProcessIdFromProcname(char *procName);bool IsWindowsNT(){// check current version of WindowsDWORD version = GetVersion();// parse returnDWORD majorVersion = (DWORD)(LOBYTE(LOWORD(version)));DWORD minorVersion = (DWORD)(HIBYTE(LOWORD(version)));}int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow){if(IsWindowsNT())LoadDll(PROCESS_NAME, DLL_NAME);elseMessageBox(0, "Your system does not support this method", "Error!", 0);return 0;}BOOL LoadDll(char *procName, char *dllName){DWORD ProcID = 0;ProcID = GetProcID(procName);if(!(InjectDLL(ProcID, dllName)))MessageBox(NULL, "Process located, but injection failed", "Loader", NULL); ?return true;}BOOL InjectDLL(DWORD ProcessID, char *dllName){HANDLE Proc;char buf[50]={0};LPVOID RemoteString, LoadLibAddy;if(!ProcessID)return false;Proc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, ProcessID);if(!Proc){sprintf(buf, "OpenProcess() failed: %d", GetLastError());MessageBox(NULL, buf, "Loader", NULL);return false;}LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle(""), "LoadLibraryA");RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, strlen(DLL_NAME), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);WriteProcessMemory(Proc, (LPVOID)RemoteString, dllName, strlen(dllName), NULL);CreateRemoteThread(Proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL); ??CloseHandle(Proc);return true;}unsigned long GetTargetProcessIdFromProcname(char *procName){PROCESSENTRY32 pe;HANDLE thSnapshot;BOOL retval, ProcFound = false;thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);if(thSnapshot == INVALID_HANDLE_VALUE){MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false;}= sizeof(PROCESSENTRY32);retval = Process32First(thSnapshot, &pe);while(retval){if(StrStrI, procName) ){ProcFound = true;break;}retval = Process32Next(thSnapshot,&pe);= sizeof(PROCESSENTRY32);}return ;}#include <>#include <>#define PROC_NAME ""#define DLL_NAME ""void LoadDll(char *procName, char *dllName);unsigned long GetTargetThreadIdFromProcname(char *procName);int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) {LoadDll(PROC_NAME, DLL_NAME);return 0;}void LoadDll(char *procName, char *dllName){HMODULE hDll;unsigned long cbtProcAddr;hDll = LoadLibrary(dllName);cbtProcAddr = GetProcAddress(hDll, "CBTProc");?SetWindowsHookEx(WH_CBT, cbtProcAddr, hDll, GetTargetThreadIdFromProcName(procName)); ?return TRUE;}unsigned long GetTargetThreadIdFromProcname(char *procName){PROCESSENTRY32 pe;HANDLE thSnapshot, hProcess;BOOL retval, ProcFound = false;unsigned long pTID, threadID;thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);if(thSnapshot == INVALID_HANDLE_VALUE){MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL);return false;}= sizeof(PROCESSENTRY32);retval = Process32First(thSnapshot, &pe);while(retval){if(StrStrI, procName) ){ProcFound = true;break;}retval = Process32Next(thSnapshot,&pe);= sizeof(PROCESSENTRY32);}CloseHandle(thSnapshot);?_asm {mov eax, fs:[0x18]add eax, 36mov [pTID], eax}hProcess = OpenProcess(PROCESS_VM_READ, false, ;ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess);return threadID;}#include <>#include <>#include <>#define PROC_NAME ""#define DLL_NAME ""unsigned long GetTargetProcessIdFromProcname(char *procName); unsigned long GetTargetThreadIdFromProcname(char *procName);__declspec(naked) loadDll(void){_asm{// Placeholder for the return addresspush 0xDEADBEEF// Save the flags and registerspushfdpushad// Placeholder for the string address and LoadLibrarypush 0xDEADBEEFmov eax, 0xDEADBEEF// Call LoadLibrary with the string parametercall eax// Restore the registers and flagspopadpopfd?// Return control to the hijacked threadret}}__declspec(naked) loadDll_end(void){}int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) {void *dllString;void *stub;unsigned long wowID, threadID, stubLen, oldIP, oldprot, loadLibAddy;HANDLE hProcess, hThread;CONTEXT ctx;?stubLen = (unsigned long)loadDll_end - (unsigned long)loadDll;?loadLibAddy = (unsigned long)GetProcAddress(GetModuleHandle(""), "LoadLibraryA");wowID = GetTargetProcessIdFromProcname(PROC_NAME);hProcess = OpenProcess((PROCESS_VM_WRITE | PROCESS_VM_OPERATION), false, wowID);dllString = VirtualAllocEx(hProcess, NULL, (strlen(DLL_NAME) + 1), MEM_COMMIT, PAGE_READWRITE);stub = VirtualAllocEx(hProcess, NULL, stubLen, MEM_COMMIT, PAGE_EXECUTE_READWRITE);?WriteProcessMemory(hProcess, dllString, DLL_NAME, strlen(DLL_NAME), NULL);?threadID = GetTargetThreadIdFromProcname(PROC_NAME);hThread = OpenThread((THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME), false, threadID); SuspendThread(hThread);= CONTEXT_CONTROL;GetThreadContext(hThread, &ctx);oldIP = ;= (DWORD)stub;= CONTEXT_CONTROL;VirtualProtect(loadDll, stubLen, PAGE_EXECUTE_READWRITE, &oldprot);memcpy((void *)((unsigned long)loadDll + 1), &oldIP, 4);memcpy((void *)((unsigned long)loadDll + 8), &dllString, 4);memcpy((void *)((unsigned long)loadDll + 13), &loadLibAddy, 4);WriteProcessMemory(hProcess, stub, loadDll, stubLen, NULL);SetThreadContext(hThread, &ctx);ResumeThread(hThread);Sleep(8000);VirtualFreeEx(hProcess, dllString, strlen(DLL_NAME), MEM_DECOMMIT);VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT);CloseHandle(hProcess);CloseHandle(hThread);return 0;}unsigned long GetTargetProcessIdFromProcname(char *procName){PROCESSENTRY32 pe;HANDLE thSnapshot;BOOL retval, ProcFound = false;thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);if(thSnapshot == INVALID_HANDLE_VALUE){MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false;}= sizeof(PROCESSENTRY32);retval = Process32First(thSnapshot, &pe);while(retval){if(StrStrI, procName) ){ProcFound = true;break;}retval = Process32Next(thSnapshot,&pe);= sizeof(PROCESSENTRY32);}CloseHandle(thSnapshot);return ;}unsigned long GetTargetThreadIdFromProcname(char *procName) {PROCESSENTRY32 pe;HANDLE thSnapshot, hProcess;BOOL retval, ProcFound = false;unsigned long pTID, threadID;thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);if(thSnapshot == INVALID_HANDLE_VALUE){MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", NULL); return false;}= sizeof(PROCESSENTRY32);retval = Process32First(thSnapshot, &pe);while(retval){if(StrStrI, procName) ){ProcFound = true;break;}retval = Process32Next(thSnapshot,&pe);= sizeof(PROCESSENTRY32);}CloseHandle(thSnapshot);?_asm {mov eax, fs:[0x18]add eax, 36mov [pTID], eax}hProcess = OpenProcess(PROCESS_VM_READ, false, ;ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess);return threadID;}。
//得到鼠标指向的窗口句柄Hwnd = Plugin.Window.MousePoint()//得到窗口句柄的客户区大小sRect = Plugin.Window.GetClientRect(Hwnd)Dim MyArrayMyArray=Split(sRect,"|")Ux=MyArray(0)Uy=MyArray(1)MoveTo ux,uy//MessageBox "游戏窗口左上角的坐标:"&Vbcrlf&Ux&","&Uy&Vbcrlf&"句柄是:"&Hwnd '&是字符串连接符, Vbcrlf是换行符//坐标定位Hx=Ux+756 //好友菜单Hy=Uy+277Hx1=Ux+640 //第一位好友Hy1=Uy+170Jlx=Ux+380 //确定获得奖励Jly=Uy+395Scx1=Ux+483 //与他赛车Scy1=Uy+577Scx2=Ux+315 //赛一场Scy2=Uy+503Gtx=Ux+55 //快速过图Gty=Uy+481Cjx=Ux+380 //去抽奖Cjy=Uy+422Cjx1=Ux+272 //抽奖一Cjy1=Uy+467Cjqx=Ux+313 //抽奖确认Cjqy=Uy+348Cjjsx=Ux+377 //抽奖结束Cjjsy=Uy+547'==========传说中的分割线=========='=====打开好友菜单For 8MoveTo hx, hyDelay 500MoveTo hx1, hy1Delay 40LeftClick 1Delay 400'=====单击获得奖励MoveTo JLx, JLyDelay 5000LeftClick 1Delay 400'=====单击与他比赛MoveTo Scx1, Scy1Delay 400LeftClick 1Delay 400'=====单击赛一场,开始比赛MoveTo Scx2, Scy2Delay 400LeftClick 1Delay 400'=====快速跳过比赛MoveTo Gtx, GtyDelay 1000LeftClick 1Delay 400'=====单击开始抽奖MoveTo Cjx, CjyDelay 3000LeftClick 1Delay 400MoveTo Cjx1, Cjy1Delay 200LeftClick 1Delay 400For 2Cjx1= Cjx1+110MoveTo Cjx1, Cjy1Delay 200LeftClick 1Delay 400MoveTo Cjqx, CjqyDelay 200LeftClick 1Delay 400Next'=====比赛结束单击确定For 2MoveTo 711, 740Delay 400LeftClick 1Delay 400NextNext'==========以下是按键精灵录制的内容========== '==========开始执行比赛Delay 7MoveTo 699, 614Delay 100LeftClick 1Delay 400'==========赛一场选择Delay 7MoveTo 319, 533Delay 1000LeftClick 1Delay 400GetColor=GetPixelColor(22,279)While GetColor = 000000MoveTo 740, 319Delay 100LeftClick 1Delay 10GetColor=GetPixelColor(22,279)WendGetColor=GetPixelColor(22,249) While GetColor = 000000MoveTo 741, 390Delay 100LeftClick 1Delay 10GetColor=GetPixelColor(22,249) WendGetColor=GetPixelColor(22,230) While GetColor = 000000MoveTo 742, 461Delay 100LeftClick 1Delay 10GetColor=GetPixelColor(22,230) Wend'==========跳过动画Delay 7MoveTo 64, 511Delay 1000LeftClick 1Delay 400'==========确定输赢Delay 7MoveTo 388, 451Delay 2500LeftClick 1Delay 400。
获取当前鼠标所在的窗口句柄用到的API函数:GetCursorPos基本信息函数功能:该函数检取光标的位置,以屏幕坐标表示。
函数原型:BOOL GetCursorPos(LPPOINT lpPoint);参数:IpPoint:POINT结构指针,该结构接收光标的屏幕坐标。
使用时要先定义一个数据结构:Public Type POINTAPIx As Longy As LongEnd Type例如:dim biao as POINTAPIGetCursorPos biao那么biao.x用来存放当前光标的x轴坐标,biao.y用来存放当前y 轴的坐标。
返回值:如果成功,返回值非零;如果失败,返回值为零。
若想获得更多错误信息,请调用GetLastError函数。
备注:1.光标的位置通常以屏幕坐标的形式给出,它并不受包含该光标的窗口的映射模式的影响。
该调用过程必须具有对窗口站的WINSTA_READATTRIBUTES访问权限。
2.此函数为api函数,调用时要函数声明:Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long速查:Windows NT:3.1及以上版本:Windows:95及以上版本;Windows CE:不支持;头文件:winuser.h;库文件:user32.lib。
WindowFromPoint函数功能:该函数获得包含指定点的窗口的句柄。
函数原型:HWND WindowFromPoint(POINT Point);参数:Point:指定一个被检测的点的POINT结构。
返回值S:返回值为包含该点的窗口的句柄。
如果包含指定点的窗口不存在,返回值为NULL。
如果该点在静态文本控件之上,返回值是在该静态文本控件的下面的窗口的句柄。
备注:WindowFromPoint函数不获取隐藏或禁止的窗口句柄,即使点在该窗口内。
C#写个类操作窗口(句柄操作)实现过程:过程一:找到当前鼠标位置的句柄您的使用2个WinAPI(俺喜欢自己封装下来用):ViewCode[DllImport("user32.dll",EntryPoint="GetCursorPos")]publicstaticexternbool GetCursorPos(out Pointpt);[DllImport("user32.dll",EntryPoint="WindowFromPoint")]publicstaticextern IntPtrWindowFromPoint(Pointpt);//鼠标位置的坐标publicstatic PointGetCursorPosPoint(){Pointp=new Point();if(GetCursorPos(out p)){return p;}returndefault(Point);}///<summary>///找到句柄///</summary>///<paramname="p">坐标</param>///<returns></returns>publicstatic IntPtrGetHandle(Pointp){return WindowFromPoint(p);}过程二:改变窗口的Text您的使用1个WinAPI:ViewCode[DllImport("user32.dll",EntryPoint="SendMessage")]privatestaticexternint SendMessage(IntPtrhWnd,int Msg,IntPtrwParam,string lParam);///<summary>///给窗口发送内容///</summary>///<paramname="hWnd">句柄</param>///<paramname="lParam">要发送的内容</param>publicstaticvoid SetText(IntPtrhWnd,string lParam){SendMessage(hWnd,WM_SETTEXT,IntPtr.Zero,lParam);}privateconstint WM_SETTEXT=0x000C;通过这个方法就能改变Text的值了。
按键精灵教程:控件实现抓抓获取句柄功能来源:按键学院【按键精灵】在按键精灵论坛上看到了一个这样的问题:能不能添加一个类似“抓抓” 抓句柄那样的控件?有了这个控件,咱们可以放在QUI界面上,让用户自己获取窗口句柄,那么,通用同步器这类的脚本实现起来就轻松多了。
(ps:通用同步器是指能够兼容多种游戏窗口键鼠同步功能,也就是说没办法预先知道窗口的类名,标题名去获取窗口句柄,这个时候,抓抓句柄功能就很重要了。
)其实呢,“抓抓”抓句柄的功能,实现起来是很容易的,我们一起来操作看看。
实现功能点击图片控件之后鼠标不松开,到了需要获取句柄的窗口松开鼠标,获取窗口句柄显示在标签控件里。
(点击图片控件之后,按住鼠标左键光标形状改变,松开鼠标之后,光标恢复系统默认形状。
)思路&步骤1、画一个计时器。
时间间隔设置为200毫秒,有效设置为否(即:Timer1.Enabled = false)2、在图像控件点击事件中:(图像控件中设置显示图像为:光标2.jpg )①调用api修改光标形状为:②将图像控件显示的图像改为:光标1.jpg ,点击之后就变为空的,就像是里面的光标跑走了一样。
③Timer1控件的Enabled属性设置为True ,启动计时器。
3、在计时器Timer事件中,使用api函数GetAsyncKeyState 检测上次按过的鼠标键,如果鼠标松开则:①使用 MousePoint 鼠标指向窗口命令获取当前鼠标指向的窗口句柄。
②将获取到的窗口句柄显示在标签中。
③将光标形状还原成系统默认形状④将图像控件显示的图像改为:光标2.jpg最后将计时器Enabled属性设置为false,不可用。
修改光标要使用的api函数数函数功能 该函数使一个应用程序定制系统光标。
函数声明 Public Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" (ByVal uAction As Long, ByVal uParamLong, lpvParam As Any, ByVal fuWinIni As Long)函数语法SystemParametersinfo (uiAction , uiParam ,pvParam , fWinlni )参数说明 uiAction : 该参数指定要查询或设置的系统级。
用到的API函数:
GetCursorPos
基本信息
函数功能:该函数检取光标的位置,以屏幕坐标表示。
函数原型:BOOL GetCursorPos(LPPOINT lpPoint);
参数:
IpPoint:POINT结构指针,该结构接收光标的屏幕坐标。
使用时要先定义一个数据结构:
Public Type POINTAPI
x As Long
y As Long
End Type
例如:
dim biao as POINTAPI
GetCursorPos biao
那么biao.x用来存放当前光标的x轴坐标,biao.y用来存放当前y轴的坐标。
返回值:如果成功,返回值非零;如果失败,返回值为零。
若想获得更多错误信息,请调用GetLastError函数。
备注:
1.光标的位置通常以屏幕坐标的形式给出,它并不受包含该光标的窗口的映射模式的影响。
该调用过程必须具有对窗口站的WINSTA_READATTRIBUTES访问权限。
2.此函数为api函数,调用时要函数声明:Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
速查:Windows NT:3.1及以上版本:Windows:95及以上版本;Windows CE:不支持;头文件:winuser.h;库文件:user32.lib。
WindowFromPoint
函数功能:该函数获得包含指定点的窗口的句柄。
函数原型:HWND WindowFromPoint(POINT Point);
参数:
Point:指定一个被检测的点的POINT结构。
返回值S:返回值为包含该点的窗口的句柄。
如果包含指定点的窗口不存在,返回值为NULL。
如果该点在静态文本控件之上,返回值是在该静态文本控件的下面的窗口的句柄。
备注:WindowFromPoint函数不获取隐藏或禁止的窗口句柄,即使点在该窗口内。
应用程序应该使用ChildWindowFromPoint函数进行无限制查询,这样就可以获得静态文本控件的句柄。
速查:Windows NT:3.1以上版本:Windows:95以上版本;Windows CE:1.0以上版本:头文件:Winuser.h;库文件:user32.lib。
获取当前鼠标所在的窗口句柄代码:
POINT pNow = {0,0};
If (GetCursorPos(&pNow))
{
HWND hwndPointNow = NULL;
hwndPointNow = WindowFromPoint(pNow);
if (hwndPointNow)
cout <<“Success!!”<< endl;
else
cout <<“Error!!”<< endl;
}
else
cout <<“Error!!”<< endl;。