不知道程序的窗口句柄时结束该程序的进程

3/8/2008来源:C/C++教程人气:5507


  假如只要判定EXE的名字(不需要判定路径),可以省略EnumPRocess,因为
pe32.szExeFile 里就已经有EXE的名字了,因为没有路径,所以才又使用了
函数EnumProcess来取得完整的路径。这样就简洁一些了。
BOOL CALLBACK EnumWinProc(HWND hwnd, LPARAM lParam)
{
    DWord dwID;

    GetWindowThreadProcessId(hwnd, &dwID);
    if (dwID == (DWORD)lParam) {
        PostMessage(hwnd, WM_QU99v, 0, 0);
        return FALSE;
    }
    return TRUE;
}

void KillProgram(LPCSTR ExeName)
{
    char *File;
    HANDLE hProcessSnap;
    PROCESSENTRY32 pe32;

    if (!ExeName !ExeName[0])
        return;
    File = strrchr(ExeName, '\\');
    if (File!=0) ExeName = File+1;
    hProcessSnap = CreateToolhelp32Snapshot(
        TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == (HANDLE)-1) return;

    memset(&pe32, 0, sizeof(pe32));
    pe32.dwSize = sizeof(PROCESSENTRY32);
    if (Process32First(hProcessSnap, &pe32))
    {
        do {
            memset(&me32, 0, sizeof(me32));
            me32.dwSize = sizeof(me32);
            File = strrchr(pe32.szExeFile, '\\');
            File = File? File+1 : pe32.szExeFile;
            if (strcmpi(File,ExeName)==0) {
                EnumWindows((WNDENUMPROC)EnumWinProc,
                   pe32.th32ProcessID);
            }
        }
        while(Process32Next(hProcessSnap,&pe32));
    }
    CloseHandle(hProcessSnap);
}