0
votes

I have a script that I use to close a program by giving it its full exe path like "c:\run\myprogram.exe", and I want it to close it gracefully. I have been successful doing it forcefully using Process, Close, %hWnd% or WinClose, ahk_id %iId% but what I have been searching for is a method that would close a given program by its full path and then close it gracefully without force-closing it.

So far, I have this script:

closeByExactPathToEXE(path) {
 for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process") {
 	If (ePath  := process.ExecutablePath){
 
       iName  := process.Name
       iId    := process.ProcessId
       hWnd   := process.Handle
       ePath  := process.ExecutablePath
       SplitPath, ePath,, oPath,,,oDrive
      ;MsgBox %  "Letter:" oDrive "`nPath: "oPath "`npath" path
      
       If !InStr(ePath,path)
           Continue
 
       Loop, parse, exCludes, CSV
         If (iName = A_LoopField ) 	
            Continue
 
      ;My NO!!!
       If (iId = AmiNO) or (iName = A_ScriptName) 
           continue
 		
       ;~ MsgBox %  "Letter:" oDrive "`nPath: "oPath 
       ;~ Process, Close, %hWnd%
       ;~ PostMessage, 0x112, 0xF060,,, %hWnd%  ; 0x112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE
       ;~ PostMessage, 0x112, 0xF060,,, %iName%  ; 0x112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE
       ;~ WinClose, ahk_id %iId%
       
  }
 }
}

the above script accepts the full path and should close the given program gracefully. The nearest thing that I have found is this:

PostMessage, 0x112, 0xF060,,, %hWnd%  ; 0x112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE

and:

PostMessage, 0x112, 0xF060,,, %iName%  ; 0x112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE

however, they do not work with %hWnd% and %iName%.

Any possible solution or fix for the above script?

1

1 Answers

3
votes

First of all I'd try

WinClose, ahk_id %iId%

because

  • WinClose (WM_Close message) is the least forceful way:

    WinClose, WinTitle

  • PostMessage (SC_Close message) is similar to WM_Close, but more forceful:

    PostMessage, 0x112, 0xF060,,,WinTitle

  • WinKill attempts WM_Close, then attempts to kill the process:

    WinKill, WinTitle

  • Process,Close is the most forceful way - equivalent to killing a process from the task manager:

    Process,Close, ProcessName.exe