Jump to content

....


stuka
 Share

Recommended Posts

Hi

OnAutoItExit() wouldn't get a chance to run in a script crash or system crash, but you could regularly write the @ExitMethod

code to a log file with date along with a start time/date in the log file and use your script to compare if the last shutdown

happened normally:

e.g.

Edit: typos, again

[startUp/ShutDown]

2007-09-17 03:49:36 : StartTime

2007-09-17 03:49:40 : ExitMethod: 2 ; close by clicking on exit of the systray.

2007-09-17 03:51:39 : StartTime

2007-09-17 03:51:41 : ExitMethod: 0 ; Natural closing.

2007-09-17 03:54:18 : StartTime ; Exit time missing

delete the log contents after your preferred number of start/close events

even a simple string search for an Even number of "ExitMethod" to StartTime" strings in the log would indicate a crash,

then use that in your Run at startup script

You could install a small console app (no gui)

that runs on startup. or run your script on startup with a commandline parameter that runs code to clear the temp folder

then exits the script without running your usual program routine or a gui

see $cmdline and $cmdlineRAW in the help file

add a key to the registry run section

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

RegWrite("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", "YourFolderClear", "REG_SZ", "C:\Program Files\YourFolder\YourScript.exe /clear")

You could also deploy a second script when your script starts that monitors the first script and deletes the folder if the first script crashes

there are some examples on the forum of scripts that restart a script if it is closed

See Help section "Running Script"

Edit: just set a scheduled task to delete the folder, that would handle a script crash and the below code would allow deleting the folder after reboot.

remove the task and schedule a new one if the script is still running close to the scheduled time of the first task

#include <File.au3>

Opt("OnExitFunc","OnAutoItExit");"OnAutoItExit" called on Exit

Local $ClearTemp = "/cleartemp"
Local $ProgFolderClear = @ProgramFilesDir & "\YourFolder\YourScript.exe /cleartemp"
Local $ProgFolder = @ProgramFilesDir & "\YourFolder"

; any admin permissions etc, are required
If Not RegRead("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", "YourFolderClear") Then
    $Regwrite = RegWrite("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", "YourFolderClear", "REG_SZ", $ProgFolderClear)
    If $Regwrite = 0 Or @error <> 0 Then
        Switch @error
            Case 1
                $regerr1 = "Unable to open requested reg key"
                $regerr2 = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
            Case 2
                $regerr1 = "Unable to open requested main key:"
                $regerr2 = "HKLM\SOFTWARE"
            Case 3
                $regerr1 = "Unable to remote connect to the registry"
                $regerr2 = ""
            Case -1
                $regerr1 = "Unable to open requested value"
                $regerr2 = $progFolder
            Case -2
                $regerr1 = "Value type not supported"
                $regerr2 = ""
        EndSwitch
        MsgBox(16, "Unable To Write Registry Entry", $regerr1 & @CRLF & $regerr2)
    EndIf
EndIf

; place in your script before message loop or any other events,
; preferably after #includes, AutoItSetOption, and variables are declared

; parse commandline options
If IsArray($CmdLine) And $CmdLine[0] Then
    For $element In $Cmdline
        Switch $element
            Case $ClearTemp ; Delete files in temp folder
                If FileExists($ProgFolder) Then ; checks that folder exists
                    ;DirRemove($ProgFolder, 1) ; remove files and subdirectories under $ProgFolder
                    FileDelete($ProgFolder & "\*.*")   ; delete all
                    FileDelete($ProgFolder & "\*.au3") ; delete individual filetypes
                    FileDelete($ProgFolder & "\*.tmp") ; ..
                    ; ..... add file types to delete
                    ; FileRecycle("C:\*.tmp") ; send files to recycle bin
                    ; If Not FileExists($ProgFolder & "\*.*") Then DirRemove($ProgFolder, 0)
                    ; delete folder after file delete, less risk of deleting wrong folder, only deletes if folder empty of files and subdirs
                EndIf
                _FileWriteLog(@ScriptDir & "\event.log","Folder Clear Run"& @CRLF & @CRLF)
                Exit
            ;Case ... additional command line options
            Case Else
        EndSwitch
    Next
EndIf

_FileWriteLog(@ScriptDir & "\event.log","StartTime") ; write startime

; script body here

Func OnAutoItExit()
    Switch @exitMethod
        Case 0
            $exitmeth = "Natural closing"
        Case 1
            $exitmeth = "close by Exit function"
        Case 2
            $exitmeth = "close by clicking on exit of the systray"
        Case 3
            $exitmeth = "close by user logoff"
        Case 4
            $exitmeth = "close by Windows shutdown"
    EndSwitch
    _FileWriteLog(@ScriptDir & "\event.log","ExitMethod: "& $exitmeth & @CRLF & @CRLF) ; write exit time and method
EndFunc   ; OnAutoItExit

Edit: changed RegWrite startup type to "RunOnce", added missing AutoItSetOption "OnAutoItExit"

Edited by rover

I see fascists...

Link to comment
Share on other sites

AutoIt returns @ExitMethod as it shutsdown

so a logoff or a system shutdown is detected automatically and OnAutoItExit function is run

so the best thing is to have your script set the registry RunOnce to run the script on reboot and delete the temp folder

when the script first starts,

then, if script shutdown is normal and the OnAutoItExit function deletes the temp folder, then remove that registry entry.

If the script crashes or the OnAutoItExit function doesn't get to complete the normal temp folder delete

the registry entry your script made when first run will still be there and on reboot will run your script with a commandline parameter

'/cleartemp", that will delete the temp folder and exit the script.

the registry RunOnce entry will be removed by windows after the script is run, hence "RunOnce".

seems not..

you can change the regwrite to regdelete for the runonce key

you need to edit these variables with your path/filenames

$ProgScriptFolder ; program files folder\scriptname.exe and commandline parameter name that when run will only delete the temp folder then exit script

$ProgTempFolder ; program files folder\the name of your temp folder

$RegkeyValue ; the name of the registry value for the script to run at startup, could be "Autorun Eater"

#include <File.au3>
; your includes
Local $ClearTemp = "/cleartemp"
Local $ProgScriptFolder = @ProgramFilesDir & "\YourScriptFolder\YourScript.exe /cleartemp"
Local $ProgTempFolder = @ProgramFilesDir & "\YourTempFolder"
Local $RegKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
Local $RegkeyValue = "YourFolderClear"
Opt("OnExitFunc","OnAutoItExit");"OnAutoItExit" called on Exit

 _CMDLineParse()    ; place in your script after #includes, AutoItSetOption, and variables are declared
_RegWriteRunOnce()  ; call function to schedule script run on reboot, cancel if "Exit" is normal and temp folder deleted

; your code

; place these three functions at bottom of script
Func _RegWriteRunOnce() ; registry write for RunOnce at system startup with Error Handling
    Local $regerr1, $regerr2
    If RegRead($RegKey, $RegkeyValue) <> $ProgScriptFolder Then
        RegWrite($RegKey, $RegkeyValue, "REG_SZ", $ProgScriptFolder)
        Local $regerror = @error
        
        AutoItSetOption("WinTitleMatchMode", 4)
        Local $SpyBotTitle = "[TITLE:Spybot - Search & Destroy]; CLASS:TformRegistryWarning]"

        WinWait($SpyBotTitle, "", 5)
        If WinExists($SpyBotTitle,"") Then
            WinSetOnTop($SpyBotTitle, "", 1)
            Do
                Sleep(250)
                If Not WinActive($SpyBotTitle, "") Then WinActivate($SpyBotTitle, "")
                Send("!a")
            Until Not WinExists($SpyBotTitle,"")
            If RegRead($RegKey, $RegkeyValue) <> $ProgScriptFolder Then
                _FileWriteLog(@ScriptDir & "\event.log","Spybot - Search & Destroy Has Deleted Reg Entry" & @CRLF)
                RegWrite($RegKey, $RegkeyValue, "REG_SZ", $ProgScriptFolder)
                $regerror = @error
            EndIf
        EndIf
        
        If RegRead($RegKey, $RegkeyValue) <> $ProgScriptFolder Then
            Switch $regerror
                Case 1
                    $regerr1 = "Unable to open requested reg key"
                    $regerr2 = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
                Case 2
                    $regerr1 = "Unable to open requested main key:"
                    $regerr2 = "HKLM\SOFTWARE"
                Case 3
                    $regerr1 = "Unable to remote connect to the registry"
                    $regerr2 = ""
                Case -1
                    $regerr1 = "Unable to open requested value"
                    $regerr2 = $ProgTempFolder
                Case -2
                    $regerr1 = "Value type not supported"
                    $regerr2 = ""
            EndSwitch
            MsgBox(16, "Unable To Write RunOnce Registry Entry", $regerr1 & @CRLF & $regerr2)
            $regmsg = "RegWrite FAIL: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"&@CRLF&$regerr1&@CRLF&$regerr2
        Else
            $regmsg = "RegWrite SUCCESS: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
        EndIf
    Else
        $regmsg = "RegWrite SUCCESS: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
    EndIf
    _FileWriteLog(@ScriptDir & "\event.log","StartTime" & @CRLF & $regmsg) ; write startime and regwrite RunOnce status
EndFunc ; _RegWriteRunOnce()

; parse commandline options
Func _CMDLineParse() ; delete temp folder on reboot with /cleartemp commandline parameter, then exit script
    If IsArray($CmdLine) And $CmdLine[0] Then
        For $element In $Cmdline
            Switch $element
                Case $ClearTemp ; Delete files in temp folder
                    If FileExists($ProgTempFolder) Then ; checks that folder exists
                        FileSetAttrib($ProgTempFolder, "-RSH",1)
                        DirRemove($ProgTempFolder, 1)   ; remove files and subdirectories under $ProgTempFolder
                    EndIf
                          RegDelete($RegKey, $RegkeyValue) ; DELETE regkey for runonce of script - EDIT 09/18/2007 - Changed to Delete Reg Key
                            AutoItSetOption("WinTitleMatchMode", 4)
                            Local $SpyBotTitle = "[TITLE:Spybot - Search & Destroy]; CLASS:TformRegistryWarning]"

                            WinWait($SpyBotTitle, "", 5)
                            If WinExists($SpyBotTitle,"") Then
                         WinSetOnTop($SpyBotTitle, "", 1)
                                         $timer = TimerInit()
                        Do
                       Sleep(250)
                        If Not WinActive($SpyBotTitle, "") Then WinActivate($SpyBotTitle, "")
                        Send("!a")
                                            If TimerDiff($timer) > 5000 Then ExitLoop
                         Until Not WinExists($SpyBotTitle,"")
                         If RegRead($RegKey, $RegkeyValue) <> "" Then
                    _FileWriteLog(@ScriptDir & "\event.log","Spybot - Search & Destroy Has Prevented Reg Delete" & @CRLF)
                    RegDelete($RegKey, $RegkeyValue) ; DELETE regkey for runonce of script - EDIT 09/18/2007 - Changed to Delete Reg Key
                EndIf
            EndIf
                    _FileWriteLog(@ScriptDir & "\event.log","Folder Clear Successfull"& @CRLF & @CRLF)
                    Exit
                Case Else
            EndSwitch
        Next
    EndIf
EndFunc ; _CMDLineParse()

Func OnAutoItExit()
    Local $regmsg = ""
    FileSetAttrib($ProgTempFolder, "-RSH",1)
    DirRemove($ProgTempFolder, 1)   ; remove files and subdirectories under $ProgTempFolder, script paused until delete completes or fails
    
    Switch FileExists($ProgTempFolder)
        Case 0                  ; folder successfully deleted BEFORE system shutdown, so abort delete on reboot, remove RunOnce command
            RegDelete($RegKey, $RegkeyValue) ; DELETE regkey for runonce of script - EDIT 09/18/2007 - Changed to Delete Reg Key
            
            ;AutoItSetOption("WinTitleMatchMode", 4)
            Local $SpyBotTitle = "[TITLE:Spybot - Search & Destroy]; CLASS:TformRegistryWarning]"

            WinWait($SpyBotTitle, "", 5)
            If WinExists($SpyBotTitle,"") Then
                WinSetOnTop($SpyBotTitle, "", 1)
                                 $timer = TimerInit()
                Do
                    Sleep(250)
                    If Not WinActive($SpyBotTitle, "") Then WinActivate($SpyBotTitle, "")
                    Send("!a")
                                        If TimerDiff($timer) > 5000 Then ExitLoop
                Until Not WinExists($SpyBotTitle,"")
                If RegRead($RegKey, $RegkeyValue) <> "" Then
                    _FileWriteLog(@ScriptDir & "\event.log","Spybot - Search & Destroy Has Prevented Reg Delete" & @CRLF)
                    RegDelete($RegKey, $RegkeyValue) ; DELETE regkey for runonce of script - EDIT 09/18/2007 - Changed to Delete Reg Key
                EndIf
            EndIf
            
            $regmsg = "Temp Folder Deleted"
        Case Else
            $regmsg = "Temp Folder NOT Deleted, script will run on system reboot and delete temp folder"
    EndSwitch
    
_FileWriteLog(@ScriptDir & "\event.log","ExitMethod: "& @exitMethod & @CRLF & $regmsg& @CRLF & @CRLF) ;write time, ExitMethod, RegWrite Result
EndFunc   ; OnAutoItExit

EDIT: OK, I changed confusingly named variables for your script location and the Temp folder location

Edited by rover

I see fascists...

Link to comment
Share on other sites

Do you mean that the RunOnce key will not be removed automatically by Windows? Which part of the script should I edit?

Thank you for your enormous help you've given so far, it is greatly appreciated. I'll give you due credit in my application once it is officially released. :)

Hi,

I used RegWrite instead of RegDelete to be cautious ...

only deleting the run command but not the registry key.

so you could change the RegWrite line in the OnAutoItExit Exit function

Edit: code boxes too big, changed to AutoIt boxes, what is it with this *&#$@%^* forum software?

From

RegWrite($RegKey, $RegkeyValue, "REG_SZ", "") ; clear regkey for runonce of scriptoÝ÷ Ù:ºÚ"µÍYÑ[]J  ÌÍÔYÒÙ^K   ÌÍÔYÚÙ^U[YJHÈ[]HYÚÙ^HÜ[ÛÙHÙØÜ

Edit: text overwritten and garbled. by editor

Resnullius had some valid points in your other topic regarding dealing with various softwares that protect the registry.

so if you want to deal with other softwares you may need a loop that keeps checking the registry after making the edit

and perhaps pops up a messagebox to request the user input to allow the registry edit as it would be hard to code for

and anticipate every possible programs registry write intervention routine..

I assume your script will not be in the target temp directory?

as that would make it hard to delete the folder and it's contents?

so if you use the three functions you can write the reboot delete line to the registry every time your script runs.

delete that line if the script exits normally, the onautoitexit function will do that as well as delete the target temp folder

if script crashes or system crashes, then your call to your script via commandline on reboot will delete the folder.

i'm going to add another regdelete i think to the commandline folder delete routine

because otherwise the registry entry will still be there unless the script is run and exited normally one more time

see revised code above for commandline section.

Edited by rover

I see fascists...

Link to comment
Share on other sites

Yes, you could put a message box

just after the reg write, that will pause the script and alert the user that they should allow the spybot dialog.

you would still have to detect that window / popup that might undo the registry change

and/or monitor the registry to see if after a certain time the reg value is there or not

if present when script writes at start and when absent at script exit or after reboot and commandline temp folder delete

kind of goes round in circles? doesn't it?

a lot o things to keeep track of and some unexpected things to anticipate.

remove this from commandline function and from onautoitexit

AutoItSetOption("WinTitleMatchMode", 4)
                    Local $SpyBotTitle = "[TITLE:Spybot - Search & Destroy]; CLASS:TformRegistryWarning]"

                    WinWait($SpyBotTitle, "", 5)
                    If WinExists($SpyBotTitle,"") Then
                        WinSetOnTop($SpyBotTitle, "", 1)
                        Do
                            Sleep(250)
                            If Not WinActive($SpyBotTitle, "") Then WinActivate($SpyBotTitle, "")
                            Send("!a")
                        Until Not WinExists($SpyBotTitle,"")

replace with

MsgBox(262144,"User Permission Required", "Allow This Registry Write, Before Clicking OK On This Message")

something like that, see also Resnullius code,... this forum editor is tiring to work with...

Edited by rover

I see fascists...

Link to comment
Share on other sites

Thanks for the script.

My script will only clear the 'temporary folder' when it is exited through the tray icon. Can the script be scripted in a way whereby it detects that the system is shutting down and then adds a task to delete it during the next boot, or something like that?

I'm sorry if i'm being redundant.

No need to do that.. You can get notification of a shutdown and perform a clean up

$WM_QUERYENDSESSION = 0x0011

GUICreate("ShutDownNotificationGui")
GUIRegisterMsg($WM_QUERYENDSESSION, "_ShutdownInitiated")
GUISetSTate(@SW_HIDE)

While 1
    sleep(10)
WEnd

Func _ShutdownInitiated($hWndGUI, $MsgID, $WParam, $LParam)
    FileDelete("MyFile.txt");do whatever you need to do here
    Return True
EndFunc
Link to comment
Share on other sites

Hi

actually this is what AutoIt does with OnAutoItExit() function

i added file logging with @exitmethod code and shutdown and logged off system

log showed exitmethod 4 for system shutdown and exitmethod 3 for logoff

Func OnAutoItExit()

_FileWriteLog(@ScriptDir & "\event.log","ExitMethod: "& @exitMethod & @CRLF & $regmsg& @CRLF & @CRLF)

; write exit time, ExitMethod

;0 Natural closing

;1 close by Exit function.

;2 close by clicking on exit of the systray.

;3 close by user logoff.

;4 close by Windows shutdown.

EndFunc

I see fascists...

Link to comment
Share on other sites

rover, which AutoIt code should I use out of the 2 'AutoIt Codes' you added in the previous replies? I mean the complete one. The one that deletes temp files on shutdown/exit and has the function that deals with the RegWrite issue.

ChrisL, the script will detect that windows is shutting down and clear the files? Does it work if the system crashes or if the script is killed using TaskMgr? Where should I place the script you mentioned?

Windows sends a notification on shutdown, the code I attached accepts that notification and performs the action you require.

It doesn't do anything with crashes or task manager end task

If you already have a gui you can use that rather than the one I made (which is not visible)

You can put the code where you like as long as it has been called, Put the gui and the $WM_QUERYENDSESSION = 0x0011 at the top with the registermessage and the func at the bottom.

The while loop is probably not needed if your script is already running something which keeps it going

Link to comment
Share on other sites

Hi ChrisL

this functionality is already built into AutoIt.

AutoIt does detect shutdowns , thats one of the things OnAutoItExit() does,

look in the help file

AutoIt initiates a shutdown of the script if you logoff or start a reboot or shutdown...

as my example above shows,

you can even record to log the method of shutdown, i.e system or user

what am i missing here, communication wise?

is this faster than native autoit shutdown?

is there a speed advantage to using this over the native autoit Windows notification detect.

i've used guiregistermsg method for toolbars, sliders etc.

Edited by rover

I see fascists...

Link to comment
Share on other sites

jackit

The second one, the first was rough outline of the three functions

commandline parse

onautoitexit

regwrite

but you need to edit it for your use , it does have a lot of error handling, that always bloats script

got to go.....

I see fascists...

Link to comment
Share on other sites

Hi ChrisL

this functionality is already built into AutoIt.

AutoIt does detect shutdowns , thats one of the things OnAutoItExit() does,

look in the help file

AutoIt initiates a shutdown of the script if you logoff or start a reboot or shutdown...

as my example above shows,

you can even record to log the method of shutdown, i.e system or user

what am i missing here, communication wise?

is this faster than native autoit shutdown?

is there a speed advantage to using this over the native autoit Windows notification detect.

i've used guiregistermsg method for toolbars, sliders etc.

It doesn't always work like you think, see here http://www.autoitscript.com/forum/index.ph...c=52810&hl=

In that post someone wanted to do something when shutdown was detected, using onAutoitExit() didn't work for them, but using the guiregistermessage method did

Link to comment
Share on other sites

is the combined script above correct?

The first thing that jumps out is you haven't put what you want to delete in the _shutdownInitiated function FileDelete("MyFile.txt") was an example you need to put all of the things you want to do before shutdown where I put the example fileDelete()

Func _ShutdownInitiated($hWndGUI, $MsgID, $WParam, $LParam)
    FileDelete("MyFile.txt");do whatever you need to do here
    Return True
EndFunc
Link to comment
Share on other sites

Hi jacKit and thanks ChrisL for the code and timely info on the OnAutoItExit problem,

I used grc.com's Wizmo.exe with the "shutdown!" option for a fast shutdown,

_ShutdownInitiated() function responds first.

normal gui exiting uses OnAutoItExit function

logoff or system shutdown is handled by message handler _ShutdownInitiated()

jacKit, I have an update to your code

a long AutoIt3ExecuteLine messagebox line will wrap in the codebox

so download the attachment below the code box.

; ////changelog////
;
; incorporates suggestions from Resnullius - Regwrite loop and ChrisL - WM_QUERYENDSESSION
; superfluous error handling removed, code cleaned up and simplified
;
; IsAdmin(): if user has admin privleges use HKEY_LOCAL_MACHINE RunOnce, so any logged in account after reboot will delete temp 
; otherwise user has Standard or Limited, local machine reg write not allowed, use HKEY_CURRENT_USER

; RunOnce instead of Run
; Run is now RunOnce, RunOnce reg keys are deleted by OS when command runs on startup
; so no delete needed in script for reg entry, also apparently MS says not good to delete reg keys in RunOnce by the very script
; launched by RunOnce, so thats good.

; User Temp Folder: @tempdir
; you may want to consider using the users Temp Folder: @tempdir = C:\DOCUME~1\usersname\LOCALS~1\Temp
; C:\Documents and Settings\usersname\Local Settings\Temp
; however it's good practice to not delete everything in the users temp folder (this is what some hard drive cleanup programs do)
; as some software uses the temp folder to store installers for repair installs or re-installing
; also software that has to install on boot can place its files here
; so any delete routine will have to target your own folder in the tempdir... just a suggestion.

; Open Files
; if there are any open file handles, either by running programs or by Explorer.exe then you can't delete those files or folders they are in
; so you need to confirm any programs launched by your script that have opened data files in your temp folder
; or if those programs are in your temp folder have closed before exiting your script, use ProcessExists, WinExist etc.

#include <File.au3>
; your includes here
;--------------------------------------------------------------------------------------------
; Edit these lines with your Path/Filenames/Commandline parameter name
Global Const $ClearTemp = "/cleartemp"                                                              ; Commandline parameter name used for RunOnce script run
Global Const $ProgScriptFolder = @ProgramFilesDir & "\YourScriptFolder\YourScript.exe /cleartemp"   ; RunOnce registry key path to script folder and script name
Global Const $ProgTempFolder = @ProgramFilesDir & "\YourTempFolder"                                 ; Path to Temp Folder
;Global Const $ProgTempFolder = @TempDir & "\YourTempFolder"                                        ; Path to Temp Folder - In Users Temp Dir
Global Const $RegkeyValue = "Auto Run Eater CleanUp"                                                ; Name for the RunOnce registry key
Local $msg,  $RegMsg = "RegDelete Result [1 OK]: ", $ExitCmdLine = 0, $cancel = 0, $count = 0, $timer = 0
If (Not IsDeclared("$WM_QUERYENDSESSION")) Then Global Const $WM_QUERYENDSESSION = 0x0011   ; Windows Message constant
;--------------------------------------------------------------------------------------------

Switch IsAdmin()
    Case 1 ; Use Local Machine Reg Key, allows any account on reboot to run script to delete temp folder
        Global $RegKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"     ; Registry Local_Machine "RunOnce" key
    Case 0 ; Use Current_User Reg Key, only runs script on reboot when current user account script was run on is logged on
        Global $RegKey = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"      ; Registry Current_User "RunOnce" key
EndSwitch
    
Opt('MustDeclareVars', 1)                 ; 0=no, 1=require pre-declare 
Opt("OnExitFunc","_Exit")                 ; "_Exit" called on Exit for MessageLoop Mode (GUIGetMsg)
;Opt("GUIOnEventMode", 1)                 ; if oneventmode used for gui
;GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit") ; "_Exit" called on Exit for OnEvent Mode GUI

_CMDLineParse()     ; place these two lines (in order shown) in your script after #includes, AutoItSetOption, and variables are declared

_RegWriteRunOnce()  ; schedule script temp folder delete on reboot, (removed from registry if "Exit" is normal and temp folder deleted)
; file copy here

; _RegWriteRunOnce() can be run with Optional timeout in seconds for the Dialog messagebox
; _RegWriteRunOnce() Returns user confirmation [1] or Optional unattended timeout [-1] e.g. $RegReturn = _RegWriteRunOnce(10)

GUIRegisterMsg($WM_QUERYENDSESSION, "_ShutdownInitiated"); place this line after GuiCreate

; bulk of your code here
;////////////////////////////////////////
; Replace with your message loop or oneventmode loop
While 1
    ; your messageloop code here
    $msg = GUIGetMsg()
    Switch $msg
        Case -3 ; $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd
;////////////////////////////////////////

; place these three functions at bottom of script
; ///////////////////////////////////////////////////////////////////////////////
Func _RegWriteRunOnce($timeout=-1) ; registry write for RunOnce at system startup for cleanup in case of system crash
; with user confirmation dialog for dealing with possible registry monitoring software
; Optional Dialog Timeout _RegWriteRunOnce(10) - run with 10 second dialog timeout

    If RegRead($RegKey, $RegkeyValue) <> $ProgScriptFolder Then    ; if reg entry already exists, skips this routine
        Local $regerror = @error
        Local $regApprove  = ""
        Local $delay = 5000
        Local $delayCount = 0
        Beep(1000,10) ; Subtle Attention Getter - more like 'Pip'
    
     Switch MsgBox(262144 + 4096 + 64 + 1, "PLEASE NOTE", 'Auto Run Eater is about to insert itself into the Windows Registry RunOnce Key' & @CRLF& @CRLF & _
             'If you are running certain Registry Monitoring software that some AntiSpyware or AntiVirus programs install' & @CRLF & _
             'you may be prompted to allow the addition of "'&$RegkeyValue&'" to the "RunOnce" key. ' & @CRLF & @CRLF & _
             'Please allow this change so that Auto Run Eater can be properly installed, otherwise Auto Run Eater will exit'  & @CRLF & @CRLF & _
             '"Click "OK" to continue, Cancel" will exit Auto Run Eater' & @CRLF & @CRLF & 'THANK YOU',$timeout)
        Case 1
            $regApprove = 1 ; user approved
        Case 2
            $cancel = 1
            Exit
        Case -1
            $regApprove = -1 ; user unattended timeout (if used)
     Endswitch
     RegWrite($RegKey, $RegkeyValue, "REG_SZ", $ProgScriptFolder) 
     Sleep(2000)
     While RegRead($RegKey, $RegkeyValue) = $ProgScriptFolder
            Sleep(500)
            $delayCount += 500
            If $delayCount = $delay Then ExitLoop
     WEnd
    
    $delayCount = 0
    
    ; after waiting 5 sec after reg entry
    ; if user cancels popup message from, or reg entry is automatically cancelled by third party software,  then next timeout runs messagebox followed by regwrite
    
     While Not RegRead($RegKey, $RegkeyValue) = $ProgScriptFolder
            Sleep(500)
            $delayCount += 500
            If $delayCount = $delay Then
                $cancel = 1
                Exit ; Exit if reg entry missing
            EndIf
     WEnd
            Return $regApprove
    EndIf
    Return 0
EndFunc ; _RegWriteRunOnce()
; ///////////////////////////////////////////////////////////////////////////////

; parse commandline options
Func _CMDLineParse() ; delete temp folder on reboot with /cleartemp commandline parameter, then exit script
    If IsArray($CmdLine) And $CmdLine[0] Then ; Delete files in temp folder
        Switch $CmdLine[1]
            Case $ClearTemp
                $ExitCmdLine = 1
                Exit ; normal exit function will do folder removal
        EndSwitch
    EndIf
    Return 0
EndFunc ; _CMDLineParse()

;  windows message handler WM_QUERYENDSESSION, handles unexpected shutdowns: user logoff or system shutdown
Func _ShutdownInitiated($hWndGUI, $MsgID, $WParam, $LParam) ; 4 parameters listed in function MUST remain although not used in this function
    ; Code Idea Author: ChrisL
    FileSetAttrib($ProgTempFolder & "\*.*", "-RSH",1)
    FileDelete($ProgTempFolder & "\*.*")
    DirRemove($ProgTempFolder, 1)       ; remove files and subdirectories under $ProgTempFolder, script paused until delete completes or fails
   
    Switch FileExists($ProgTempFolder)
        Case 0                          ; folder successfully deleted BEFORE system shutdown, so abort delete on reboot, remove RunOnce command
            $RegMsg &= RegDelete($RegKey, $RegkeyValue) ; Delete regkey for RunOnce of script
        Case 1
            FileDelete($ProgTempFolder & "\*.*")
            DirRemove($ProgTempFolder, 1)
            If Not FileExists($ProgTempFolder) Then RegDelete($RegKey, $RegkeyValue)
    EndSwitch
    _FileWriteLog(@ScriptDir & "\event.log","_ShutdownInitiated Exit Temp Folder Delete Successful: " & $RegMsg & @CRLF & @CRLF)
    ; write exit time, RegWrite Result
    Return True
EndFunc   ; _ShutdownInitiated

Func _Exit() ; Normal exit routine
    FileSetAttrib($ProgTempFolder & "\*.*", "-RSH",1)
    FileDelete($ProgTempFolder & "\*.*")
    DirRemove($ProgTempFolder, 1)       ; remove files and subdirectories under $ProgTempFolder, script paused until delete completes or fails
    
    Switch FileExists($ProgTempFolder)
        Case 0                          ; folder successfully deleted BEFORE system shutdown, so remove RunOnce delete on reboot command
            If Not $ExitCmdLine Then
                $RegMsg &= RegDelete($RegKey, $RegkeyValue)  ; Delete regkey for RunOnce of script
            EndIf
        Case 1
            FileDelete($ProgTempFolder & "\*.*")
            DirRemove($ProgTempFolder, 1)
            If Not FileExists($ProgTempFolder) And Not $ExitCmdLine Then
                $RegMsg &= RegDelete($RegKey, $RegkeyValue) 
            EndIf
    EndSwitch
    _FileWriteLog(@ScriptDir & "\event.log","Exit Temp Folder Delete Successful: "& $RegMsg & @CRLF & @CRLF)
    ; write exit time, RegWrite Result
    Beep(1000,10) ; Subtle Attention Getter - more like 'Pip'
    ;////////////////////////
    ; THIS LINE WILL WRAP IN THE FORUM CODE BOX, SO YOU NEED TO REMOVE LINEBREAKS IN SCITE
    ; AutoIt3ExecuteLine of code to display after your script has exited, 15 sec timeout reminding user to permit any regmon popup dialog
    If Not $ExitCmdLine And Not $cancel Then
        Run(@AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(64+4096,''Auto Run Eater Is Exiting'',''Please permit any popup prompt from your registry monitor program''&@LF&''so that the RunOnce key can be removed''&@LF&@LF&''THANK YOU'',15)"')
    EndIf
    ;////////////////////////
EndFunc   ; _Exit
Edited by rover

I see fascists...

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...