C利用句柄操作窗口

合集下载

C#查找指定窗口的子窗口的句柄

C#查找指定窗口的子窗口的句柄

C#查找指定窗口的子窗口的句柄用axWebBrowser加载HTML网页时,真正显示内容的窗体并不是axWebBrowser,而是其子窗口的子窗口一个名为Internet Explorer_Server的类。

从spy++可知:公司需要在网页上进行手写,需要对Internet Explorer_Server进行操作,而通过axWebBrowser的Handle不能直接操作Internet Explorer_Server。

于是在网上搜到Paul DiLascia写的一个CFindWnd类,是用C++写的,由于我用C#进行了改写。

这个类主要用的的API 是EnumChildWindows和FindWindowEx,第一个遍历指定窗口下的子窗口,第二个查找指定名称的窗口,如果找到返回此窗口Handle。

该类的用法:FindWindow fw = new FindWindow(wndHandle, "ChildwndClassName"); //实例化,第一个参数是要查找的起始窗口的句柄;第二个参数是要查找的窗口的类的名称。

现在我们需要的传的是"Internet Explorer_Server"。

IntPtr ip = fw.FoundHandle;//FindWindow的公共属性FoundHandle就是查找到的窗口的句柄。

完整的类如下:using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;namespace SystemManager.Utility{///<summary>/// This class is to find the given window's child window accroding to the given child w indow's name./// The useage: FindWindow fw = new FindWindow(wndHandle, "ChildwndClassNam e"); IntPtr ip = fw.FoundHandle;/// I adapt the code from Paul DiLascia,who is the MSDN Magazine's writer./// The original class is named CFindWnd which is written in C++, and you could get i t on Internet./// is a great website.It includes almost all the API fuctoin to be use d in C#.///</summary>class FindWindow{[DllImport("user32")][return: MarshalAs(UnmanagedType.Bool)]//IMPORTANT : LPARAM must be a pointer (InterPtr) in VS2005, otherwise an ex ception will be thrownprivate static extern bool EnumChildWindows(IntPtr window, EnumWindowProc ca llback, IntPtr i);//the callback function for the EnumChildWindowsprivate delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);//if found return the handle , otherwise return IntPtr.Zero[DllImport("user32.dll", EntryPoint = "FindWindowEx")]private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfte r, string lpszClass, string lpszWindow);private string m_classname; // class name to look forprivate IntPtr m_hWnd; // HWND if foundpublic IntPtr FoundHandle{get { return m_hWnd; }}// ctor does the work--just instantiate and gopublic FindWindow(IntPtr hwndParent, string classname){m_hWnd = IntPtr.Zero;m_classname = classname;FindChildClassHwnd(hwndParent, IntPtr.Zero);}///<summary>/// Find the child window, if found m_classname will be assigned///</summary>///<param name="hwndParent">parent's handle</param>///<param name="lParam">the application value, nonuse</param>///<returns>found or not found</returns>//The C++ code is that lParam is the instance of FindWindow class , if found assig n the instance's m_hWndprivate bool FindChildClassHwnd(IntPtr hwndParent, IntPtr lParam){EnumWindowProc childProc = new EnumWindowProc(FindChildClassHwnd);IntPtr hwnd = FindWindowEx(hwndParent, IntPtr.Zero, this.m_classname, string .Empty);if (hwnd != IntPtr.Zero){this.m_hWnd = hwnd; // found: save itreturn false; // stop enumerating}EnumChildWindows(hwndParent, childProc, IntPtr.Zero); // recurse redo FindC hildClassHwndreturn true;// keep looking}}}注意:在VS2005中,MDA检查的很严格,LPARAM是64位,要用IntPtr表示(网上有人用long来表示,我试了,MDA会抛出异常)。

VCMFC编程各种窗口句柄获取函数详解

VCMFC编程各种窗口句柄获取函数详解

AfxGetMainWndAfxGetMainWnd获取自身窗口句柄HWND hWnd = AfxGetMainWnd()->m_hWnd;GetTopWindow函数功能:该函数检查与特定父窗口相联的子窗口z序(Z序:垂直屏幕的方向,即叠放次序),并返回在z序顶部的子窗口的句柄。

函数原型:HWND GetTopWindow(HWND hWnd);参数:hWnd:被查序的父窗口的句柄。

如果该参数为NULL,函数返回Z序顶部的窗口句柄。

返回值:如果函数成功,返回值为在Z序顶部的子窗口句柄。

如果指定的窗口无子窗口,返回值为NULL。

GetForegroundWindow函数功能:该函数返回当前系统的前台窗口的窗口句柄。

函数原型:HWND GetForegroundWindow(VOID)返回值:函数返回前台窗回的句柄。

GetActiveWindow函数功能:该函数可以获得与调用该方法的线程的消息队列相关的活动窗口的窗口句柄(就是取得当前进程的活动窗口的窗口句柄)。

函数原型:HWND GetActiveWindow(VOID)返回值:返回值是与调用线程的消息队列相关的活动窗口的句柄。

否则,返回值为NULL。

GetSafeHwnd函数功能:获取某个窗口对象(CWnd的派生对象)指针的句柄(HWND)时,最安全的方法是使用GetSafeHwnd()函数。

通过下面的例子来看其理由:CWnd *pwnd = FindWindow(“ExploreWClass”,NULL); //希望找到资源管理器HWND hwnd = pwnd->m_hwnd; //得到它的HWND这样的代码当开始得到的pwnd为空的时候就会出现一个“General protection error”,并关闭应用程序,因为一般不能对一个NULL指针访问其成员,如果用下面的代码:CWnd *pwnd = FindWindow(“ExploreWClass”,NULL); //希望找到资源管理器HWND hwnd = pwnd->GetSafeHwnd(); //得到它的HWND就不会出现问题,因为尽管当pwnd是NULL时,GetSafeHwnd仍然可以用,只是返回NULLIsWindowVisible函数功能:该函数获得给定窗口的可视状态。

c 语言setconsolecursorposition的用法 -回复

c 语言setconsolecursorposition的用法 -回复

c 语言setconsolecursorposition的用法-回复C语言中,`SetConsoleCursorPosition` 是一个用来设置控制台窗口光标位置的函数。

它通常用于Windows平台上开发命令行程序,可以让开发者灵活控制光标在控制台窗口中的移动位置。

在本文中,我们将详细介绍`SetConsoleCursorPosition`函数的用法,以及如何使用它来进行控制台窗口光标位置的设置。

一、`SetConsoleCursorPosition` 函数的说明在使用`SetConsoleCursorPosition`函数之前,我们首先需要了解它的一些基本信息。

`SetConsoleCursorPosition`函数位于`windows.h`头文件中,并且需要通过`HANDLE` 参数来指定要设置光标位置的控制台。

此外,它还需要一个`COORD`类型的参数,来指定光标在控制台窗口中的X 和Y 坐标。

以下是`SetConsoleCursorPosition`函数的原型:cBOOL SetConsoleCursorPosition(HANDLE hConsoleOutput, COORD dwCursorPosition);其中,`hConsoleOutput`参数为要设置光标位置的控制台的句柄,而`dwCursorPosition`参数是一个COORD结构体,用来指定光标在控制台窗口中的坐标。

二、`SetConsoleCursorPosition` 函数的用法下面我们将详细介绍如何使用`SetConsoleCursorPosition`函数来设置控制台窗口的光标位置。

1. 引入所需的头文件在使用`SetConsoleCursorPosition`函数之前,我们需要先引入相应的头文件,以便能够使用它。

在C语言中,我们需要引入`windows.h`头文件,即:c#include <windows.h>2. 获取输出控制台的句柄在使用`SetConsoleCursorPosition`函数之前,我们需要先获取要设置光标位置的控制台的句柄。

c语言创建窗口代码 -回复

c语言创建窗口代码 -回复

c语言创建窗口代码-回复如何使用C语言创建一个窗口C语言是一种通用的编程语言,可以用来开发各种类型的应用程序,包括图形用户界面(GUI)应用程序。

创建一个窗口是GUI应用程序中的基本操作之一,本文将介绍如何使用C语言创建一个窗口。

在使用C语言创建窗口之前,我们首先需要一个可供编程的集成开发环境(IDE),例如Code::Blocks或Visual Studio。

这些IDE提供了编写、编译和调试C语言程序的工具,并且支持创建窗口应用程序的相关库。

步骤1:导入窗口相关的库在C语言中,我们需要使用一些库来实现窗口的创建和管理。

常用的窗口库有WinAPI和GTK等。

在这篇文章中,我们将使用WinAPI来创建窗口。

首先,我们需要在代码中导入Windows头文件,以便使用WinAPI提供的函数和常量。

可以通过以下代码行实现:c#include <windows.h>步骤2:定义窗口过程在WinAPI中,窗口是由窗口过程函数控制的。

窗口过程函数是一个特殊的函数,它接收和处理与窗口相关的消息(例如鼠标点击、键盘输入等)。

我们可以通过以下代码定义一个简单的窗口过程函数:cLRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){switch (uMsg){case WM_CLOSE:DestroyWindow(hwnd);break;case WM_DESTROY:PostQuitMessage(0);break;default:return DefWindowProc(hwnd, uMsg, wParam, lParam);}return 0;}在这个窗口过程函数中,我们根据收到的消息类型采取不同的行动。

当我们接收到WM_CLOSE消息时,我们调用DestroyWindow函数来销毁窗口。

当我们接收到WM_DESTROY消息时,我们调用PostQuitMessage 函数来终止应用程序。

c语言句柄示例

c语言句柄示例

c语言句柄示例C语言句柄示例在C语言中,句柄(Handle)是一种特殊的数据类型,用于表示资源的引用或标识符。

它可以是指向某个对象的指针、文件描述符、窗口句柄等。

句柄的使用可以提高程序的效率和灵活性,下面是一些常见的C语言句柄示例:1. 文件句柄(File Handle):在C语言中,使用文件句柄来操作文件,比如打开、读取和关闭文件。

文件句柄通常是一个整数值,通过调用文件操作函数来获取和使用。

例如,使用fopen函数打开文件,返回的文件句柄可以用于后续的文件读写操作。

2. 内存句柄(Memory Handle):在C语言中,使用内存句柄来管理动态分配的内存。

内存句柄通常是一个指向内存块的指针,可以通过malloc或calloc函数分配内存,并使用free函数释放内存。

内存句柄的使用可以避免内存泄漏和提高内存的利用率。

3. 窗口句柄(Window Handle):在图形用户界面(GUI)编程中,窗口句柄是用来表示窗口的标识符。

它通常是一个整数值或指针,可以用于操作窗口,比如创建、显示和关闭窗口。

在Windows操作系统中,使用HWND类型表示窗口句柄。

4. 设备句柄(Device Handle):在设备驱动程序中,设备句柄用于表示设备的标识符。

它可以是一个整数值或指针,用于与设备进行通信,比如打开、读取和写入设备。

设备句柄的使用可以实现对硬件设备的控制和操作。

5. 线程句柄(Thread Handle):在多线程编程中,线程句柄用于表示线程的标识符。

它可以是一个整数值或指针,用于创建、启动和等待线程的结束。

线程句柄的使用可以实现多线程并发执行,提高程序的性能和响应能力。

6. 互斥量句柄(Mutex Handle):在多线程编程中,互斥量句柄用于实现线程间的互斥访问。

它可以是一个整数值或指针,用于创建、加锁和解锁互斥量。

互斥量句柄的使用可以避免多个线程同时访问共享资源,保证数据的一致性和正确性。

7. 信号量句柄(Semaphore Handle):在多线程编程中,信号量句柄用于实现线程间的同步和通信。

c语言mfc的两个界面间的通信

c语言mfc的两个界面间的通信

c语言mfc的两个界面间的通信在 C 语言 MFC 中实现两个界面间的通信,通常可以使用消息映射机制或窗口句柄来进行通信。

下面是一个简单的示例,演示了如何在 MFC 中实现两个界面间的通信:```cpp// 主窗口消息#define WM_MAIN_MSG WM_USER+0x01001// 子窗口消息#define WM_SUB_MSG WM_USER+0x02001// 主窗口消息处理函数afx_msg LRESULT CMultiWindowsDlg::OnMainMsg(WPARAM wParam, LPARAM lParam) {CString* strMsg = (CString*)wParam;SetDlgItemText(IDC_EDIT1, *strMsg);return 0;}// 子窗口向父窗口发送消息的处理函数afx_msg LRESULT CMySubDialog::OnSubMsg(WPARAM wParam, LPARAM lParam){CString* strMsg = (CString*)wParam;SetDlgItemText(IDC_EDIT1, *strMsg);return 0;}// 打开子窗口void CMultiWindowsDlg::OnBnClickedButton1(){if (dlg == NULL){dlg = new CMySubDialog();dlg->Create(IDD_DIALOG1, this);if (dlg == NULL)return (void)MessageBox(_T("子窗口的句柄为空!"));dlg->ShowWindow(SW_SHOWNORMAL);}}// 向子窗口发送消息void CMultiWindowsDlg::OnBnClickedButton2(){CString strEdit;GetDlgItemText(IDC_EDIT1, strEdit);if (dlg == NULL)return (void)MessageBox(_T("子窗口的句柄为空!"));dlg->SendMessage(WM_SUB_MSG, (WPARAM)&strEdit);}// 向父窗口发送消息void CMySubDialog::OnBnClickedButton1(){CString strEdit;GetDlgItemText(IDC_EDIT1, strEdit);HWND hWnd = this->GetParent()->GetSafeHwnd();if (hWnd == NULL)return (void)MessageBox(_T("获得父窗口句柄失败!"));::SendNotifyMessage(hWnd, WM_MAIN_MSG, (WPARAM)&strEdit, NULL);}```上述代码中,通过在主窗口中声明一个消息`WM_MAIN_MSG`,并在子窗口中声明一个消息`WM_SUB_MSG`,实现了两个窗口之间的通信。

C_窗体中Invoke和BeginInvoke方法详解

C_窗体中Invoke和BeginInvoke方法详解

在Invoke或者BeginInvoke的使用中无一例外地使用了委托Delegate,至于委托的本质请参考我的另一随笔:对.net事件的看法。

一、为什么Control类提供了Invoke和BeginInvoke机制?关于这个问题的最主要的原因已经是dotnet程序员众所周知的,我在此费点笔墨再次记录到自己的日志,以便日后提醒一下自己。

1、windows程序消息机制Windows GUI程序是基于消息机制的,有个主线程维护着一个消息泵。

这个消息泵让windows 程序生生不息。

Windows GUI程序的消息循环Windows程序有个消息队列,窗体上的所有消息是这个队列里面消息的最主要来源。

这里的while 循环使用了GetMessage()这个方法,这是个阻塞方法,也就是队列为空时方法就会被阻塞,从而这个while循环停止运动,这避免了一个程序把cpu无缘无故地耗尽,让其它程序难以得到响应。

当然在某些需要cpu最大限度运动的程序里面就可以使用另外的方法,例如某些3d游戏或者及时战略游戏中,一般会使用PeekMessage()这个方法,它不会被windows阻塞,从而保证整个游戏的流畅和比较高的帧速。

这个主线程维护着整个窗体以及上面的子控件。

当它得到一个消息,就会调用DispatchMessage 方法派遣消息,这会引起对窗体上的窗口过程的调用。

窗口过程里面当然是程序员提供的窗体数据更新代码和其它代码。

2、dotnet里面的消息循环public static void Main(string[] args){Form f = new Form();Application.Run(f);}Dotnet窗体程序封装了上述的while循环,这个循环就是通过Application.Run方法启动的。

3、线程外操作GUI控件的问题如果从另外一个线程操作windows窗体上的控件,就会和主线程产生竞争,造成不可预料的结果,甚至死锁。

C利用句柄操作窗口

C利用句柄操作窗口

C利用句柄操作窗口
在C语言中,可以使用句柄(handle)来操作窗口。

句柄是一个唯一标识符,用来表示窗口或其他资源的引用。

以下是一些常见的句柄操作窗口的函数:
1. GetActiveWindow(:获取当前活动窗口的句柄。

2. FindWindow(lpClassName, lpWindowName):根据类名和窗口名称查找窗口,并返回窗口句柄。

3. SendMessage(hWnd, Msg, wParam, lParam):向指定窗口发送消息。

4. MoveWindow(hWnd, x, y, width, height, repaint):移动指定窗口的位置和大小。

5. ShowWindow(hWnd, nCmdShow):显示或隐藏指定窗口。

以下是一个示例代码,演示如何使用句柄操作窗口:
```c
#include <windows.h>
int mai
HWND hwnd = FindWindow(NULL, "窗口标题"); // 查找窗口句柄
if (hwnd == NULL)
printf("未找到窗口\n");
return 1;
}
//移动窗口的位置和大小
MoveWindow(hwnd, 100, 100, 500, 300, TRUE);
//发送消息给窗口
SendMessage(hwnd, WM_CLOSE, 0, 0);
return 0;
```
注意,上述示例代码是在Windows平台下使用的。

如果你是在其他操作系统下使用C语言,可能需要使用对应的窗口操作函数。

C#操作窗口类(句柄操作)

C#操作窗口类(句柄操作)

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改变窗口大小和样式

改变窗口的外观和大小改变窗口的外观和大小需要在窗口创建以前改变。

所以我们可以在CMainFrame的PreCreateWindow中改变CREATESTRUCT 结构体的值就行了。

E.G.BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)改变窗口的大小-> cs.cx = 300; cs.cy = 200;改变窗口的显示位置坐标是 cs.x 和 cs.y这里常用的一个函数是::GetSysMetrics(SM_CXSCREEN);::GetSysMetrics(SM_CYSCREEN);用来取得屏幕的大小。

要改变窗口标题栏的字符串:cs.lpszName = "Seven"; 会发现标题栏不会改变窗口的标题栏的上的字符串。

改变单文档应用程序的标题栏的字符串参考MSDN windowstyles/Frame-window styles 下面有一个Changing the styles of a window create by MFC./ The SDI Case默认的情况是WS_OVERLAPPEDWINDOW and FWS_ADDTOTITLE styles FWS_ADDTOTITLE is add the document title to the window’s caption.去掉FWS_ADDTOTITLE 就可以更改窗口标题栏字符串。

cs.style &= ~FWS_ADDTOTITLE;cs.lpszName = "Seven";如果我们需要改变背景,画刷,光标等等时候。

我们可以在:PreCreateWindow中创建窗口类,WNDCLASS wndClass;把这个类里的值改变成自己想要的内容就可以了。

E.G.wndClass.cbClsExtra = 0;wndClass.cbWndExtra = 0;wndClass.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);wndClass.hCursor = LoadCursor(NULL, IDC_WAIT);wndClass.hIcon = LoadIcon(NULL, IDI_WARNING);wndClass.hInstance = AfxGetInstanceHandle();获取应用程序的实例句柄可用AfxGetInstanceHandle函数,这个函数是一个全局的函数,前面有一个AFX表示是一个应用程序框架类函数,哪里都可用。

c利用句柄操作窗口

c利用句柄操作窗口

c利用句柄操作窗口 Document number【980KGB-6898YT-769T8CB-246UT-18GG08】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 IpW indowName);[DllImport("", EntryPoint = "FindWindowEx")]private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hw ndChildAfter, string lpszClass, string lpszWindow);[DllImport("", EntryPoint = "SendMessage")]private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wPa ram, 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 = , ExactSpelli ng = true)]public static extern IntPtr WindowFromPoint(Point pt);[DllImport("", CharSet = ]public static extern int GetClassName(IntPtr hWnd, StringBuilder lpCla ssName, int nMaxCount);[DllImport("", CharSet = ]public static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs] S tringBuilder 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 nWi dth, int nHeight, bool bRepaint);[DllImport("", CharSet = , SetLastError = true, ExactSpelling = true)] public static extern int ScreenToClient(IntPtr hWnd, ref Rectangle rec t);#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 detailingall 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 likeCreateThread(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 forpointing 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 LoadLibrary push 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);= 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);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;}。

C#获取进程的主窗口句柄的实现方法

C#获取进程的主窗口句柄的实现方法

C#获取进程的主窗⼝句柄的实现⽅法通过调⽤Win32 API实现。

复制代码代码如下:public class User32API{private static Hashtable processWnd = null;public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);static User32API(){if (processWnd == null){processWnd = new Hashtable();}}[DllImport("user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);[DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]public static extern IntPtr GetParent(IntPtr hWnd);[DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);[DllImport("user32.dll", EntryPoint = "IsWindow")]public static extern bool IsWindow(IntPtr hWnd);[DllImport("kernel32.dll", EntryPoint = "SetLastError")]public static extern void SetLastError(uint dwErrCode);public static IntPtr GetCurrentWindowHandle(){IntPtr ptrWnd = IntPtr.Zero;uint uiPid = (uint)Process.GetCurrentProcess().Id; // 当前进程 IDobject objWnd = processWnd[uiPid];if (objWnd != null){ptrWnd = (IntPtr)objWnd;if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd)) // 从缓存中获取句柄{return ptrWnd;}else{ptrWnd = IntPtr.Zero;}}bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);// 枚举窗⼝返回 false 并且没有错误号时表明获取成功if (!bResult && Marshal.GetLastWin32Error() == 0){objWnd = processWnd[uiPid];if (objWnd != null){ptrWnd = (IntPtr)objWnd;}}return ptrWnd;}private static bool EnumWindowsProc(IntPtr hwnd, uint lParam){uint uiPid = 0;if (GetParent(hwnd) == IntPtr.Zero){GetWindowThreadProcessId(hwnd, ref uiPid);if (uiPid == lParam) // 找到进程对应的主窗⼝句柄{processWnd[uiPid] = hwnd; // 把句柄缓存起来SetLastError(0); // 设置⽆错误return false; // 返回 false 以终⽌枚举窗⼝}}return true;}}调⽤User32API.GetCurrentWindowHandle()即可返回当前进程的主窗⼝句柄,如果获取失败则返回IntPtr.Zero。

c语言句柄的用法

c语言句柄的用法

c语言句柄的用法C语言句柄的用法句柄(Handle)是一种对某个对象的引用或代理,它提供了对对象的访问和操作。

在C语言中,句柄通常是一个整型或指针类型的变量,用于标识或引用某个资源。

下面是一些常见的C语言句柄的用法:文件句柄文件句柄用于对文件进行操作,包括打开、读写、关闭等操作。

•打开文件:使用文件句柄可以打开一个文件,获取文件句柄后就可以对文件进行读取或写入操作。

例如:FILE *file = fopen("", "r");•读取文件:使用文件句柄可以对文件进行读取操作。

例如:char buffer[100];fgets(buffer, 100, file);•写入文件:使用文件句柄可以对文件进行写入操作。

例如:fputs("Hello, World!", file);•关闭文件:使用文件句柄可以关闭文件,释放资源。

例如:fclose(file);窗口句柄窗口句柄用于对窗口进行操作,比如创建、显示、隐藏等操作。

•创建窗口:使用窗口句柄可以创建一个窗口。

例如:HWND hwnd = CreateWindow("MyWindowClass", "My Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 500, NULL, NULL, hInstance, NULL);•显示窗口:使用窗口句柄可以显示一个窗口。

例如:ShowWindow(hwnd, nCmdShow);•隐藏窗口:使用窗口句柄可以隐藏一个窗口。

例如:ShowWindow(hwnd, SW_HIDE);内存句柄内存句柄用于对内存进行分配和释放操作。

•分配内存:使用内存句柄可以分配一块内存。

例如:HANDLE hMemory = GlobalAlloc(GMEM_MOVEABLE, 100);•使用内存:使用内存句柄可以对已分配的内存进行读写操作。

c语言 句柄判断程序

c语言 句柄判断程序

如何判断c语言句柄?
在c语言中,句柄(handle)是指某个操作系统或程序所分配的
一个代表资源的整数值。

例如文件句柄代表着一个打开的文件,窗口
句柄代表着一个打开的窗口等等。

所以说,判断c语言句柄的方法就
是判断代表的资源是否有效。

以下是一些常见的判断句柄的方法:
1. 文件句柄
在打开文件时,fopen函数会返回一个文件指针。

判断这个文件指针是否有效,可以使用feof函数先判断文件是否结束,如果没有结束,再使用ferror函数判断是否有错误。

如果文件已经结束或者出错,则
认为文件指针无效。

2. 窗口句柄
在Windows操作系统中,窗口句柄代表着一个窗口。

判断窗口句
柄是否有效,可以使用IsWindow函数,该函数返回值为TRUE时代表
窗口句柄有效,否则无效。

3. 进程句柄
在Windows操作系统中,进程句柄代表着一个进程。

判断进程句
柄是否有效,可以使用OpenProcess函数,该函数返回一个进程句柄,如果返回值为NULL,则代表进程句柄无效。

需要注意的是,在使用句柄时,要注意处理句柄泄露的情况,即句柄在不需要时没有被释放,导致资源浪费。

为了避免句柄泄露,我们应该在使用完句柄后及时释放它们。

总之,判断c语言句柄的方法因资源而异,需要根据具体情况来选择。

同时,避免句柄泄露也是很重要的。

cshell句柄

cshell句柄

在C语言中,句柄(handle)是一个用于表示某个资源或对象的概念。

它通常是一个整数或指针,用于在程序中引用和操作该资源或对象。

在CShell中,句柄通常用于表示不同类型的资源,例如文件、网络连接、数据库连接等。

通过使用句柄,程序可以打开、读取、写入和关闭这些资源,而无需直接操作底层的文件名、网络地址等细节。

下面是一个示例,演示了如何在CShell中使用文件句柄:```c#include <stdio.h>#include <fcntl.h>#include <unistd.h>int main() {int file_handle;char buffer[256];// 打开文件file_handle = open("example.txt", O_RDONLY);if (file_handle == -1) {perror("Failed to open file");return 1;}// 读取文件内容ssize_t bytes_read = read(file_handle, buffer, sizeof(buffer)); if (bytes_read == -1) {perror("Failed to read file");close(file_handle);return 1;}// 输出文件内容printf("File content: %s\n", buffer);// 关闭文件if (close(file_handle) == -1) {perror("Failed to close file");return 1;}return 0;}```在这个示例中,我们使用了`open()`函数来打开一个名为`example.txt`的文件,并获取其文件句柄。

c语言中sendinput函数

c语言中sendinput函数

c语言中sendinput函数sendinput函数是C语言中的一个系统函数,用于模拟用户的输入操作。

该函数主要用于自动化测试、远程控制以及编写键盘驱动等应用场景。

它可以模拟鼠标、键盘和其他输入设备的输入操作,从而实现对目标窗口的操作。

sendinput函数的原型如下:```cUINT WINAPI SendInputUINT nInputs,LPINPUT pInputs,int cbSize```该函数接受三个参数,分别是nInputs、pInputs和cbSize。

1. nInputs是一个无符号整数,表示输入数据的个数。

它指定了pInputs数组中结构体的数量。

2. pInputs是一个指向INPUT结构体的指针数组。

每个INPUT结构体描述了一个输入事件,可以是鼠标事件、键盘事件或者硬件事件。

3. cbSize是一个整数,表示一个INPUT结构体的大小。

它通常使用sizeof(INPUT)来获取。

INPUT结构体的定义如下:```ctypedef struct tagINPUTDWORD type;unionMOUSEINPUT mi;KEYBDINPUT ki;HARDWAREINPUT hi;}DUMMYUNIONNAME;}INPUT,*PINPUT,*LPINPUT;```其中,type表示输入事件的类型,可以是INPUT_MOUSE、INPUT_KEYBOARD和INPUT_HARDWARE等。

而mi、ki和hi是用来表示具体输入事件类型的联合体,分别对应鼠标事件、键盘事件和硬件事件。

下面分别介绍几种常见的输入事件。

1.鼠标事件MOUSEINPUT结构体定义了鼠标事件的信息,包括鼠标位置、鼠标按键状态以及鼠标移动信息等。

2.键盘事件KEYBDINPUT结构体定义了键盘事件的信息,包括按键的扫描码、按键的状态以及按键的附加信息。

3.硬件事件HARDWAREINPUT结构体定义了硬件事件的信息,可以用来模拟若干硬件操作,如模拟发送电流等。

C语言控制台窗口界面编程控制

C语言控制台窗口界面编程控制

控制台窗口界面编程控制摘要一、概述二、控制台文本窗口的一般控制步骤三、控制台窗口操作四、文本属性操作五、文本输出六、文本操作示例七、滚动和移动八、光标操作九、读取键盘信息十、读取鼠标信息十一、结语摘要单击右键可弹出快捷菜单操作文本界面的控制台应用程序开发是深入学习C++、掌握交互系统的实现方法的最简单的一种手段。

然而,Visual C++的C++专用库却没有TC所支持的文本(字符)屏幕控制函数,为此本系列文章从一般控制步骤、控制台窗口操作、文本(字符)控制、滚动和移动、光标、键盘和鼠标等几个方面讨论控制台窗口界面的编程控制方法。

在众多C++开发工具中,由于Microsoft本身的独特优势,选用 Visual C++已越来越被众多学习者所接受。

显然,现今如果还再把TC作为开发环境的话,不仅没有必要,而且也不利于向Windows应用程序开发的过渡。

然而,Visual C++的C++专用库却没有TC所支持的文本屏幕(控制台窗口)控制函数(相应的头文件是conio.h)。

这必然给C++学习者在文本界面设计和编程上带来诸多不便。

要知道,文本界面设计是一种深入学习C++、掌握交互系统的实现方法的最简单的一种手段,它不像C++的Windows图形界面应用程序,涉及知识过多。

为此,本系列文章来讨论在Visual C++ 6.0开发环境中,如何编写具有美观清晰的控制台窗口界面的C++应用程序。

一、概述单击右键可弹出快捷菜单操作所谓控制台应用程序,就是指那些需要与传统DOS操作系统保持某种程序的兼容,同时又不需要为用户提供完善界面的程序。

简单地讲,就是指在Windows环境下运行的DOS程序。

一旦C++控制台应用程序在Windows 9x/NT/2000操作系统中运行后,就会弹出一个窗口。

例如下列过程:单击Visual C++标准工具栏上的“New Text File”按钮,打开一个新的文档窗口。

选择File | Save菜单或按快捷键Ctrl+S或单击标准工具栏的Save按钮,弹出“保存为”文件对话框。

按键精灵句柄使用示例

按键精灵句柄使用示例

按键精灵可以通过使用句柄来获取窗口、控件等对象的引用,进而进行操作。

以下是使用句柄的示例:
1. 获取窗口句柄:
```csharp
Hwnd = Plugin.Window.Find("类名", "标题名")
```
其中,“类名”和“标题名”分别代表目标窗口的类名和标题。

如果找到了目标窗口,则返回窗口句柄;否则返回0。

2. 获取子窗口句柄:
```csharp
HwndEx = Plugin.Window.FindEx(Hwnd, 0, "子窗口类名", "子窗口标题")
```
其中,`Hwnd`是父窗口的句柄,“子窗口类名”和“子窗口标题”分别代表子窗口的类名和标题。

如果找到了子窗口,则返回子窗口句柄;否则返回0。

3. 使用句柄进行操作:
```csharp
Call Plugin.Window.Min(Hwnd) '最小化窗口
Delay 500 '等待500毫秒
Call Plugin.Bkgnd.LeftClick(HwndEx, 475, 574) '在子窗口左上角点击鼠标左键
```
其中,`Plugin.Window.Min(Hwnd)`表示将目标窗口最小化;`Delay 500`表示等待500毫秒;`Plugin.Bkgnd.LeftClick(HwndEx, 475, 574)`表示在子窗口左上角点击鼠标左键。

以上示例仅供参考,实际使用时需要根据具体情况进行调整。

c语言sendmessage函数用法

c语言sendmessage函数用法

c语言sendmessage函数用法摘要:1.C语言SendMessage函数简介2.SendMessage函数的参数3.SendMessage函数的用途4.SendMessage函数的实例5.注意事项正文:C语言SendMessage函数是一种在Windows操作系统中发送消息的函数,它主要用于在不同进程之间传递消息。

SendMessage函数的原型为:```BOOL SendMessage(HWND hWnd, // 目标窗口句柄UINT msg, // 消息码WPARAM wParam, // 消息参数LPARAM lParam // 消息附加参数);```SendMessage函数主要有以下几个参数:1.hWnd:目标窗口的句柄,通过这个句柄可以找到目标窗口。

2.msg:消息码,表示要发送的消息类型,如WM_NULL、WM_KEYDOWN等。

3.wParam:消息参数,根据不同消息类型,传递相应的信息。

4.lParam:消息附加参数,根据不同消息类型,传递附加信息。

SendMessage函数的用途主要包括:1.在同一进程的不同窗口之间传递消息。

2.在不同进程之间传递消息,但进程必须支持消息传递功能。

以下是一个SendMessage函数的实例:```c#include <windows.h>LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam){switch (msg){case WM_DESTROY:PostQuitMessage(0);return 0;case WM_KEYDOWN:if (wParam == VK_SPACE){MessageBox(NULL, TEXT("你按下了空格键!"), TEXT("提示"), MB_OK);return 0;}return DefWindowProc(hWnd, msg, wParam, lParam);}int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){WNDCLASS wc = { 0 };wc.lpfnWndProc = WndProc;wc.hInstance = hInstance;wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);wc.hCursor = LoadCursor(NULL, IDC_ARROW);wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);wc.lpszClassName = TEXT("SendMessageExample");if (!RegisterClass(&wc)){MessageBox(NULL, TEXT("注册窗口类失败!"), TEXT("错误"), MB_OK);return 1;}HWND hWnd = CreateWindowEx(TEXT("SendMessageExample"),TEXT("发送消息示例"),WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,NULL,NULL,hInstance,NULL);if (!hWnd){MessageBox(NULL, TEXT("创建窗口失败!"), TEXT("错误"), MB_OK);return 1;}ShowWindow(hWnd, nCmdShow);UpdateWindow(hWnd);MSG msg;while (GetMessage(&msg, NULL, 0, 0)){TranslateMessage(&msg);DispatchMessage(&msg);}return msg.wParam;}```在上述例子中,我们创建了一个窗口,当用户按下空格键时,会弹出一个提示框显示“你按下了空格键!”。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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};", Escape,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()));}}上全部代码,里面加了窗口的部分属性,扩展其他的属性,自己发挥吧,就是搞WinAPIView 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 nMaxCount);[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};", Escape,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 proper credit 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{void *dllString, *stub;unsigned long wowID;HANDLE hProcess?unsigned long threadID;HANDLE hThread;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 = ;We needVirtualProtect(loadDll, stubLen, PAGE_EXECUTE_READWRITE, &oldprot); ?Sleep(8000);VirtualFreeEx(hProcess, dllString, strlen(DLL_NAME), MEM_DECOMMIT); VirtualFreeEx(hProcess, stub, stubLen, MEM_DECOMMIT);CloseHandle(hProcess);CloseHandle(hThread);unsigned long GetTargetProcessIdFromWindow(char *className, char *windowName) {unsigned long procID;HWND targetWnd;targetWnd = FindWindow(className, windowName);GetWindowThreadProcessId(targetWnd, &procId);?return procID;}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 ;}unsigned long GetTargetThreadIdFromWindow(char *className, char *windowName) {HWND targetWnd;HANDLE hProcessunsigned long processId, pTID, threadID;targetWnd = FindWindow(className, windowName);GetWindowThreadProcessId(targetWnd, &processId);_asm {mov eax, fs:[0x18]add eax, 36mov [pTID], eax}hProcess = OpenProcess(PROCESS_VM_READ, false, processID);ReadProcessMemory(hProcess, (const void *)pTID, &threadID, 4, NULL); CloseHandle(hProcess);return threadID;}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 <>#include <>#define PROCESS_NAME ""#define DLL_NAME ""#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)));return (version < 0x);}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 LoadLibrary push 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; }。

相关文档
最新文档