//skin.exe只運行一個實例
//根據窗體標題判斷程序是否已經啓動
BOOL CSkinApp::InitInstance()
{
//根據窗體標題來判斷應用程序是否在運行
HWND hWnd;
//我的應用程序的標題skinTest
hWnd = ::FindWindow(NULL,"skinTest");
if(hWnd != NULL)
{
AfxMessageBox("已經運行");
return FALSE;
}
CSkinDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{ //*******
}
//=============================================================
#include <afx.h>
#include<direct.h>
#include<stdlib.h>
#include "Shlwapi.h"
#include <Tlhelp32.h>
#pragma comment(lib,"shlwapi.lib")
//skin.exe進程來啓動a.exe進程
//a.exe進程只啓動一次,如果該進程已經運行則不再啓動
//啓動a.exe程序
void CSkinDlg::OnButton1()
{
//獲取a.exe所在的目錄
CString strCurDir=GetModuleDir();
//獲取a.exe的絕對路徑
CString strSwp =strCurDir+"//a.exe";
//如果已經啓動a.exe,則不重新啓動
//參數傳遞進程名
if (GetProcessIdFromName("a.exe"))
{
AfxMessageBox("a.exe已啓動");
}
else
{
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset(&si,0,sizeof(si));
si.cb=sizeof(si);
si.wShowWindow=SW_SHOW;
si.dwFlags=STARTF_USESHOWWINDOW;
bool fRet=CreateProcess(strSwp,NULL,NULL,FALSE,NULL,NULL,NULL,strCurDir,&si,&pi);
}
}
//獲取當前目錄
CString CSkinDlg::GetModuleDir()
{
CString sPath;
GetModuleFileName(NULL,sPath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer();
int nPos=0;
nPos=sPath.ReverseFind('//');
sPath=sPath.Left (nPos);
CString file;
file.Format("%s",sPath);
return file;
}
//判斷進程是否運行
DWORD GetProcessIdFromName(LPCTSTR strname)
{
PROCESSENTRY32 pe;
DWORD id = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
pe.dwSize = sizeof(PROCESSENTRY32);
if( !Process32First(hSnapshot,&pe))
return 0;
while(1)
{
pe.dwSize = sizeof(PROCESSENTRY32);
if( Process32Next(hSnapshot,&pe)==FALSE)
break;
if(strcmp(pe.szExeFile,strname) == 0)
{
id = pe.th32ProcessID;
break;
}
}
CloseHandle(hSnapshot);
return id;
}
//=============================================================