Posted on 2007-12-26 17:34
江边之鸟 阅读(7328)
评论(2) 编辑 收藏 引用 所属分类:
c++
在VC程序中如何结束系统正在运行的其他进程(该进程必须有窗口界面),其实很简单,按如下步骤进行即可:
1.取得进程的句柄(利用FindWindow函数得到);
2.获取进程ID号(用GetWindowThreadProcessId函数获取);
3.打开进程,OpenProcess函数中的第一个参数设为PROCESS_TERMINATE,就可以获取处理该进程的句柄;
4.利用TerminateProcess函数结束进程,将该函数的第二个参数设为4。
代码如下:
//结束进程
int CStaticFunc::KillProcess(LPCSTR pszClassName, LPCSTR
pszWindowTitle)
{
HANDLE hProcessHandle;
ULONG nProcessID;
HWND TheWindow;
TheWindow = ::FindWindow( NULL, pszWindowTitle );
::GetWindowThreadProcessId( TheWindow, &nProcessID );
hProcessHandle = ::OpenProcess( PROCESS_TERMINATE, FALSE,
nProcessID );
return ::TerminateProcess( hProcessHandle, 4 );
}
而启动进程则只需要CreateProcess函数就可完成,需要注意的是这个函数的几个输入参数,第一个参数是
//启动新进程
int CStaticFunc::CreateNewProcess(LPCSTR pszExeName)
{
PROCESS_INFORMATION piProcInfoGPS;
STARTUPINFO siStartupInfo;
SECURITY_ATTRIBUTES saProcess, saThread;
ZeroMemory( &siStartupInfo, sizeof(siStartupInfo) );
siStartupInfo.cb = sizeof(siStartupInfo);
saProcess.nLength = sizeof(saProcess);
saProcess.lpSecurityDescriptor = NULL;
saProcess.bInheritHandle = true;
saThread.nLength = sizeof(saThread);
saThread.lpSecurityDescriptor = NULL;
saThread.bInheritHandle = true;
return ::CreateProcess( NULL, (LPTSTR)pszExeName, &saProcess,
&saThread, false,
CREATE_DEFAULT_ERROR_MODE, NULL, NULL,
&siStartupInfo, &piProcInfoGPS );
}