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语言是一种通用的编程语言,可以用来开发各种类型的应用程序,包括图形用户界面(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语言中,句柄(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语言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;}```在上述例子中,我们创建了一个窗口,当用户按下空格键时,会弹出一个提示框显示“你按下了空格键!”。
C语言API编写窗口界面和button

C语⾔API编写窗⼝界⾯和button近期有个同学的程序须要⽤对话框的⽅式实现,但前⾯都是通过⿊框形式完毕的,⽼师突然让添加⼀个界⾯,本来准备採⽤MFC完毕的,但后来⼀想,该程序核⼼东西是体如今它的算法上,控制台的程序并不是不好.转念⼀想,假设使⽤MFC这个⽅案好像须要再倒腾⼀遍,想到了⼤⼀在"C语⾔能⼲⼤事"中的东西,所以就准备採⽤这种形式直接完毕,投机取巧的⽅法.主要是通过调⽤Windows API界⾯的CreateWindows函数完毕,同⼀时候也能创建button,把參数设置为button,假设想响应该button,仅仅需在回调函数中添加消息WM_COMMAND推断就可以.代码例如以下:#include<windows.h>#include<stdio.h>//声明回调函数LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;//主函数程序⼊⼝int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow){static TCHAR szAppName[] = TEXT ("HelloWin") ;HWND hwnd ; //⽤来保存成功创建窗⼝后返回的句柄MSG msg ; //定义消息结构体变量WNDCLASS wndclass ; //窗⼝类wndclass.style = CS_HREDRAW | CS_VREDRAW ; //指定窗⼝风格wndclass.lpfnWndProc = WndProc ; ////函数指针,指向处理窗⼝消息的函数⼊⼝wndclass.cbClsExtra = 0 ; //结构体后附加的字节数,⼀般总为0wndclass.cbWndExtra = 0 ; //窗⼝实例附加的字节数,⼀般总为0wndclass.hInstance = hInstance ; //模块句柄wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ; //图标句柄任务栏显⽰的图标wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ; //光标句柄wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //背景颜⾊COLOR_BACKGROUNDwndclass.lpszMenuName = NULL ; //菜单名的字符串wndclass.lpszClassName = szAppName ; //⾃⼰定义类名,不要与其它类名反复if (!RegisterClass (&wndclass)){MessageBox (NULL, TEXT ("注冊类失败!"), szAppName, MB_ICONERROR) ;return 0 ;}int x =((GetSystemMetrics(SM_CXSCREEN)/2)-200); //x居中int y =((GetSystemMetrics(SM_CYSCREEN)/2)-200); //y居中//创建窗⼝APIhwnd = CreateWindow(szAppName,TEXT("毕业设计"),WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX,x,y,400,400,NULL,NULL,hInstance,NULL);//显⽰窗⼝的API 传⼊须要显⽰的窗⼝句柄和显⽰⽅式ShowWindow(hwnd,iCmdShow);//刷新窗⼝的APIUpdateWindow(hwnd);//从系统的应⽤程序线程消息队列中取得⼀个消息while(GetMessage(&msg,NULL,0,0) > 0){DispatchMessage(&msg);}return msg.wParam;}LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){HDC hdc; //句柄PAINTSTRUCT ps;RECT rect; //矩形HINSTANCE hInstance; //窗⼝实例static HWND hwndButton[2]; //button句柄switch (message){case WM_CREATE: //创建button{hInstance = ((LPCREATESTRUCT)lParam)->hInstance;//button1hwndButton[0] = CreateWindow("BUTTON","训练",WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,10,10,100,100,hwnd,NULL,(HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL);//button2hwndButton[1] = CreateWindow("BUTTON","获取",WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,10,250,100,100,hwnd,NULL,(HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL);return 0;}case WM_PAINT: //绘制⽂字hdc = BeginPaint(hwnd,&ps);GetClientRect(hwnd,&rect);DrawText(hdc,TEXT("By:Eastmount CSDN制作"),-1,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER); EndPaint(hwnd,&ps);return 0;case WM_COMMAND: //响应button消息if((HWND)lParam == hwndButton[0]){MessageBox(NULL,TEXT("是否训练图⽚?"),TEXT("提⽰"),MB_YESNO|MB_ICONQUESTION);}if((HWND)lParam == hwndButton[1]){MessageBox(NULL,TEXT("是否获取图⽚?"),TEXT("提⽰"),MB_YESNO|MB_ICONQUESTION);}return 0;case WM_CLOSE: //关闭if(IDYES==MessageBox(hwnd,"是否关闭程序?","提⽰",MB_YESNO|MB_ICONQUESTION)){DestroyWindow (hwnd);}return 0;case WM_DESTROY: //退出程序PostQuitMessage (0) ;return 0 ;}return DefWindowProc (hwnd, message, wParam, lParam) ;}程序执⾏结果例如以下图所看到的:当中主要涉及到的函数原型例如以下所看到的://创建窗⼝hwnd = CreateWindow (szClassName, /* Classname */"Windows App", /* Title Text */WS_OVERLAPPEDWINDOW, /* default window */CW_USEDEFAULT, /* Windows decides the position */CW_USEDEFAULT, /* where the window ends up on the screen */544, /* The programs width */375, /* and height in pixels */HWND_DESKTOP, /* The window is a child-window to desktop */NULL, /* No menu */hThisInstance, /* Program Instance handler */NULL /* No Window Creation data */);//创建按钮hwndButton = CreateWindow("BUTTON", // predefined class"OK", // button textWS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // styles10, // starting x position10, // starting y position100, // button width100, // button heighthwnd, // parent windowNULL, // No menu(HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE),NULL // pointer not needed);最后,写这篇⽂章主要是怀念⾃⼰⼤⼀时的⽣活,从⼀个什么都不知道的孩⼦,通过学习C语⾔,C语⾔能⼲⼤事開始接触编程.同⼀时候,我觉得这个程序也是很还的⼊门程序,希望刚接触程序的同学也能够看看,编编⾃⼰感兴趣的程序、写写博客、AC题⽬、编写游戏、聊天软件、移动开发,能从程序和⽣活中找到⼀些让⾃⼰⼼灵美妙的东西.(By:Eastmount 2014-5-25 夜2点半原创CSDN)。
如何获得窗口句柄和改变窗口属性

如何获得窗口句柄和改变窗口属性要获得窗口句柄(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);```这个函数可以重新设置窗口的位置、大小,并且可以实时更新窗口的样式。
需要注意的是,对于不属于当前进程创建的窗口,可能需要通过其他技术手段获取窗口句柄并改变属性,如使用钩子函数或其他进程间通信的方式。
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`,实现了两个窗口之间的通信。
MFC的窗口句柄

MFC的窗⼝句柄1.窗⼝、控件的指针和句柄的相互转化1)指针转化为句柄在MFC应⽤程序中⾸先要获得窗⼝的指针,然后将其转化为句柄 CWnd* pWnd; HANDLE hWnd = pWnd->GetSafeHwnd();2)句柄转化为指针在MFC应⽤程序中⾸先获得对话框控件的句柄,然后获得其指针HANDLE hWnd;GetDlgItem(IDC_xxx,&hWnd);CWnd * pWnd = FromHandle(hWnd);获得程序窗⼝指针的办法:a.获得主框架窗⼝指针(任何时候都可以⽤,只要是MFC程序中):CWnd* pWnd = AfxGetMainWnd();b.获得对话框中控件指针:CWnd* pWnd = GetDlgItem(IDC_xxx);c.获得对话框中某控件的句柄:HANDLE GetDlgItem(m_hDLG,m_nID_DlgItem);d.获得GDI对象的句柄:HANDLE m_hGDIObj = m_pGDIObj->GetSafeHanle();2. 如何获取应⽤程序的实例句柄?AfxGetInstanceHandle()应⽤程序的实例句柄保存在CWinAppIm_hInstance 中,可以这么调⽤ AfxGetInstancdHandle获得句柄;Example: HANDLE hInstance=AfxGetInstanceHandle();3. 如何通过代码获得应⽤程序主窗⼝的指针?AfxGetMainWnd GetSafeHwnd() AfxGetAppName() AfxGetThread主窗⼝的指针保存在CWinThread::m_pMainWnd中,调⽤ AfxGetMainWnd实现。
【例】 AfxGetMainWnd() ->ShowWindow(SW_SHOWMAXMIZED); //使程序最⼤化.【例】此例的主窗⼝是对话框,下⾯的代码是在另外⼀个CFileTreeCtrl 类(⼦窗)中相关函数实现在主对话框(主窗)中的⼏个静态⽂本框(⼦窗)中显⽰路径:CWnd* m_pCWnd= AfxGetMainWnd(); //得到主窗⼝指针,通过主窗指针访问其他⼦窗资源//⽅法⼀m_pCWnd->SetDlgItemText(IDC_STATIC_path,"CWnd* "+m_sCurPath); //在主窗中的⼦窗(ID:IDC_STATIC_path)中显⽰字符串m_pCWnd->SetDlgItemText(IDC_STATIC_who,"路径显⽰由FileTreeCtrl类完成:");//⽅法⼆m_pCWnd->SendMessage(STN_CLICKED); //向主窗⼝发送⼀个消息,显⽰任务由主窗完成。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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()));}}上全部代码,里面加了窗口的部分属性,扩展其他的属性,自己发挥吧,就是搞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 lp szWindow);[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 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 aspropercredit 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 more people should know how to use.The trick is simple, and elegant. The windows API provides us with a function called CreateRemoteThread(). This allows you to 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)));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 thread ret}}__declspec(naked) loadDll_end(void){}。