VC:如何根据文件名来获取程序进程和窗口句柄的代码 (原创)
根据系统进程中的模块名和运行文件名称的匹配来查找程序进程的代码如下(因为窗口类和窗口名都在变化,所以只能如此了)。- //做系统进程快照
- Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- //找第一个进程
- f = Process32First(Snapshot, &processListStr);
- while(f)
- {
- char *t1="3SMeeting.exe"; //这是运行文件名
- if (*processListStr.szExeFile ==*t1){
- sprintf( szHello, "ProcessID:%X EXE:%s",processListStr.th32ProcessID,processListStr.szExeFile);
- TextOut(hdc, rt.left, rt.top, szHello,strlen(szHello));
- break;
- }
- f = Process32Next(Snapshot, &processListStr); //继续查找
- }
- CloseHandle(Snapshot);
复制代码 在VC中获取其它窗口句柄的方法很多,但用FindWindow等要根据窗口类和窗口标题来查找得到窗口句柄,正好碰到窗口类和窗口标题都是不断变化的,下面的代码是我经过实践得到的。
根据窗口名的一部分来获取窗口的句柄,代码如下:- int i;
- //以桌面为父窗口来查找第一个主窗口
- hWndPrevious = GetWindow(GetDesktopWindow(),GW_CHILD);
- LPTSTR m_pszExeName;
- while (IsWindow(hWndPrevious))
- {
- int i=GetWindowTextLength(hWndPrevious);
- GetWindowText(hWndPrevious,szHello,i);//获取窗口标题
- //这里我的窗口中只有下面几个字是不变的
- if (strstr(szHello,"当前用户数:")){
- sprintf( szHello1, "Hwnd:%X Title:%s",hWndPrevious,szHello);
- TextOut(hdc, rt.left, rt.top, szHello1,strlen(szHello1));
- break;
- //匹配,这时hWndPrevious就是所要找的窗口的句柄
- }
- hWndPrevious = GetWindow(hWndPrevious,GW_HWNDNEXT);
- }
复制代码 欢迎指正。 |