天天看點

windows程式設計,根據程序名删除系統程序

main函數版本:

#include <windows.h>
#include "tlhelp32.h"
#include <iostream>
using namespace std;

DWORD GetProcessIDByName(const wchar_t* pName)
{
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (INVALID_HANDLE_VALUE == hSnapshot) {
        return NULL;
    }
    PROCESSENTRY32 pe = { sizeof(pe) };
    for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe))
    {
        if (wcscmp(pe.szExeFile, pName) == 0)
        {
            CloseHandle(hSnapshot);
            return pe.th32ProcessID;
        }
    }
    CloseHandle(hSnapshot);
    return 0;
}

BOOL KillProcess(DWORD ProcessId)
{
    HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, ProcessId);
    if (hProcess == NULL)
        return FALSE;
    if (!TerminateProcess(hProcess, 0))
        return FALSE;
    return TRUE;
}

int main() {
    const wchar_t* s = L"cmd.exe";
    // wprintf(L"程序名稱:%s\n", s);
    wcout << "程序名稱: " << s << endl;
    DWORD pid = GetProcessIDByName(s);
    // wprintf(L"程序号:%d\n",pid);
    if (0 == pid)
    {
        cout << "沒找到程序" << endl;
    }
    else
    {
        cout << "程序号:" << pid << endl;
        if (KillProcess(pid)) {
            cout << "程序已被成功删除" << endl;
        }
        else
        {
            cout << "删除失敗..." << endl;
        }

    }
    
    system("pause");
    return 0;
}
           

mfc版本:

見上傳資源

繼續閱讀