怎么在子进程获取父进程的窗口句柄
如题
请教各位
用 CreateProcess或ShellExecute 打开的程序如何获得打开他的窗口的句柄(我需要向父窗口发送消息)
当然先排除findwindow、或通过命令行参数传递,有其他方法吗?
------解决方案--------------------
CreateToolhelp32Snapshot中使用PROCESSENTRY32 得到WORD th32ParentProcessID,然后再用EnumWindows,在里面调用GetWindowThreadProcessId对比上面找到的ID,得到父进程窗口
------解决方案--------------------
你CreateProcess直接将HWND作为命令行参数、或者环境变量参数传递给子进程,在子进程中解析一下即可。
用环境变量的方法与下面类似GetEnvironmentStrings();具体使用参考MSDN文档
- C/C++ code
// 父进程创建子进程,将自己的HWND窗口句柄作为参数传递到子进程中。 STARTUPINFO si = {sizeof(si)}; PROCESS_INFORMATION pi = {0}; TCHAR szAppPath[MAX_PATH] = {0}; _stprintf(szAppPath, _T("%s 0x%x"), _T("F:\\11.exe"), GetSafeHwnd()); if(CreateProcess(NULL, szAppPath, NULL, NULL, FALSE, NULL, NULL, NULL, &si ,&pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } else { DWORD dwRet = GetLastError(); CString str; str.Format(_T("%d"), dwRet); AfxMessageBox(str); } // 子进程中解析命令行即可 LPWSTR *szArglist = NULL; int nArgs = 0; int i = 0; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if( NULL == szArglist ) { return FALSE; } else { if(nArgs >= 2) { HWND hWnd = (HWND)_tcstoul(CString(szArglist[1]), NULL, 16); TCHAR buf[MAX_PATH] = {0}; GetWindowText(hWnd, buf, MAX_PATH-1); AfxMessageBox(buf); } }