思路:创建进程的时候,通过enumwindos获得句柄,movewindow到自己窗口中。
在codeproject的基础和csdn的基础上进行了修改
static HANDLE g_hEvent=NULL; //event handle
static HANDLE handle;//process handle
static HWND apphwnd;//window handle
/*************Global functions for hosting******************/
//Function to enumerate all windows.
int CALLBACK EnumWindowsProc(HWND hwnd, LPARAM param)
{
DWORD pID;
DWORD TpID = GetWindowThreadProcessId(hwnd, &pID);//get process id
if (TpID == (DWORD)param)
{
apphwnd=hwnd;//hwnd is the window handle
SetEvent(g_hEvent);
return false;
}
ResetEvent(g_hEvent);
return true;
}
//Functio to start a orocess and return the process handle
HANDLE StartProcess(LPCTSTR program, LPCTSTR args)
{
HANDLE hProcess = NULL;
PROCESS_INFORMATION processInfo;
STARTUPINFO startupInfo;
::ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags=STARTF_USESHOWWINDOW;
startupInfo.wShowWindow=SW_HIDE;
if(::CreateProcess(program, (LPTSTR)args,
NULL, // process security
NULL, // thread security
FALSE, // no inheritance
0, // no startup flags
NULL, // no special environment
NULL, // default startup directory
&startupInfo,
&processInfo))
{ /* success */
WaitForInputIdle(processInfo.hProcess,-1);
::EnumWindows(&EnumWindowsProc, processInfo.dwThreadId);//Iterate all windows
hProcess = processInfo.hProcess;
} /* success */
return hProcess;
}
/**********************************************************/
//handle for host menu
void CHostMSPaintDlg::OnActionHostmspaint()
{
CRect rect;
DWORD nRet=-1;
g_hEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
GetClientRect(&rect);//get our dialog size into rect
handle=StartProcess(NULL,"C:\\Program Files\\Microsoft Office\\Office12\\WINWORD.EXE d:\1.doc");//Start ms paint
nRet=WaitForSingleObject(g_hEvent,5000); //waited the target window for 2000 ms
CloseHandle(g_hEvent);
if(nRet!=WAIT_OBJECT_0)
{
::MessageBox(NULL,_T("启动word,超时!"),_T("错误提示"),MB_ICONEXCLAMATION);
SendMessage(WM_CLOSE,0,0);
return;
}
if(apphwnd!=NULL)//check for window handle
{
::SetParent(apphwnd,m_hWnd);//set parent of ms paint to our dialog.
SetWindowLong(apphwnd, GWL_STYLE, WS_VISIBLE);//eraze title of ms paint window.
//Positioning ms paint.
::MoveWindow(apphwnd, rect.left, rect.top,rect.right, rect.bottom, true);
::ShowWindow(apphwnd,SW_SHOW);
}
else//no window for our process
MessageBox("Cannot find Window");
}
//handle for kill process menu.
void CHostMSPaintDlg::OnActionKillprocess()
{
TerminateProcess(handle,0); //kill the process using handle
}