方法一:
void CXXXDlg::RestartSoftWare()
{
::PostMessage(AfxGetMainWnd()->m_hWnd, WM_SYSCOMMAND, SC_CLOSE, NULL);
//获取exe程序当前路径
extern CXXXApp theApp;
TCHAR szAppName[MAX_PATH];
::GetModuleFileName(theApp.m_hInstance, szAppName, MAX_PATH);
CString strAppFullName;
strAppFullName.Format(_T("%s"), szAppName);
//重启程序
STARTUPINFO StartInfo;
PROCESS_INFORMATION procStruct;
memset(&StartInfo, 0, sizeof(STARTUPINFO));
StartInfo.cb = sizeof(STARTUPINFO);
::CreateProcess(
(LPCTSTR)strAppFullName,
NULL,
NULL,
NULL,
FALSE,
NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&StartInfo,
&procStruct);
}
方法二:
//启动
ShellExecute(NULL,"open","Path","","",SW_SHOW);
//关闭进程
UINT iProID=GetProcessIdByName(_T(".exe"));
HWND hWnd=ProcIDToMainHWND(iProID);
if(hWnd){
::SendMessage(hWnd,WM_CLOSE,0,0);
}
#include "tlhelp32.h"
// 根据进程反找主窗口句柄
// 2007.9.16
HWND ProcIDToMainHWND(DWORD a_hProcID)
{
int iCount=0;
HWND hWnd=::FindWindow(NULL,NULL);
DWORD hProcId;
while(hWnd!=0)
{
if(::GetParent(hWnd)==0)
{
//_MyGetWindowText(hWnd,chr,255);
GetWindowThreadProcessId(hWnd, &hProcId);
if(hProcId==a_hProcID){
return hWnd;
}
}
hWnd=::GetWindow(hWnd,GW_HWNDNEXT);
}
return 0;
}
/////////////////////
UINT GetProcessIdByName(LPCTSTR pszExeFile)
{
UINT nProcessID = 0;
PROCESSENTRY32 pe = {sizeof(PROCESSENTRY32)};
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
if (Process32First(hSnapshot, &pe))
{
while (Process32Next(hSnapshot, &pe))
{
if (lstrcmpi(pszExeFile, pe.szExeFile) == 0)
{
nProcessID = pe.th32ProcessID;
break;
}
}
}
CloseHandle(hSnapshot);
}
return nProcessID;
}