进程只被实例化一次(VC)

//=============================================================
//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;
}
//=============================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值