Jump to content

OnAutoItExitRegister questions


Recommended Posts

Hello all.  So I have some questions concerning the OnAutoItExitRegister function.  I see the help file takes the time to explain how the exit code and exit method can be retrieved from macro values and even defines some of the methods, but my question is are the methods that the help file defines the only methods that autoit can detect?  Allow me to elaborate: consider the below script, which was compiled as a CUI script rather than a GUI script:

; *** Start added by AutoIt3Wrapper ***
#include <AutoItConstants.au3>
; *** End added by AutoIt3Wrapper ***
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_SaveSource=y
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Res_requestedExecutionLevel=requireAdministrator
#AutoIt3Wrapper_Add_Constants=n
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.15.0 (Beta)
 Author:         myName

 Script Function:
    Template AutoIt script.

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

OnAutoItExitRegister ( "endproc" )
ShellExecute ( "notepad.exe" )
$text = 0
Do
    $text = $text + 1
    ; Do stuff
Until $text = 5
; Do more stuff here

Func endproc ()
    Do
        ProcessClose ( "notepad.exe" )
    Until Not ProcessExists ( "notepad.exe" )
EndFunc

This script is not the exact same as the one I am working with, but it will still help me illustrate the nature of my question/problem.  The main difference between this script and the one I am working with is that the contents inside the "Do...Until" loop are very unlikely to satisfy the condition that would allow the loop to exit (its monitoring if a web site is online and will only exit the loop if the code in the loop indicate the site has gone down).  That being the case, the scenario which is much more likely is that the script will be closed by me when I close the command prompt (either by clicking the "x" or using the keyboard "ctrl + c").  However, when I exit the application in this way, the contents of the function that I defined in the "OnAutoitExitRegister" function do not appear to be executing, as notepad remains open after the script has stopped running.  Why is this?  I am guessing compiling the script as a cui rather than a gui might have something to do with it, but is there a way for autoit to register a function when a cui script is closed in either of the ways I described above.  I look forward to your feed back.

Link to comment
Share on other sites

2 hours ago, MattHiggs said:

I look forward to your feed back.

; *** Start added by AutoIt3Wrapper ***
#include <AutoItConstants.au3>
; *** End added by AutoIt3Wrapper ***
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_SaveSource=y
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Res_requestedExecutionLevel=requireAdministrator
#AutoIt3Wrapper_Add_Constants=n
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.15.0 (Beta)
 Author:         myName

 Script Function:
    Template AutoIt script.

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

ReRun() ; ugly fix
Func ReRun()

    If Not @Compiled Then
        ConsoleWrite(@CRLF & @CRLF & @CRLF & "!!!   compile to run the example   !!!" & @CRLF & @CRLF & @CRLF & @CRLF)
        Exit 0
    EndIf

    If Not StringInStr($CmdLineRaw, "/ErrorStdOut") Then
        WinSetState(@ScriptFullPath, "", @SW_HIDE)
        Local $errorlevel = ShellExecuteWait(@ScriptFullPath, "/ErrorStdOut " & $CmdLineRaw)
        Do
            ProcessClose ( "notepad.exe" )
        Until Not ProcessExists ( "notepad.exe" )
        Exit $errorlevel
    EndIf

EndFunc

;~ OnAutoItExitRegister ( "endproc" ) ; replaced by ugly fix
ShellExecute ( "notepad.exe" )
$text = 0
WinActivate(@ScriptFullPath)
Do
    $text = $text + 1
    ConsoleWrite('loop # ' & $text  & ' of 10'& @CRLF)
    ; Do stuff
    Sleep(2000)
Until $text = 10
; Do more stuff here

Func endproc ()
    Do
        ProcessClose ( "notepad.exe" )
    Until Not ProcessExists ( "notepad.exe" )
EndFunc

Same here. If I close the compiled script it does not behave has expected.
But you could write a watchdog that'll do the work of OnAutoItExitRegister() when you exit  =/

Edited by argumentum
ugly fix example / watchdog

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

The OP script works as intended here (W7 x64). I'm surprised it doesn't work elsewhere.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

here the problem described by op also arises. (Win7 x64),
as suggested by @argumentum better to insert a delay of few seconds within the do ...  Until $text = 5 loop so to give time to notepad to start, and also allow users to force the close of the command prompt window.
When I force the close of the command prompt window, (before the script ends by himself) the notepad is not killed by the OnAutoItExitRegister function.

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

even more strange... as @argumentum suggested, tryed a WatchDog way by spawn a process detached from the main script. (I can see that there are 2 processes with 2 different Pid in task manager) the whole works OK even if compiled, but if I force the close of the command prompt window of the main exe, then also the detached exe is closed as well (shouldn't the detached exe continue to run??)

 

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#pragma compile(AutoItExecuteAllowed, true)

Local $hPid = ShellExecute('notepad.exe')

_WatchDog_OnAutoItExitRegister()

MsgBox(0, "Demo", "press ok to exit (and let notepd be closed by the watchdog)")


Func _WatchDog_OnAutoItExitRegister()

    ; prepare the "On exit" script (it must stay all in one line)
    Local $sCommand = "Local $WatchDog = ProcessWaitClose($CmdLine[1]), $Dummy = ProcessClose($CmdLine[2]) + MsgBox(0,'WatchDog','All done! ... woof woof!' )"

    ; adjust quotes if needed
    ;https://www.autoitscript.com/forum/topic/181491-question-about-autoit3executeline/?do=findComment&comment=1303199
    $sCommand = '"' & StringReplace($sCommand, '"', '""') & '"'

    ; unleash the "WatchDog"
    ; the @AutoItPID passed here is the Pid of the "main" script (not the pid of the detached script)
    Run(@AutoItExe & ' /AutoIt3ExecuteLine ' & $sCommand & ' ' & @AutoItPID & ' ' & $hPid)

EndFunc   ;==>_WatchDog_OnAutoItExitRegister

 

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

1 hour ago, Chimp said:

even more strange... as @argumentum suggested, tryed a WatchDog way by spawn a process detached from the main script. (I can see that there are 2 processes with 2 different Pid in task manager) the whole works OK even if compiled, but if I force the close of the command prompt window of the main exe, then also the detached exe is closed as well (shouldn't the detached exe continue to run??)

 

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#pragma compile(AutoItExecuteAllowed, true)

Local $hPid = ShellExecute('notepad.exe')

_WatchDog_OnAutoItExitRegister()

MsgBox(0, "Demo", "press ok to exit (and let notepd be closed by the watchdog)")


Func _WatchDog_OnAutoItExitRegister()

    ; prepare the "On exit" script (it must stay all in one line)
    Local $sCommand = "Local $WatchDog = ProcessWaitClose($CmdLine[1]), $Dummy = ProcessClose($CmdLine[2]) + MsgBox(0,'WatchDog','All done! ... woof woof!' )"

    ; adjust quotes if needed
    ;https://www.autoitscript.com/forum/topic/181491-question-about-autoit3executeline/?do=findComment&comment=1303199
    $sCommand = '"' & StringReplace($sCommand, '"', '""') & '"'

    ; unleash the "WatchDog"
    ; the @AutoItPID passed here is the Pid of the "main" script (not the pid of the detached script)
    Run(@AutoItExe & ' /AutoIt3ExecuteLine ' & $sCommand & ' ' & @AutoItPID & ' ' & $hPid)

EndFunc   ;==>_WatchDog_OnAutoItExitRegister

 

Wow.  Did not expect the conversation to go in this direction.  I had assumed I had done something wrong and that was why OnAutoItExitRegister was not running correctly, but it appears that I am not the only one who is running into this issue.  So I just want to confirm that the behavior for OnAutoItExitRegister is not by design and is not behaving as it should, right?  Should I file a bug report?

 

Also, thanks for the solution, @argumentum.

Edited by MattHiggs
Link to comment
Share on other sites

7 hours ago, MattHiggs said:

However, when I exit the application in this way, the contents of the function that I defined in the "OnAutoitExitRegister" function do not appear to be executing,

That's by design, you aren't exiting the process, you are killing it. There's no way for any program to know you're doing that. OnAutoItExit only works when the program closes normally, you're not closing it normally. There's no bug.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

17 minutes ago, BrewManNH said:

That's by design, you aren't exiting the process, you are killing it. There's no way for any program to know you're doing that. OnAutoItExit only works when the program closes normally, you're not closing it normally. There's no bug.


Ok.  While I understand what you are saying, autoit is able to determine if a script exited due to the user logging out or shutting down the machine, right?  As far as the executing script is concerned, wouldn't the act of shutting down or logging off the machine be interpreted as "killing the script" as well, @BrewManNH?

Edited by MattHiggs
Link to comment
Share on other sites

  • Developers

Nope, When a computer shuts down, a close messages is send to all "program windows" which will then include the hidden Autoit3 window and a normal close will be performed by AutoIt3 which includes performing the registered functions for Exit.

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

therefore, the use of Run(@AutoItExe & ' /AutoIt3ExecuteLine ' & ... does not generate a detached process, but in this case, it generates a process that is "child" and still connected to the main script (I thought it was not so).
it seems however that using ShellExecute () instead of run (), generates a detached and independent process from the main script. Good to know...
here a working version of the WatchDog that works as expected (at least as expected by me)
 so that if you force the close of the main scipt, the WatchDog still runs and acts as it was programmed to do

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#pragma compile(AutoItExecuteAllowed, true)

Local $hPid = ShellExecute('notepad.exe')

_WatchDog_OnAutoItExitRegister()

MsgBox(0, "Demo", "press ok to exit (and let notepd be closed by the watchdog)")


Func _WatchDog_OnAutoItExitRegister()

    ; prepare the "On exit" script (it must stay all in one line)
    Local $sCommand = "Local $WatchDog = ProcessWaitClose($CmdLine[1]), $Dummy = ProcessClose($CmdLine[2]) + MsgBox(0,'WatchDog','All done! ... woof woof!' )"

    ; adjust quotes if needed
    ;https://www.autoitscript.com/forum/topic/181491-question-about-autoit3executeline/?do=findComment&comment=1303199
    $sCommand = '"' & StringReplace($sCommand, '"', '""') & '"'

    ; unleash the "WatchDog"
    ; the @AutoItPID passed here is the Pid of the "main" script (not the pid of the detached script)
    ; Run(@AutoItExe & ' /AutoIt3ExecuteLine ' & $sCommand & ' ' & @AutoItPID & ' ' & $hPid)
    ShellExecute(@AutoItExe, ' /AutoIt3ExecuteLine ' & $sCommand & ' ' & @AutoItPID & ' ' & $hPid, '', '', @SW_HIDE)

EndFunc   ;==>_WatchDog_OnAutoItExitRegister

 

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

4 hours ago, BrewManNH said:

That's by design, you aren't exiting the process, you are killing it.

; *** Start added by AutoIt3Wrapper ***
#include <AutoItConstants.au3>
; *** End added by AutoIt3Wrapper ***
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseX64=y
#AutoIt3Wrapper_Change2CUI=n
#AutoIt3Wrapper_Res_SaveSource=y
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Res_requestedExecutionLevel=requireAdministrator
#AutoIt3Wrapper_Add_Constants=n
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.15.0 (Beta)
 Author:         myName

 Script Function:
    Template AutoIt script.

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

;~ ReRun() ; ugly fix
;~ Func ReRun()

;~  If Not @Compiled Then
;~      ConsoleWrite(@CRLF & @CRLF & @CRLF & "!!!   compile to run the example   !!!" & @CRLF & @CRLF & @CRLF & @CRLF)
;~      Exit 0
;~  EndIf

;~  If Not StringInStr($CmdLineRaw, "/ErrorStdOut") Then
;~      WinSetState(@ScriptFullPath, "", @SW_HIDE)
;~      Local $errorlevel = ShellExecuteWait(@ScriptFullPath, "/ErrorStdOut " & $CmdLineRaw)
;~      Do
;~          ProcessClose ( "notepad.exe" )
;~      Until Not ProcessExists ( "notepad.exe" )
;~      Exit $errorlevel
;~  EndIf

;~ EndFunc

;;; GUI vs. CUI
AutoItWinSetTitle(@ScriptFullPath)
WinSetState(@ScriptFullPath, "", @SW_SHOW)

;;; if I close the "main" window
;;; OnAutoItExitRegister() behaves as expected
;;; but is not expected that a CUI's frame is
;;; not the "window" of the script.
;;; Then again, we are not programmers  =)


OnAutoItExitRegister ( "endproc" ) ; replaced by ugly fix
ShellExecute ( "notepad.exe" )
Global $text = 0, $sTemp = ""
WinActivate(@ScriptFullPath)
Do
    $text = $text + 1
    ConsoleWrite('loop # ' & $text  & ' of 10'& @CRLF)
    $sTemp &= 'loop # ' & $text  & ' of 10'& @CRLF
    ControlSetText(@ScriptFullPath, "", "Edit1", $sTemp)
    ; Do stuff
    Sleep(2000)
Until $text = 10
; Do more stuff here

Func endproc ()
    Do
        ProcessClose ( "notepad.exe" )
    Until Not ProcessExists ( "notepad.exe" )
EndFunc

We are scriptwriters, not programmers. Hence, we believe, that the frame we see, is a window 😕 
Understood :) 

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

6 minutes ago, argumentum said:

Hence, we believe, that the frame we see, is a window 😕 
Understood :) 

I don't understand at all what you're trying to say here, or in the comments in your script. BTW, script writers are programmers, don't sell yourself short.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

What CUI are you talking about? The AutoIt hidden window? That's not a "CUI" that's there on every script that gets run, whether or not you use CUI mode or not. The 2 things aren't the same.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

24 minutes ago, BrewManNH said:

I don't understand at all what you're trying to say here, or in the comments in your script.

I don't try, I say.
As far as understanding, I can not make you understand :( 

...and the OP question is answered, so no more chatting on this thread from me. ;) 

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

  • Developers

No the less, this last post is pretty spot on. ;) 

57 minutes ago, BrewManNH said:

What CUI are you talking about? The AutoIt hidden window? That's not a "CUI" that's there on every script that gets run, whether or not you use CUI mode or not. The 2 things aren't the same.

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Another possible solution.

#AutoIt3Wrapper_Change2CUI=y

ShellExecute("notepad.exe")

Global $g_cbHandler = DllCallbackRegister(_HandlerRoutine, "BOOL", "DWORD")

;~ https://docs.microsoft.com/en-us/windows/console/setconsolectrlhandler
DllCall("kernel32", "BOOL", "SetConsoleCtrlHandler", "PTR", DllCallbackGetPtr($g_cbHandler), "BOOL", True)

ProcessWaitClose(@AutoItPID)

Func _HandlerRoutine($dwCtrlType)
    ProcessClose("notepad.exe")
EndFunc

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...