WinCloseEx

Post your working scripts, libraries and tools.
CyberKlabauter
Posts: 44
Joined: 26 Jan 2017, 17:59

WinCloseEx

27 Feb 2024, 03:53

I have ported @Flipeador WinCloseEx to AHK V2 (see viewtopic.php?p=119186&sid=a23658e68fed5bb77cf5268cada39404#p119186). I hope it hasn't already been done. It might be useful for some.

Code: Select all

; -----------------------------        WinCloseEx          -----------------------------
;author:	Flipeador
;forum:		https://www.autohotkey.com/boards/viewtopic.php?p=119186&sid=a23658e68fed5bb77cf5268cada39404#p119186
/*
hWnd: Window ID.
Force:
			0 = WM_CLOSE.
			1 = TerminateThread.
			2 = TerminateProcess.
			3 = if TerminateThread fails, try TerminateProcess.
*/

WinCloseEx(hWnd := 0, Force := false) {
	if !StrLen(hWnd)
		hWnd := WinExist(hWnd)

	if (Force = 1) || (Force = 2) || (Force = 3) {
		if !(ThreadId := DllCall("User32.dll\GetWindowThreadProcessId", "Ptr", hWnd, "UIntP", &ProcessId, "UInt"))
			return false

		;maybe you could try terminate the thread...
		if (Force = 1) || (Force = 3)
			hThread := DllCall("Kernel32.dll\OpenThread", "UInt", 0x0001, "Int", false, "UInt", ThreadId, "Ptr")			, Result := DllCall("Kernel32.dll\TerminateThread", "Ptr", hThread, "UInt", 0)			, DllCall("Kernel32.dll\CloseHandle", "Ptr", hThread)

		;this is how winkill works if WM_CLOSE fail.
		if (Force = 2) || ((Force = 3) && !(Result))
			hProcess := DllCall("Kernel32.dll\OpenProcess", "UInt", 0x0001, "Int", false, "UInt", ProcessId, "Ptr")			, Result := DllCall("Kernel32.dll\TerminateProcess", "Ptr", hProcess, "UInt", 0)			, DllCall("Kernel32.dll\CloseHandle", "Ptr", hProcess)

		return Result
		}

	if !DllCall("User32.dll\IsWindow", "Ptr", hWnd) || DllCall("User32.dll\IsHungAppWindow", "Ptr", hWnd)
		return false

	;normal method
	Result := DllCall("User32.dll\PostMessageW", "Ptr", hWnd, "UInt", 0x0002, "Ptr", 0, "Ptr", 0)
	DllCall("User32.dll\PostMessageW", "Ptr", hWnd, "UInt", 0x112, "Ptr", 0xF060, "Ptr", 0)
	return Result
	}
Cheers
User avatar
andymbody
Posts: 1034
Joined: 02 Jul 2017, 23:47

Re: WinCloseEx

29 Feb 2024, 06:00

Thank you!!

Does this work when admin is required, but scripts cannot be run as admin on the system? I am trying to write a solution for a remote client, but I cannot test their environment directly. I ask this question to determine whether I should even attempt to try this function, cause it takes awhile for the client to test it themselves, and if this is not expected to work, I will try something else to save time.
CyberKlabauter
Posts: 44
Joined: 26 Jan 2017, 17:59

Re: WinCloseEx

04 Mar 2024, 15:46

As far as I know, this should not be possible in general.

Return to “Scripts and Functions (v2)”

Who is online

Users browsing this forum: No registered users and 28 guests