配置MSI文件以在安装时启动和终止程序

时间:2017-07-06 16:01:13

标签: c# visual-studio-2010 windows-installer

我有一个我在Visual Studio 2010中开发的应用程序,需要配置安装程序(作为.msi文件)来启动程序然后终止任务。我在msi中有一个自定义动作来启动程序,但是我在添加一个步骤来杀死任务时遇到了麻烦。任何建议都会很棒。谢谢!

1 个答案:

答案 0 :(得分:0)

您需要创建自定义操作才能处理此问题。 Windows Installer没有kill process事件。下面是我为处理此问题而创建的本机C ++应用程序。

// KillProc.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"

#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <algorithm>
#include <string> 

BOOL KillProcess(_TCHAR* szProcessToKill);
TCHAR* AcTcharlower(TCHAR *pString);

int _tmain(int argc, _TCHAR* argv[])
{

    if(argc > 1){
        KillProcess(argv[1]);
    }else{
        // No Process found
    }
    return 0;
}

BOOL KillProcess(_TCHAR* szProcessToKill){
    HANDLE hProcessSnap;
    HANDLE hProcess;
    PROCESSENTRY32 processEntry32;
    LPWSTR lpszBuffer = new TCHAR[MAX_PATH];
    LPWSTR lpszProcessToKill = new TCHAR[MAX_PATH];
    lpszProcessToKill = AcTcharlower(szProcessToKill);
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);  // Takes a snapshot of all the processes
    if(hProcessSnap == INVALID_HANDLE_VALUE){
        return( FALSE );
    }

    processEntry32.dwSize = sizeof(PROCESSENTRY32);
    if(!Process32First(hProcessSnap, &processEntry32))
    {
        CloseHandle(hProcessSnap);     
        return( FALSE );
    }

    do
    {
        lpszBuffer = processEntry32.szExeFile;
        if(!wcsicmp(lpszBuffer,szProcessToKill)){    // Is this our Process
            hProcess = OpenProcess(PROCESS_TERMINATE,0, processEntry32.th32ProcessID);  // It is so get the process handle
            TerminateProcess(hProcess,0);
            CloseHandle(hProcess); 
        } 
    }while(Process32Next(hProcessSnap,&processEntry32));  // gets next member of snapshot

    CloseHandle(hProcessSnap);  // closes the snapshot handle
    return( TRUE );
}

TCHAR* AcTcharlower(TCHAR *pString)
{
    static TCHAR pBuffer[MAX_PATH];
    TCHAR *s = pString;
    TCHAR *t = pBuffer;
    while (*s != '\0')
    {
        *t = tolower(*s);
        s++;
        t++;
    }
    return(pBuffer);
}