如何杀死进程的名字? (Win32 API的) [英] How to kill processes by name? (Win32 API)

查看:691
本文介绍了如何杀死进程的名字? (Win32 API的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有这将启动一次以上的程序。所以,会有启动程序的两个或多个过程

Basically, I have a program which will be launched more than once. So, there will be two or more processes launched of the program.

我想使用Win32 API和杀死/终止所有的进程具有特定名称。

I want to use the Win32 API and kill/terminate all the processes with a specific name.

我已经看到了完全相同的名称(但不同参数)的终止进程的例子,但不是多个进程。

I have seen examples of killing A process, but not multiple processes with the exact same name(but different parameters).

推荐答案

尝试下面code, killProcessByName()将杀死同名称的任何程序文件名

Try below code, killProcessByName() will kill any process with name filename :

#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
void killProcessByName(const char *filename)
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while (hRes)
    {
        if (strcmp(pEntry.szExeFile, filename) == 0)
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                                          (DWORD) pEntry.th32ProcessID);
            if (hProcess != NULL)
            {
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}
int main()
{
    killProcessByName("notepad++.exe");
    return 0;
}

注:code是大小写敏感的,以文件名,您可以编辑它不区分大小写

Note: The code is case sensitive to filename, you can edit it for case insensitive.

这篇关于如何杀死进程的名字? (Win32 API的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆