C利用句柄操作窗口
- 格式:docx
- 大小:24.06 KB
- 文档页数:62
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语言是一种通用的编程语言,可以用来开发各种类型的应用程序,包括图形用户界面(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语言中,句柄(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函数用法摘要: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近期有个同学的程序须要⽤对话框的⽅式实现,但前⾯都是通过⿊框形式完毕的,⽼师突然让添加⼀个界⾯,本来准备採⽤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 中实现两个界面间的通信,通常可以使用消息映射机制或窗口句柄来进行通信。
下面是一个简单的示例,演示了如何在 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的窗⼝句柄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); //向主窗⼝发送⼀个消息,显⽰任务由主窗完成。
如何判断c语言句柄?
在c语言中,句柄(handle)是指某个操作系统或程序所分配的
一个代表资源的整数值。
例如文件句柄代表着一个打开的文件,窗口
句柄代表着一个打开的窗口等等。
所以说,判断c语言句柄的方法就
是判断代表的资源是否有效。
以下是一些常见的判断句柄的方法:
1. 文件句柄
在打开文件时,fopen函数会返回一个文件指针。
判断这个文件指针是否有效,可以使用feof函数先判断文件是否结束,如果没有结束,再使用ferror函数判断是否有错误。
如果文件已经结束或者出错,则
认为文件指针无效。
2. 窗口句柄
在Windows操作系统中,窗口句柄代表着一个窗口。
判断窗口句
柄是否有效,可以使用IsWindow函数,该函数返回值为TRUE时代表
窗口句柄有效,否则无效。
3. 进程句柄
在Windows操作系统中,进程句柄代表着一个进程。
判断进程句
柄是否有效,可以使用OpenProcess函数,该函数返回一个进程句柄,如果返回值为NULL,则代表进程句柄无效。
需要注意的是,在使用句柄时,要注意处理句柄泄露的情况,即句柄在不需要时没有被释放,导致资源浪费。
为了避免句柄泄露,我们应该在使用完句柄后及时释放它们。
总之,判断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#获取进程的主窗⼝句柄的实现⽅法通过调⽤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 枚举指定窗口下的控件概述及解释说明1. 引言1.1 概述本文的主题是关于在C 语言中如何枚举指定窗口下的控件。
随着计算机应用的发展,图形化界面已经成为了现代操作系统和软件开发的重要组成部分。
在开发过程中,我们经常需要与窗口上的各种控件进行交互,比如按钮、文本框等等。
而对于有一定规模的大型应用程序,特别是涉及到多个窗口和多个控件时,如果能够快速准确地获取到指定窗口下的所有控件信息将会大大提高开发效率。
1.2 文章结构本文将按照以下结构来介绍如何枚举指定窗口下的控件:2. 正文:介绍实现这一目标所需的基础知识和步骤。
3. 解释说明:对前述内容进行详细解释和说明,帮助读者更好理解。
4. 枚举指定窗口下的控件方法一:介绍第一种实现方式,并提供相应代码示例。
5. 枚举指定窗口下的控件方法二:介绍第二种实现方式,并提供相应代码示例。
6. 结论:总结全文内容,提出进一步思考和研究的方向。
1.3 目的本文的目的是为了帮助C 语言开发者更好地理解和应用枚举指定窗口下的控件的方法。
通过清晰地介绍相关知识和步骤,并提供实际代码示例,读者可以在自己的项目中灵活运用这些方法,提高开发效率和质量。
同时,本文也希望激发读者对于控件枚举技术的兴趣,促进更深入的研究和应用。
2. 正文在我们的日常编程工作中,经常会遇到需要获取指定窗口下的控件的需求。
无论是为了自动化测试、界面操作或者其他用途,都需要我们能够快速准确地找到并操作所需的控件。
在C语言中,我们可以利用枚举的方式来实现获取指定窗口下的控件。
枚举是一种特殊数据类型,它允许我们定义一组取值范围内的常量,并且可以为每个常量赋予一个标识符。
首先,我们需要通过窗口句柄来获取指定窗口下所有的子窗口。
子窗口通常包括各种类型的控件,如按钮、文本框、列表框等。
一旦我们获得了子窗口句柄,就可以通过枚举每个子窗口的方式来获取其控件信息。
方法一:使用EnumChildWindows函数进行枚举EnumChildWindows函数是Windows API提供的一个函数,可以用来枚举指定父窗口下所有直接子孙层次关系的子窗口。
WinCC中C脚本弹出对话框代码代码:int cal_wr;cal_wr=MessageBox(NULL, "1#卷取机1#助卷辊标定?", "标定确认",MB_YESNO|MB_SYSTEMMODAL);if (cal_wr==IDYES)SetTagBit("TAGNAME",TRUE);elseSetTagBit("TAGNAME",FALSE);相关知识:HWND hWnd=NULL //定义变量hWnd=FindWindow(NULL,"Wincc‐运行系统 ‐ ") //获取窗口句柄MessageBox(hWnd,"这是个对话框!","哈哈",MB_OKCANCEL|MB_ICONWARNING|MB_APPLMODAL)函数功能:该函数创建、显示、和操作一个消息框。
消息框含有应用程序定义的消息和标题,加上预定义图标与Push(下按)按钮的任何组合。
函数原型:int MessageBox(HWND hWnd,LPCTSTR IpCaption,UINT UType);参数:hWnd:标识将被创建的消息框的拥有窗口。
如果此参数为NULL,则消息框没有拥有窗口。
IpText:指向一个以NULL结尾的、含有将被显示的消息的字符串的指针。
IpCaption:指向一个以NULL结尾的、用于对话框标题的字符串的指针。
uType:指定一个决定对话框的内容和行为的位标志集。
此参数可以为下列标志组中标志的组合。
指定下列标志中的一个来显示消息框中的按钮,标志的含义如下。
MB_ABORTRETRYIGNORE:消息框含有三个按钮:Abort,Retry和Ignore。
MB_OK:消息框含有一个按钮:OK。
这是缺省值。
MB_OKCANCEL:消息框含有两个按钮:OK和Cancel。
C语⾔Windows程序开发—MessageBox函数介绍【第01天】(⼀)MessageBox函数的参数介绍:1int MessageBox (2 HWND hWnd, //弹出MessageBox对话框所属的窗⼝句柄3 LPCTSTR lpText, //指向MessageBox对话框内容的字符串指针4 LPCTSTR lpCaption, //指向MessageBox对话框标题的字符串指针5 UINT uType //MessageBox对话框的风格6 ) ;函数调⽤⽰例:1 MessageBox ( NULL, TEXT ("程序运⾏出错!"), TEXT ("错误"), MB_OK | MB_ICONERROR ) ;第1个参数:窗⼝句柄的实参为NULL,表⽰不属于任何窗⼝;第2个参数:对话框内容,“程序运⾏错误!”;第3个参数:对话框标题,“错误”;第4个参数:对话框风格,其值通常是以MB_开头的常量组合(MB_按钮类型 | MB_图标类型)对话框风格常量类型:<1>对话框的按钮类型:1#define MB_OK 0x00000000L //"确定"2#define MB_OKCANCEL 0x00000001L //"确定" + "取消"3#define MB_ABORTRETRYIGNORE 0x00000002L //"终⽌" + "重试" + "忽略"4#define MB_YESNOCANCEL 0x00000003L //"是" + "否" + "取消"5#define MB_YESNO 0x00000004L //"是" + "否"6#define MB_RETRYCANCEL 0x00000005L //"重试" + "取消"<2>对话框的图标类型1#define MB_ICONHAND 0x00000010L //带有红X的错误/停⽌图标2#define MB_ICONQUESTION 0x00000020L //问号的询问图标3#define MB_ICONEXCLAMATION 0x00000030L //黄⾊感叹号的警告图标4#define MB_ICONASTERISK 0x00000040L //带有蓝i的信息提⽰图标(⼆)MessageBox函数实例应⽤1 #include <windows.h>23int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow )4 {5 MessageBox ( NULL, TEXT ("Hello, World!"), TEXT ("MessageBox⽰例"), MB_OK ) ;6return0 ;7 }运⾏结果:。
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++程序设计有所帮助。
按键精灵可以通过使用句柄来获取窗口、控件等对象的引用,进而进行操作。
以下是使用句柄的示例:
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)`表示在子窗口左上角点击鼠标左键。
以上示例仅供参考,实际使用时需要根据具体情况进行调整。
MFC中CWnd类及其派生类对话框、消息处理、窗口操作CWnd类我们在屏幕上看到的所有对象都和窗口有关,它们或者派生于CWnd,属继承关系,如对话框、工具栏、状态栏、子控件;或者被CWnd合成,属服务员与服务对象关系,如图标、菜单、显示设备。
CWnd类封装的窗口操作主要包含窗口的创建和销毁、操作窗口风格、操作窗口状态、窗口子类化、获取指定窗口等。
当然,CWnd还实现了其他功能:1、绘制窗口GetDC()//取得客户区显示设备上下文GetWindowsDC()//取得整个窗口的显示设备上下文ReleaseDC()BeginPaint()EndPaint()PrintClient()RedrawWindow()//重绘客户区的某区域2、操作窗口子控件GetDlgItem():取得(临时的)控件对象指针SetDlgItemText()和GetDlgItemText():设置、取得控件标题SubclassDlgItem():将控件句柄与相应类相关联DlgDirList()和DlgDirListComboBox():以文件列表或目录列表填充(组合框)列表框CheckDlgButton()和CheckRadioButton():设置复选框(单选按钮)状态。
GetNextDlgTabItem():取得下一个WS_TABSTOP风格控件3、窗口定时器SetTimer():设置定时器KillTimer():销毁定时器4、窗口消息的相关函数GetCurrentMessage():取得当前被处理的消息PreTranslateMessage():可重载的虚函数。
被UI线程的消息循环调用,可以过滤窗口收到的消息,过滤出的消息得以分发SendMessage():向本窗口发送消息。
不通过消息循环,直接调用窗口函数处理消息。
窗口函数执行完毕,该函数才返回PostMessage():向本窗口寄送消息。
将消息放入消息队列,立即返回。
【核心代码】using System;using System.Drawing;using System.Collections;using ponentModel;using System.Windows.Forms;using System.Runtime.InteropServices; using System.Security.Permissions; using System.Reflection;using System.Globalization;using System.Diagnostics;using Common;namespace TaskbarSorter{/// <summary>/// Summary description for Form1./// </summary>public class Form1 : System.Windows.Forms.Form{private System.Windows.Forms.Button button1;private System.Windows.Forms.ToolBar toolBar1;private System.Windows.Forms.TreeListView treeListView1;private System.Windows.Forms.ColumnHeader columnHeader1;private ponentModel.IContainer components;private System.Windows.Forms.ColumnHeader columnHeader2;private System.Windows.Forms.ColumnHeader columnHeader3;private System.Windows.Forms.ColumnHeader columnHeader4;private System.Windows.Forms.ToolBarButton toolBarButtonMoveFirst;private System.Windows.Forms.ToolBarButton toolBarButtonMoveUp; private System.Windows.Forms.ImageList imageListToolbar;private System.Windows.Forms.ToolBarButton toolBarButtonMoveDown;private System.Windows.Forms.ToolBarButton toolBarButtonMoveLast;private System.Windows.Forms.Button _Apply;private System.Windows.Forms.Button _ViewTree;private System.Windows.Forms.Button _ExpandAll;private System.Windows.Forms.Button _CollapseAll;private System.Windows.Forms.ImageList imageListTreeView;private System.Windows.Forms.Button _Repair;private System.Windows.Forms.ToolTip _ToolTips;private Icon _Icon = null;private bool_FirstActivation = true;private ITree _Tree = NodeTree.NewTree( typeof( DataBase ) );private IntPtr _ToolbarWindowHandle = IntPtr.Zero;private bool_Glomming = true;public Form1(){string[] a =Assembly.GetEntryAssembly().GetManifestResourceNames();Trace.WriteLine( "\nResourceNames:");foreach( string s in a ) Trace.WriteLine( "\t"s );Trace.WriteLine( "");InitializeComponent();}protected override void OnHandleCreated( EventArgs e ){base.OnHandleCreated( e );UInt32 hIcon = User32.GetClassLong( Handle, GCL.HICONSM );if( hIcon == 0 ){if( _Icon == null) _Icon = new Icon( typeof( Form1 ), "Icons.App.ico");User32.SetClassLong( Handle, GCL.HICONSM, ( UInt32 ) _Icon.Handle );}}/// <summary>/// Clean up any resources being used./// </summary>protected override void Dispose( bool disposing ){if( disposing ){if(components != null){components.Dispose();}}base.Dispose( disposing );}#region Windows Form Designer generated code/// <summary>/// Required method for Designer support - do not modify/// the contents of this method with the code editor./// </summary>private void InitializeComponent(){ponents = new ponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));this.button1 = new System.Windows.Forms.Button();this.toolBar1 = new System.Windows.Forms.ToolBar();this.toolBarButtonMoveFirst = newSystem.Windows.Forms.ToolBarButton();this.toolBarButtonMoveUp = newSystem.Windows.Forms.ToolBarButton();this.toolBarButtonMoveDown = newSystem.Windows.Forms.ToolBarButton();this.toolBarButtonMoveLast = newSystem.Windows.Forms.ToolBarButton();this.imageListToolbar = newSystem.Windows.Forms.ImageList(ponents);this.treeListView1 = newSystem.Windows.Forms.TreeListView();this.columnHeader1 = newSystem.Windows.Forms.ColumnHeader();this.columnHeader2 = newSystem.Windows.Forms.ColumnHeader();this.columnHeader3 = newSystem.Windows.Forms.ColumnHeader();this.columnHeader4 = newSystem.Windows.Forms.ColumnHeader();this.imageListTreeView = newSystem.Windows.Forms.ImageList(ponents);this._Apply = new System.Windows.Forms.Button();this._ViewTree = new System.Windows.Forms.Button();this._ExpandAll = new System.Windows.Forms.Button();this._CollapseAll = new System.Windows.Forms.Button(); this._Repair = new System.Windows.Forms.Button();this._ToolTips = newSystem.Windows.Forms.ToolTip(ponents);this.SuspendLayout();//// button1//this.button1.FlatStyle =System.Windows.Forms.FlatStyle.System;this.button1.Location = new System.Drawing.Point(8, 32); = "button1";this.button1.TabIndex = 1;this.button1.Text = "Refresh";this.button1.Click = newSystem.EventHandler(this.button1_Click);//// toolBar1//this.toolBar1.Appearance =System.Windows.Forms.ToolBarAppearance.Flat;this.toolBar1.Buttons.AddRange(newSystem.Windows.Forms.ToolBarButton[] {this.toolBarButtonMoveFirst,this.toolBarButtonMoveUp,this.toolBarButtonMoveDown,this.toolBarButtonMoveLast});this.toolBar1.DropDownArrows = true;this.toolBar1.ImageList = this.imageListToolbar;this.toolBar1.Location = new System.Drawing.Point(0, 0); = "toolBar1";this.toolBar1.ShowToolTips = true;this.toolBar1.Size = new System.Drawing.Size(592, 28);this.toolBar1.TabIndex = 0;this.toolBar1.ButtonClick = newSystem.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_Butt onClick);//// toolBarButtonMoveFirst//this.toolBarButtonMoveFirst.ImageIndex = 0;this.toolBarButtonMoveFirst.ToolTipText = "Move First"; //// toolBarButtonMoveUp//this.toolBarButtonMoveUp.ImageIndex = 1;this.toolBarButtonMoveUp.ToolTipText = "Move Up";//// toolBarButtonMoveDown//this.toolBarButtonMoveDown.ImageIndex = 2;this.toolBarButtonMoveDown.ToolTipText = "Move Down";//// toolBarButtonMoveLast//this.toolBarButtonMoveLast.ImageIndex = 3;this.toolBarButtonMoveLast.ToolTipText = "Move Last";//// imageListToolbar//this.imageListToolbar.ImageSize = new System.Drawing.Size(16, 16);this.imageListToolbar.ImageStream =((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageLi stToolbar.ImageStream")));this.imageListToolbar.TransparentColor =System.Drawing.Color.Transparent;//// treeListView1//this.treeListView1.AllowColumnReorder = true;this.treeListView1.Anchor =((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorSty les.Top | System.Windows.Forms.AnchorStyles.Bottom)| System.Windows.Forms.AnchorStyles.Left)| System.Windows.Forms.AnchorStyles.Right)));this.treeListView1.Columns.AddRange(newSystem.Windows.Forms.ColumnHeader[] {this.columnHeader1,this.columnHeader2,this.columnHeader3,this.columnHeader4});this.treeListView1.HideSelection = false;this.treeListView1.Location = new System.Drawing.Point(8, 64);this.treeListView1.MultiSelect = false; = "treeListView1";this.treeListView1.Size = new System.Drawing.Size(572, 392); this.treeListView1.SmallImageList = this.imageListTreeView; this.treeListView1.Sorting =System.Windows.Forms.SortOrder.None;this.treeListView1.TabIndex = 6;this.treeListView1.DoubleClick = newSystem.EventHandler(this.treeListView1_DoubleClick);//// columnHeader1//this.columnHeader1.Text = "Process / Window";this.columnHeader1.Width = 300;//// columnHeader2//this.columnHeader2.Text = "Windows";//// columnHeader3//this.columnHeader3.Text = "Window Handle";this.columnHeader3.Width = 100;//// columnHeader4//this.columnHeader4.Text = "Process Id";this.columnHeader4.Width = 90;//// imageListTreeView//this.imageListTreeView.ImageSize = newSystem.Drawing.Size(16, 16);this.imageListTreeView.ImageStream =((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageLi stTreeView.ImageStream")));this.imageListTreeView.TransparentColor =System.Drawing.Color.Transparent;//// _Apply//this._Apply.FlatStyle =System.Windows.Forms.FlatStyle.System;this._Apply.Location = new System.Drawing.Point(96, 32);this._ = "_Apply";this._Apply.TabIndex = 2;this._Apply.Text = "Apply";this._Apply.Click = newSystem.EventHandler(this._Apply_Click);//// _ViewTree//this._ViewTree.FlatStyle =System.Windows.Forms.FlatStyle.System;this._ViewTree.Location = new System.Drawing.Point(504, 32); this._ = "_ViewTree";this._ViewTree.TabIndex = 5;this._ViewTree.Text = "View Tree";this._ViewTree.Click = newSystem.EventHandler(this._ViewTree_Click);//// _ExpandAll//this._ExpandAll.FlatStyle =System.Windows.Forms.FlatStyle.System;this._ExpandAll.Location = new System.Drawing.Point(200, 32); this._ = "_ExpandAll";this._ExpandAll.TabIndex = 3;this._ExpandAll.Text = "Expand All";this._ExpandAll.Click = newSystem.EventHandler(this._ExpandAll_Click);//// _CollapseAll//this._CollapseAll.FlatStyle =System.Windows.Forms.FlatStyle.System;this._CollapseAll.Location = new System.Drawing.Point(288, 32);this._ = "_CollapseAll";this._CollapseAll.TabIndex = 4;this._CollapseAll.Text = "Collapse All";this._CollapseAll.Click = newSystem.EventHandler(this._CollapseAll_Click);//// _Repair//this._Repair.FlatStyle =System.Windows.Forms.FlatStyle.System;this._Repair.Location = new System.Drawing.Point(416, 32); this._ = "_Repair";this._Repair.TabIndex = 5;this._Repair.Text = "OS Version";this._ToolTips.SetToolTip(this._Repair, "Repair ToolTips"); this._Repair.Click = newSystem.EventHandler(this._Repair_Click);//// Form1//this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);this.ClientSize = new System.Drawing.Size(592, 466);this.Controls.Add(this._ViewTree);this.Controls.Add(this._Apply);this.Controls.Add(this.treeListView1);this.Controls.Add(this.button1);this.Controls.Add(this.toolBar1);this.Controls.Add(this._ExpandAll);this.Controls.Add(this._CollapseAll);this.Controls.Add(this._Repair);this.Icon =((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); = "Form1";this.StartPosition =System.Windows.Forms.FormStartPosition.CenterScreen;this.Text = "Taskbar Sorter";this.Load = new System.EventHandler(this.Form1_Load);this.Activated = newSystem.EventHandler(this.Form1_Activated);this.ResumeLayout(false);}#endregion/// <summary>/// The main entry point for the application./// </summary>[STAThread]// [ PrincipalPermission( SecurityAction.Demand, Authenticated = true ) ]static void Main(){// only supports WinXP or latertry{OperatingSystemVersion os = new OperatingSystemVersion(); string s = os.ToString();if(os.OSPlatformId <= OSPlatformId.Win32Windows ||os.OSPlatformId == OSPlatformId.WinCE ){MessageBox.Show("You must be joking :)","Unsupported OS",MessageBoxButtons.OK,MessageBoxIcon.Stop );return;}if( ( os < OSVersionInfo.WinXP ) ){MessageBox.Show("This program only works on WinXP and later :)" Environment.NewLine Environment.NewLine "You are running:"Environment.NewLine s, "Unsupported OS",MessageBoxButtons.OK,MessageBoxIcon.Stop );return;}}catch( InvalidOperationException x ){MessageBox.Show("Could not determine Operating System."Environment.NewLine Environment.NewLine"Error:"Environment.NewLine x.Message,"Unknown OS",MessageBoxButtons.OK,MessageBoxIcon.Stop );//return;}Application.EnableVisualStyles();Application.DoEvents();Application.Run(new Form1());}private void Form1_Load( object sender, System.EventArgs e ){// SYSTEM_INFO systemInfo;// Kernel32.GetSystemInfo( out systemInfo );// Displays a MessageBox if not found_ToolbarWindowHandle = GetToolbarWindowHandle();if( _ToolbarWindowHandle == IntPtr.Zero ) Close();// true if grouping is on_Glomming = ( Glob.Glomming.Int != 0 );}private void Form1_Activated( object sender, System.EventArgs e ) {if( _FirstActivation ){_FirstActivation = false;button1_Click( this, EventArgs.Empty );}}private IntPtr GetToolbarWindowHandle(){IntPtr hDesktop = User32.GetDesktopWindow();IntPtr hTray = User32.FindWindowEx( hDesktop, IntPtr.Zero, "Shell_TrayWnd", null);IntPtr hReBar = User32.FindWindowEx( hTray, IntPtr.Zero, "ReBarWindow32", null);IntPtr hTask = User32.FindWindowEx( hReBar, IntPtr.Zero, "MSTaskSwWClass", null);IntPtr hToolbar = User32.FindWindowEx( hTask, IntPtr.Zero, "ToolbarWindow32", null);// hToolbar = User32.FindWindowEx( hReBar, IntPtr.Zero, "ToolbarWindow32", "Quick Launch" );// hToolbar = toolBar1.Handle;if( hToolbar == IntPtr.Zero )MessageBox.Show("Couldn't find Taskbar","Error",MessageBoxButtons.OK,MessageBoxIcon.Error );return hToolbar;}private void button1_Click( object sender, System.EventArgs e ) {treeListView1.Items.Clear();_Tree.Clear();_ToolbarWindowHandle = GetToolbarWindowHandle();if( _ToolbarWindowHandle == IntPtr.Zero ) return;_Glomming = ( Glob.Glomming.Int != 0 );UInt32 count = User32.SendMessage( _ToolbarWindowHandle, TB.BUTTONCOUNT, 0, 0 );for( int i = 0 ; i < count ; i ){TBBUTTON tbButton = new TBBUTTON();string text = String.Empty;IntPtr ipWindowHandle = IntPtr.Zero;bool b = GetTBButton( _ToolbarWindowHandle, i, ref tbButton, ref text, ref ipWindowHandle );if( b ) AddData( tbButton, text, ipWindowHandle );}CreateImageList();FillTreeList();// User32.SendMessage( hToolbar, TB.CUSTOMIZE, IntPtr.Zero, IntPtr.Zero );}private void AddData( TBBUTTON tbButton, string text, IntPtr ipWindowHandle ){string state = ( ( tbButton.fsState & TBSTATE.HIDDEN ) == 0 ) ? "Shown": "Hidden";string handle = "0x"( ( UInt32 )ipWindowHandle ).ToString( "X8", CultureInfo.CurrentCulture );if( _Glomming ){if( ipWindowHandle == IntPtr.Zero ) // Process{DataProcess o = new DataProcess( tbButton, text, ipWindowHandle );o.Node = _Tree.AddChild( o );}else// Window{DataWindow o = new DataWindow( tbButton, text, ipWindowHandle );o.Node = _st.AddChild( o );}}else// not glomming{if( ipWindowHandle != IntPtr.Zero ){DataWindow o = new DataWindow( tbButton, text, ipWindowHandle );o.Node = _Tree.AddChild( o );}}}private void CreateImageList(){ImageList list = treeListView1.SmallImageList;ImageList.ImageCollection images = list.Images;while( images.Count > 2 ) images.RemoveAt( 2 );foreach( INode node in_Tree.AllChildren ){DataBase db = ( DataBase ) node.Data;if( db.DataType == DataType.Window ){DataWindow window = ( DataWindow ) db;UInt32 hIcon = 0;if( hIcon == 0 ) hIcon =User32.SendMessage ( window.WindowHandle, WM.GETICON, ICON.SMALL2, 0 ); if( hIcon == 0 ) hIcon = User32.GetClassLong( window.WindowHandle, GCL.HICONSM );if( hIcon == 0 ) hIcon = User32.GetClassLong( window.WindowHandle, GCL.HICON );if( hIcon == 0 ) continue;Bitmap bitmap = null;try{Int32 hIcon2 = unchecked( ( Int32 ) hIcon );bitmap = Bitmap.FromHicon( new IntPtr( hIcon2 ) ); }catch( ArgumentException ) { continue; }if( bitmap == null) continue;images.Add( bitmap );int imageIndex = images.Count - 1;window.ImageIndex = imageIndex;if( ! node.IsTop ){DataProcess process = ( DataProcess )node.Parent.Data;process.ImageIndex = imageIndex;}}}}private void FillTreeList(){if( _Glomming ){foreach( INode nodeProcess in_Tree.Nodes ){DataProcess process = ( DataProcess ) nodeProcess.Data;string text = process.ButtonText;bool bNoName = ( text.Length == 0 );if( bNoName ) text = "< no name >";TreeListViewItem itemProcess = new TreeListViewItem( text, process.ImageIndex );itemProcess.Tag = process;if( bNoName ) itemProcess.Expand();itemProcess.SubItems.Add( nodeProcess.Nodes.Count. ToString( CultureInfo.CurrentCulture ) );// itemProcess.SubItems.Add( "0x" ( ( UInt32 ) process.WindowHandle ).ToString( "X8", CultureInfo.CurrentCulture ) ); treeListView1.Items.Add( itemProcess );foreach( INode nodeWindow in nodeProcess.Nodes ) {DataWindow window = ( DataWindow ) nodeWindow.Data;TreeListViewItem itemWindow = new TreeListViewItem( window.ButtonText, window.ImageIndex );itemWindow.Tag = window;itemWindow.SubItems.Add( String.Empty );itemWindow.SubItems.Add( "0x"( ( UInt32 ) window.WindowHandle ).ToString( "X8", CultureInfo.CurrentCulture ) ); itemWindow.SubItems.Add( "0x"( ( UInt32 ) window.ProcessId ).ToString( "X8", CultureInfo.CurrentCulture ) ); itemProcess.Items.Add( itemWindow );}}}else// not glomming{foreach( INode nodeWindow in_Tree.Nodes ){DataWindow window = ( DataWindow ) nodeWindow.Data;TreeListViewItem itemWindow = newTreeListViewItem( window.ButtonText, window.ImageIndex );itemWindow.Tag = window;itemWindow.SubItems.Add( String.Empty );itemWindow.SubItems.Add( "0x"( ( UInt32 ) window.WindowHandle ).ToString( "X8", CultureInfo.CurrentCulture ) ); itemWindow.SubItems.Add( "0x"( ( UInt32 ) window.ProcessId ).ToString( "X8", CultureInfo.CurrentCulture ) ); treeListView1.Items.Add( itemWindow );}}}private void PopulateTreeFromList(){_Tree.Clear();foreach( TreeListViewItem itemParent in treeListView1.Items ) {DataBase dataParent = ( DataBase ) itemParent.Tag;INode nodeParent = dataParent.Node =_Tree.AddChild( dataParent );foreach( TreeListViewItem itemChild in itemParent.Items ) {DataBase dataChild = ( DataBase ) itemChild.Tag;INode nodeChild = dataChild.Node =nodeParent.AddChild( dataChild );}}}private unsafe bool GetTBButton( IntPtr hToolbar, int i, ref TBBUTTON tbButton, ref string text, ref IntPtr ipWindowHandle ){// One pageconst int BUFFER_SIZE = 0x1000;byte[] localBuffer = new byte[ BUFFER_SIZE ];UInt32 processId = 0;UInt32 threadId = User32.GetWindowThreadProcessId( hToolbar, out processId );IntPtr hProcess =Kernel32.OpenProcess( ProcessRights.ALL_ACCESS, false, processId );if( hProcess == IntPtr.Zero ) { Debug.Assert( false); return false; }IntPtr ipRemoteBuffer = Kernel32.VirtualAllocEx(hProcess,IntPtr.Zero,new UIntPtr( BUFFER_SIZE ),MIT,MemoryProtection.PAGE_READWRITE );if( ipRemoteBuffer == IntPtr.Zero ) { Debug.Assert( false); return false; }// TBButtonfixed( TBBUTTON* pTBButton = & tbButton ){IntPtr ipTBButton = new IntPtr( pTBButton );int b = ( int) User32.SendMessage( hToolbar, TB.GETBUTTON, ( IntPtr ) i, ipRemoteBuffer );if( b == 0 ) { Debug.Assert( false); return false; }// this is fixedInt32 dwBytesRead = 0;IntPtr ipBytesRead = new IntPtr( & dwBytesRead );bool b2 = Kernel32.ReadProcessMemory(hProcess,ipRemoteBuffer,ipTBButton,new UIntPtr( ( uint) sizeof( TBBUTTON ) ),ipBytesRead );if( ! b2 ) { Debug.Assert( false); return false; }}// button textfixed( byte* pLocalBuffer = localBuffer ){IntPtr ipLocalBuffer = new IntPtr( pLocalBuffer );int chars = ( int) User32.SendMessage( hToolbar,TB.GETBUTTONTEXTW, ( IntPtr ) tbButton.idCommand, ipRemoteBuffer );if( chars == -1 ) { Debug.Assert( false); return false; }// this is fixedInt32 dwBytesRead = 0;IntPtr ipBytesRead = new IntPtr( & dwBytesRead );bool b4 = Kernel32.ReadProcessMemory(hProcess,ipRemoteBuffer,ipLocalBuffer,new UIntPtr( BUFFER_SIZE ),ipBytesRead );if( ! b4 ) { Debug.Assert( false); return false; }text = Marshal.PtrToStringUni( ipLocalBuffer, chars );if( text == " ") text = String.Empty;}// window handlefixed( byte* pLocalBuffer = localBuffer ){IntPtr ipLocalBuffer = new IntPtr( pLocalBuffer );// this is in the remote virtual memory spaceIntPtr ipRemoteData = new IntPtr( tbButton.dwData );// this is fixedInt32 dwBytesRead = 0;IntPtr ipBytesRead = new IntPtr( & dwBytesRead );bool b4 = Kernel32.ReadProcessMemory(hProcess,ipRemoteData,ipLocalBuffer,new UIntPtr( 4 ),ipBytesRead );if( ! b4 ) { Debug.Assert( false); return false; }if( dwBytesRead != 4 ) { Debug.Assert( false); return false; }Int32 iWindowHandle = BitConverter.ToInt32( localBuffer, 0 );if( iWindowHandle == -1 ){ Debug.Assert( false); }//return false; }ipWindowHandle = new IntPtr( iWindowHandle );}Kernel32.VirtualFreeEx(hProcess,ipRemoteBuffer,UIntPtr.Zero,MemAllocationType.RELEASE );Kernel32.CloseHandle( hProcess );return true;}private void_Apply_Click( object sender, System.EventArgs e ) {using( new CWaitCursor() )foreach( int sw in new int[] { SW.HIDE, SW.SHOW } ){foreach( DataBase db in_Tree.AllChildren.Values ){if( db.DataType == DataType.Window ){DataWindow window = ( DataWindow ) db;IntPtr hWindow = window.WindowHandle;User32.ShowWindow( hWindow, sw );// if ( sw == SW.SHOW )System.Threading.Thread.Sleep( 500 );}}System.Threading.Thread.Sleep( 500 );}User32.SetForegroundWindow( Handle );}private void toolBar1_ButtonClick(object sender,System.Windows.Forms.ToolBarButtonClickEventArgs e){if( e.Button == toolBarButtonMoveFirst ) OnMoveFirst (); if( e.Button == toolBarButtonMoveUp ) OnMoveUp (); if( e.Button == toolBarButtonMoveDown ) OnMoveDown (); if( e.Button == toolBarButtonMoveLast ) OnMoveLast (); }private TreeListViewItemCollectionGetItemCollection( TreeListViewItem item ){if( item.Parent == null){if( item.TreeListView == null) throw new ArgumentException( "TreeListView not set for this item");return item.TreeListView.Items;}return item.Parent.Items;}private void OnMoveFirst(){// fubar// ListView.SelectedIndexCollection indices =treeListView1.SelectedIndices;// if ( indices.Count != 1 ) return;// int index = indices[ 0 ];SelectedTreeListViewItemCollection items =treeListView1.SelectedItems;if( items.Count != 1 ) return;TreeListViewItem item = items[ 0 ];MoveFirst( item );item.Selected = true;PopulateTreeFromList();}private void MoveFirst( TreeListViewItem item ){DataBase db = ( DataBase ) item.Tag;int index = db.Node.IndexBranch;if( index == 0 ) return;TreeListViewItemCollection items = GetItemCollection( item );TreeListViewItemCollection items2 = new TreeListViewItemCollection();items2.SortOrder = SortOrder.None;foreach( TreeListViewItem item2 in items )if( item2 != item )items2.Add( item2 );items.Clear();for( int i = 0 ; i < items2.Count ; i ){if( i == 0 ) items.Add( item );items.Add( items2[ i ] );}}private void OnMoveUp(){// fubar// ListView.SelectedIndexCollection indices =treeListView1.SelectedIndices;// if ( indices.Count != 1 ) return;// int index = indices[ 0 ];SelectedTreeListViewItemCollection items =treeListView1.SelectedItems;if( items.Count != 1 ) return;TreeListViewItem item = items[ 0 ];MoveUp( item );item.Selected = true;PopulateTreeFromList();}private void MoveUp( TreeListViewItem item ){DataBase db = ( DataBase ) item.Tag;int index = db.Node.IndexBranch;if( index == 0 ) return;TreeListViewItemCollection items = GetItemCollection( item );TreeListViewItemCollection items2 = new TreeListViewItemCollection();items2.SortOrder = SortOrder.None;foreach( TreeListViewItem item2 in items )if( item2 != item )items2.Add( item2 );items.Clear();for( int i = 0 ; i < items2.Count ; i ){if( i == index - 1 ) items.Add( item );items.Add( items2[ i ] );}}private void OnMoveDown(){// fubar// ListView.SelectedIndexCollection indices = treeListView1.SelectedIndices;// if ( indices.Count != 1 ) return;// int index = indices[ 0 ];SelectedTreeListViewItemCollection items = treeListView1.SelectedItems;if( items.Count != 1 ) return;TreeListViewItem item = items[ 0 ];MoveDown( item );item.Selected = true;PopulateTreeFromList();}private void MoveDown( TreeListViewItem item ){DataBase db = ( DataBase ) item.Tag;int index = db.Node.IndexBranch;if( db.Node.IsLast ) return;TreeListViewItemCollection items = GetItemCollection( item );TreeListViewItemCollection items2 = new TreeListViewItemCollection();items2.SortOrder = SortOrder.None;foreach( TreeListViewItem item2 in items )if( item2 != item )items2.Add( item2 );items.Clear();for( int i = 0 ; i < items2.Count ; i ){items.Add( items2[ i ] );if( i == index ) items.Add( item );}}private void OnMoveLast(){// fubar// ListView.SelectedIndexCollection indices =treeListView1.SelectedIndices;// if ( indices.Count != 1 ) return;// int index = indices[ 0 ];SelectedTreeListViewItemCollection items =treeListView1.SelectedItems;if( items.Count != 1 ) return;TreeListViewItem item = items[ 0 ];MoveLast( item );item.Selected = true;PopulateTreeFromList();}private void MoveLast( TreeListViewItem item ){DataBase db = ( DataBase ) item.Tag;int index = db.Node.IndexBranch;if( db.Node.IsLast ) return;TreeListViewItemCollection items = GetItemCollection( item );TreeListViewItemCollection items2 = new TreeListViewItemCollection();items2.SortOrder = SortOrder.None;foreach( TreeListViewItem item2 in items )if( item2 != item )items2.Add( item2 );items.Clear();for( int i = 0 ; i < items2.Count ; i ){items.Add( items2[ i ] );}items.Add( item );}private void_ExpandAll_Click(object sender, System.EventArgs e) {treeListView1.ExpandAll();}private void_CollapseAll_Click(object sender, System.EventArgs e){treeListView1.CollapseAll();}private void_ViewTree_Click(object sender, System.EventArgs e) {MessageBox.Show( _Tree.ToStringRecursive(), "_Tree");}private void treeListView1_DoubleClick( object sender, System.EventArgs e ){SelectedTreeListViewItemCollection items =treeListView1.SelectedItems;if( items.Count != 1 ) return;TreeListViewItem item = items[ 0 ];DataBase db = ( DataBase ) item.Tag;if( db.DataType != DataType.Window ) return;DataWindow window = ( DataWindow ) db;User32.SetForegroundWindow( window.WindowHandle );}private void_Repair_Click( object sender, System.EventArgs e ) {OperatingSystemVersion os = new OperatingSystemVersion(); string sOS = os.ToString();string sMem = String.Empty;MEMORYSTATUSEX m = new MEMORYSTATUSEX();if( Kernel32.GlobalMemoryStatusEx( m ) ){const int MB = 1024 * 1024;UInt64 total = m.TotalPhysical;UInt64 free = m.AvailablePhysical;UInt64 used = total - free;UInt64 freePercent = ( 100 * free ) / total;UInt64 usedPercent = ( 100 * used ) / total;sMem ="Memory\n"// ( Load : " m.MemoryLoad " % )\n" "---------------------\n""Physical\t : "( total / MB ) " MB\n""Used \t : "( used / MB ) " MB ( "usedPercent " % )\n""Free \t : "( free / MB ) " MB ( "freePercent " % )\n";}MessageBox.Show("You are running :"Environment.NewLine Environment.NewLine sOSEnvironment.NewLine Environment.NewLine sMem,"Supported OS",MessageBoxButtons.OK,rmation );}}}。
cmd窗口的句柄在Windows 操作系统中,每个打开的窗口都有一个唯一的句柄(句柄是一个用于标识和访问对象的值)。
对于命令提示符(CMD)窗口,你可以使用一些编程语言或工具来获取它的句柄,从而可以对该窗口进行操作。
以下是一些获取CMD 窗口句柄的方法:1. 使用编程语言如Python、C++、C#:通过调用系统API来获取窗口句柄。
例如,对于Python,你可以使用`win32gui` 模块来获取窗口句柄。
以下是一个简单的Python 示例:```pythonimport win32guicmd_handle = win32gui.FindWindow(None, "命令提示符")print("CMD 窗口句柄:", cmd_handle)```2. 使用命令行工具如AutoIt:AutoIt 是一种用于自动化Windows 界面的脚本语言,你可以使用它来获取窗口句柄。
以下是一个示例脚本:```Local $hWnd = WinGetHandle("命令提示符")MsgBox(0, "CMD 窗口句柄", $hWnd)```3. 使用Windows 内置工具如PowerShell:你可以使用PowerShell 脚本来获取CMD 窗口句柄。
以下是一个示例:```powershell$cmdHandle = (Get-WmiObject Win32_Process -Filter "Name='cmd.exe'").HandleWrite-Host "CMD 窗口句柄: $cmdHandle"```请注意,上述方法中的"命令提示符" 可能需要根据你实际的窗口标题进行调整。
获取到的窗口句柄可以用于执行诸如发送消息、最小化、最大化、关闭等操作。
但请确保在使用句柄进行操作时,不要造成系统异常或损坏。
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){}。