1

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()

3
  • Show code. See minimal reproducible example guidelines. Commented Jun 12, 2019 at 23:57
  • I suspect the application you are running may be a stub. Try notepad.exe which is a native windows application. calc.exe on Windows 10, for example, is a native app that redirects to a Windows store app and exits immediately. Commented Jun 13, 2019 at 0:18
  • I want to detect when application closed
    – Excalibur
    Commented Jun 13, 2019 at 5:53

1 Answer 1

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.

2
  • Results are the same. I think i have to use Job Object.
    – Excalibur
    Commented Jun 13, 2019 at 8:16
  • I use job object and result is positive. How can i handle apps like calc.exe? Job not work with this apps
    – Excalibur
    Commented Jun 13, 2019 at 8:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.