1. 程式人生 > >windows 下在一個程序中使用createprocess建立一個視窗程序,並獲取這個視窗的HWND控制代碼

windows 下在一個程序中使用createprocess建立一個視窗程序,並獲取這個視窗的HWND控制代碼

// Process.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <windows.h> 
#include <iostream>


DWORD g_dwProcessId = 0;
HWND g_hWnd = NULL;
BOOL   CALLBACK  EnumWindowsProcGetWndTitle(HWND hWnd,LPARAM lParam);
bool CloseProcess(DWORD pid);
DWORD InitCreateProcess(TCHAR* cmdline);
DWORD InitCreateProcess(TCHAR* cmdline)
{


TCHAR chPath[301];
int nNumberDely = 1000;
::GetCurrentDirectory(300,(LPTSTR)chPath);//得到當前目錄
wcscat(chPath,cmdline);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &pi, sizeof(pi) );
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
if(CreateProcess(chPath,L"", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
else 
{
MessageBox(NULL,L"建立失敗!",L"ERROR!",MB_OK);
HANDLE hProcess = GetCurrentProcess();//get current process
TerminateProcess(hProcess,0);         //close process
}
g_dwProcessId = pi.dwProcessId;
// 等待視窗動行起,獲取到視窗HWND
while(EnumWindows(EnumWindowsProcGetWndTitle,g_dwProcessId) && nNumberDely>0 )
{
nNumberDely--;
}
return pi.dwProcessId;
}


bool CloseProcess(DWORD pid)
{
bool result=false;
HANDLE hprocess=OpenProcess(PROCESS_TERMINATE,false,pid);
result=TerminateProcess(hprocess,0);
CloseHandle(hprocess);
return result;
}
BOOL   CALLBACK  EnumWindowsProcGetWndTitle(HWND hWnd,LPARAM lParam)
{
DWORD ProcID = 0;
GetWindowThreadProcessId(hWnd,&ProcID);
if(ProcID==lParam)//如果視窗的processid等於你的ID
{
HWND pWnd = GetParent(hWnd);
while(GetParent(pWnd)!=NULL)//得到父視窗的控制代碼
{
pWnd = GetParent(pWnd);
g_hWnd = pWnd;
return FALSE;
}
//ok  pWnd 就是主視窗了。
}
return TRUE;
}
int _tmain(int argc, _TCHAR* argv[])
{


TCHAR path[200]= L"\\softkeyboard\\SoftBoard.exe";


// 開啟程序
InitCreateProcess(path);


RECT rt;
GetWindowRect(g_hWnd,&rt);


TCHAR szPathName[100] = {0};
GetWindowText(g_hWnd,szPathName,sizeof(szPathName));


// 隱藏視窗
ShowWindow(g_hWnd,SW_HIDE);
// 顯示視窗
ShowWindow(g_hWnd,SW_SHOW);
// 將視窗移動到0,0位置,大小改變為0,0,達到隱藏效果
MoveWindow(g_hWnd, 0, 0,0,0, TRUE); 
// 將視窗移動到0,0位置,視窗大小不變
MoveWindow(g_hWnd, 0, 0,rt.right-rt.left, rt.bottom-rt.top, TRUE);


CloseProcess(g_dwProcessId);
return 0;
}