; 获取所有线程&中断线程示例  测试:Win10 AHKV1
Run "Notepad.exe",,, pid ;; 打开进程
WinWait, % "ahk_pid " pid
Sleep 1000
MsgBox % threadId := GetProcessThread(pid)[1] ;; 取进程的第一个线程

; threadId := GetProcessThread(pid)
; For k,v in threadId   ; 遍历该进程的所有线程
;    MsgBox % "次数:" k "`n线程编号:" v
   
MsgBox % TerminateThread(threadId) ;; 中断线程, 成功返回1

; 返回包含指定进程的所有线程id的数组
GetProcessThread(pid) {
  VarSetCapacity(threadEntry, threadEntrySize := 4 * 7), NumPut(threadEntrySize, threadEntry, 0, "uint")	;; initial
  if (-1 != threadSnapShot := DllCall("CreateToolhelp32Snapshot", "uint", 0x4, "uint", 0, "ptr")) {
    if (DllCall("Thread32First", "ptr", threadSnapShot, "ptr", &threadEntry, "int")) {
      arr := Array()
      loop {
        if (pid = NumGet(threadEntry, 12, "uint"))
          arr.Push(NumGet(threadEntry, 8, "uint"))
      } until !DllCall("Thread32Next", "ptr", threadSnapShot, "ptr", &threadEntry, "int")
    }
  }
  DllCall("CloseHandle", "ptr", threadSnapShot)
  return arr
}

; 中断指定线程, 请谨慎使用
TerminateThread(threadId) {
  if (threadId := DllCall("OpenThread", "uint", 0x1f03ff, "int", 0, "uint", threadId, "ptr"))
    if (DllCall("GetExitCodeThread", "ptr", threadId, "uint*", &exitCode := 0))
      return DllCall("TerminateThread", "ptr", threadId, "uint", exitCode)
}

; 返回指定线程的入口地址
GetThreadAddress(threadId) {
  if (threadHandle := DllCall("OpenThread", "uint", 0x0040, "int", 0, "uint", threadId, "ptr"))
    return !DllCall("ntdll\NtQueryInformationThread", "ptr", threadHandle, "uint", 0x09, "ptr*", &Address := 0, "uint", A_PtrSize, "uint*", 0) ? Format("{:#X}", Address) : 0
}

 

声明:站内资源为整理优化好的代码上传分享与学习研究,如果是开源代码基本都会标明出处,方便大家扩展学习路径。请不要恶意搬运,破坏站长辛苦整理维护的劳动成果。本站为爱好者分享站点,所有内容不作为商业行为。如若本站上传内容侵犯了原著者的合法权益,请联系我们进行删除下架。