How can i detect when program are closed?

0

I am open application via kernel32.CreateProcessW. After this i get PID and Handle of application. Now, I want to detect when application are closed.

I am using WaitForSingleObject. But it is return only 0.

from ctypes import *
from defines import *
from datetime import *
import time

kernel32     = windll.kernel32

class test():
    def __init__(self):
        self.hProcess   = None


    def load(self):
        creation_flags      = CREATE_NEW_CONSOLE
        startupinfo         = STARTUPINFO()
        process_information = PROCESS_INFORMATION()

        startupinfo.cb      = sizeof(startupinfo)

        if kernel32.CreateProcessW('C:\\Windows\\System32\\calc.exe',
                                    None,
                                    None,
                                    None,
                                    None,
                                    creation_flags,
                                    None,
                                    None,
                                    byref(startupinfo),
                                    byref(process_information)):
            self.hProcess = process_information.hProcess
            print('CALC PID: {0}, Handle: {1}'.format(process_information.dwProcessId, process_information.hProcess))
        else:
            print('Error while opening process')

    def waitfor(self):
        print(kernel32.WaitForSingleObject(self.hProcess, 0xFFFFFFFF))

s = test()

s.load()
s.waitfor()

python-3.x
ctypes
kernel32
asked on Stack Overflow Jun 12, 2019 by Excalibur • edited Jul 3, 2019 by Excalibur

1 Answer

1

Returning 0 is the value of WAIT_OBJECT_0, meaning the hProcess handle has signaled process exit.

As my comment stated, On Windows 10 calc.exe is a stub program. It runs a different process (a Windows store app) and immediately exits. So you are detecting that program (calc.exe) closed. Change the code to use notepad.exe (a native windows app) which doesn't go on to launch a different app, and your script will wait until you close notepad.

answered on Stack Overflow Jun 13, 2019 by Mark Tolonen

User contributions licensed under CC BY-SA 3.0