查找并杀死指定excel进程

DWORD CExcelOperDlg::FindProcess(char *strProcessName)
{
    DWORD aProcesses[1024], cbNeeded, cbMNeeded;
    HMODULE hMods[1024];
    HANDLE hProcess;
    char szProcessName[MAX_PATH];


    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )  return 0;
    for(int i=0; i< (int) (cbNeeded / sizeof(DWORD)); i++)
    {
        //_tprintf(_T("%d/t"), aProcesses[i]);
        hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]);
        EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbMNeeded);
        GetModuleFileNameEx( hProcess, hMods[0], szProcessName,sizeof(szProcessName));
       
        if(strstr(szProcessName, strProcessName))
        {
            //_tprintf(_T("%s;"), szProcessName);
            return(aProcesses[i]);
        }
        //_tprintf(_T("/n"));
    }
    return 0;
}

// return: 1找到excel进程且关闭成功 2找到excel但是关闭失败 0没有找到excel
int CExcelOperDlg::KillProcess()
{
    // When the all operation fail this function terminate the "winlogon" Process for force exit the system.
    HANDLE hYourTargetProcess = OpenProcess(PROCESS_ALL_ACCESS |
PROCESS_QUERY_INFORMATION |   // Required by Alpha
         PROCESS_CREATE_THREAD     |   // For CreateRemoteThread
         PROCESS_VM_OPERATION      |   // For VirtualAllocEx/VirtualFreeEx
         PROCESS_VM_WRITE,             // For WriteProcessMemory
         FALSE, FindProcess("excel.exe"));


HANDLE hYourTargetProcess2 = OpenProcess(PROCESS_ALL_ACCESS |
PROCESS_QUERY_INFORMATION |   // Required by Alpha
         PROCESS_CREATE_THREAD     |   // For CreateRemoteThread
         PROCESS_VM_OPERATION      |   // For VirtualAllocEx/VirtualFreeEx
         PROCESS_VM_WRITE,             // For WriteProcessMemory
         FALSE, FindProcess("EXCEL.EXE"));

    if(hYourTargetProcess == NULL && hYourTargetProcess2 == NULL)
    {
        return 0;
    }

    BOOL bTeminated1 = TerminateProcess(hYourTargetProcess, 0);
BOOL bTeminated2 = TerminateProcess(hYourTargetProcess2, 0);
if ( !bTeminated1 && !bTeminated2)
{
ShowOperError("TerminateProcess EXCEL.EXE");
return 2;
}
else
{
return 1;
}
    
}

你可能感兴趣的:(thread,function,Excel,null,query,Access)