c – 如何获取进程的主线程ID(以其ID名称)?

前端之家收集整理的这篇文章主要介绍了c – 如何获取进程的主线程ID(以其ID名称)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
你能帮我找到ID过程给定的主(唯一)线程ID吗?

任务上下文:
正在运行的进程(目前)没有窗口而是(某些)线程.

通缉:
仅在主线程上发布WM_QUIT.

未想:
使用TerminateProcess或在非主线程上发布WM_QUIT.

解决方法

#ifndef MAKEULONGLONG
#define MAKEULONGLONG(ldw,hdw) ((ULONGLONG(hdw) << 32) | ((ldw) & 0xFFFFFFFF))
#endif

#ifndef MAXULONGLONG
#define MAXULONGLONG ((ULONGLONG)~((ULONGLONG)0))
#endif

bool CloseProcessMainThread(DWORD dwProcID)
{
  DWORD dwMainThreadID = 0;
  ULONGLONG ullMinCreateTime = MAXULONGLONG;

  HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,0);
  if (hThreadSnap != INVALID_HANDLE_VALUE) {
    THREADENTRY32 th32;
    th32.dwSize = sizeof(THREADENTRY32);
    BOOL bOK = TRUE;
    for (bOK = Thread32First(hThreadSnap,&th32); bOK;
         bOK = Thread32Next(hThreadSnap,&th32)) {
      if (th32.th32OwnerProcessID == dwProcID) {
        HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION,TRUE,th32.th32ThreadID);
        if (hThread) {
          FILETIME afTimes[4] = {0};
          if (GetThreadTimes(hThread,&afTimes[0],&afTimes[1],&afTimes[2],&afTimes[3])) {
            ULONGLONG ullTest = MAKEULONGLONG(afTimes[0].dwLowDateTime,afTimes[0].dwHighDateTime);
            if (ullTest && ullTest < ullMinCreateTime) {
              ullMinCreateTime = ullTest;
              dwMainThreadID = th32.th32ThreadID; // let it be main... :)
            }
          }
          CloseHandle(hThread);
        }
      }
    }
#ifndef UNDER_CE
    CloseHandle(hThreadSnap);
#else
    CloseToolhelp32Snapshot(hThreadSnap);
#endif
  }

  if (dwMainThreadID) {
    PostThreadMessage(dwMainThreadID,WM_QUIT,0); // close your eyes...
  }

  return (0 != dwMainThreadID);
}

猜你在找的C&C++相关文章