相关文章推荐

Hi a4825a,

你可以尝试C#和C++两种方法去强制结束进程。以下先介绍CSharp的强制结束进程办法,值得强调的是参数有效性检测和名字比较,由于系统中可能运行很多意想不到的进程,所以在比较名字的时候一定要用等于而不是包含或者之比较开头和结尾,否则很可能杀错进程,即要用Equals来得到进程名字。

//Return true for successful and false for failed
public bool FindAndKillProcessByName(string name) 
            //Parameter check 
            if (0 == name.Length) 
                return false; 
            //Find the named process and terminate it 
            foreach (Process winProc in Process.GetProcesses()) 
                //use equals for the task in case we kill 
                //a wrong process 
                if (winProc.ProcessName.Equals(name)) 
                    winProc.Kill(); 
                    return true; 
            return false; 

   接着是C++的办法是如何通过快照来强制结束进程,完成这个工作的函数是CreateToolhelp32Snapshot(),在头文件#include<tlhelp32.h>中,你可以使用PInvoke的方法调用这些函数遍历出这些进程然后强制结束进程。

BOOL FindAndKillProcessByName(LPCTSTR strProcessName) 
        if(NULL == strProcessName) 
                return FALSE; 
        HANDLE handle32Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 
        if (INVALID_HANDLE_VALUE == handle32Snapshot) 
                        return FALSE; 
        PROCESSENTRY32 pEntry;        
        pEntry.dwSize = sizeof( PROCESSENTRY32 ); 
        //Search for all the process and terminate it 
        if(Process32First(handle32Snapshot, &pEntry)) 
                BOOL bFound = FALSE; 
                if (!_tcsicmp(pEntry.szExeFile, strProcessName)) 
                        bFound = TRUE; 
                while((!bFound)&&Process32Next(handle32Snapshot, &pEntry)) 
                        if (!_tcsicmp(pEntry.szExeFile, strProcessName)) 
                                bFound = TRUE; 
                if(bFound) 
                        CloseHandle(handle32Snapshot); 
                        HANDLE handLe =  OpenProcess(PROCESS_TERMINATE , FALSE, pEntry.th32ProcessID); 
                        BOOL bResult = TerminateProcess(handLe,0); 
                        return bResult; 
        CloseHandle(handle32Snapshot); 
        return FALSE; 
 
推荐文章