Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate

Demonstration: SuspendThread

  • Please log in to reply
1 reply to this topic
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006
While searching for something else, I came across a few requests (in Wish List and Ask for Help) for suspending a process or thread. The following demonstrates how to pause and resume the thread associated with a window. (Written out of curiosity and boredom.)

;hwnd := WinExist("Untitled")  ; test with Notepad

Run, Notepad,,, pid
WinWait, ahk_pid %pid%
hwnd := WinExist()

if (!hwnd) {
    MsgBox, Test window not found.

WinGetTitle, title

; The GetWindowThreadProcessId function retrieves the identifier of the thread that
; created the specified window and, optionally, the identifier of the process that
; created the window. 

thread_id := DllCall("GetWindowThreadProcessId"
    , "uint", hwnd
    , "uint*", process_id)

; To get just the thread ID:
;  thread_id := DllCall("GetWindowThreadProcessId", "uint", hwnd, "uint", 0)

; Get a handle to the thread.
thread_handle := DllCall("OpenThread"
    , "uint", 0x2  ; request THREAD_SUSPEND_RESUME access right
    , "int", 0
    , "uint", thread_id)

if (!thread_handle) {
    MsgBox, Error opening thread to suspend.`nErrorLevel: %ErrorLevel%`nLast Win32 Error: %A_LastError%

; MSDN: Suspends the specified thread.
;    The handle must have the THREAD_SUSPEND_RESUME access right.
suspend_count := DllCall("SuspendThread", "uint", thread_handle)

if (!ErrorLevel and suspend_count != -1)
    MsgBox, Paused thread of Window "%title%". Click OK to unpause.
    DllCall("ResumeThread", "uint", thread_handle)

DllCall("CloseHandle", "uint", thread_handle)

if suspend_count = -1
    MsgBox, Failed to suspend thread of Window "%title%".
(The script should successfully freeze Notepad until you click OK.)

Relevant threads:
Suspend and Resume threads/processes
Process - Suspend and Resume
How to pause an external process?
Can you make another program sleep?

  • Members
  • 2462 posts
  • Last active: Feb 07 2012 04:00 AM
  • Joined: 12 Feb 2007
I guess Notepad is single-threaded.
SuspendThread is quite straight-forward. The non-trivial one is how to chain them to suspend a process, especially for the multi-threaded process, as there is no documented API like SuspendProcess (:there exists an undocumented one, however).
<!-- m -->http://www.autohotke...topic17466.html<!-- m -->