How to determine if win32api.ShellExecute was successful using hinstance?

前端 未结 2 629
一向
一向 2021-01-14 01:33

I\'ve been looking around for an answer to my original issue.. how do i determine (programmatically) that my win32api.ShellExecute statement executed successfully, and if a

相关标签:
2条回答
  • 2021-01-14 01:52

    The return value of ShellExecute is what you need to test. You return that from print_file, but you then ignore it. You need to capture it and check that.

    hinstance = print_file(i, printer_name)
    if hinstance > 32:
        ....
    

    However, having your print_file function leak implementation detail like an HINSTANCE seems bad. I think you would be better to check the return value of ShellExecute directly at the point of use. So try to move the > 32 check inside print_file.

    Note that ShellExecute has very weak error reporting. If you want proper error reporting then you should use ShellExecuteEx instead.

    Your delete/sleep loop is very brittle indeed. I'm not quite sure I can recommend anything better since I'm not sure what you are trying to achieve. However, expect to run into trouble with that part of your program.

    0 讨论(0)
  • 2021-01-14 01:59

    With ShellExecute, you will never know when the printing is complete, it depends on the size of the file and whether the printer driver buffers the contents (the printer might be waiting for you to fill the paper tray, for example).

    According to this SO answer, it looks like subprocess.call() is a better solution, since it waits for the command to complete, only in this case you would need to read the registry to obtain the exe associated with the file.

    ShellExecuteEx is available from pywin32, you can do something like:

    import win32com.shell.shell as shell
    param = '/d:"%s"' % printer
    shell.ShellExecuteEx(fmask = win32com.shell.shellcon.SEE_MASK_NOASYNC, lpVerb='print', lpFile=pfile, lpParameters=param)
    

    EDIT: code for waiting on the handle from ShellExecuteEx()

    import win32com.shell.shell as shell
    import win32event
    #fMask = SEE_MASK_NOASYNC(0x00000100) = 256 + SEE_MASK_NOCLOSEPROCESS(0x00000040) = 64
    dict = shell.ShellExecuteEx(fMask = 256 + 64, lpFile='Notepad.exe', lpParameters='Notes.txt')
    hh = dict['hProcess']
    print hh
    ret = win32event.WaitForSingleObject(hh, -1)
    print ret
    
    0 讨论(0)
提交回复
热议问题