Jump to content

Restart on exit


Recommended Posts

  • Moderators

I have been searching the forum, but have yet to come up with the right answer. I have a customer request to create a simple tooltip in the system tray. The code itself is very simple:

#NoTrayIcon
Opt("TrayAutoPause", 1)
Opt("TrayMenuMode", 1)
TrayCreateItem("Account: " & @UserName)
TrayCreateItem("Hostname: " & @ComputerName)
TrayCreateItem("Domain: " & @LogonDomain)
TrayCreateItem("Resolution: " & @DesktopWidth & "x" & @DesktopHeight)
TrayCreateItem("")
$aboutItem  = TrayCreateItem("About")
TraySetState()
TraySetToolTip("Helpdesk Utility")
While 1
    $msg = TrayGetMsg()
    Select
        Case $msg = 0
            ContinueLoop
        Case $msg = $aboutItem
            Msgbox(64,"About","Helpdesk Tooltip Utility" & @CRLF & "Version 0.1b, February 2012")
    EndSelect
WEnd
Exit

Through some typical management paranoia, the customer is looking for a way to ensure the tooltip is not closed. The tooltip has no exit option, but someone could theoretically close it through the Task Manager. I have been asked to come up with a way to have it relaunch if it is closed.

Thus far, I have been able to get the code below to work with an OnAutoItExitRegister call that creates a temp file to call the main executable. Just wondering if there is an easier, more elegant way of doing it that I'm missing.

#include <File.au3>
OnAutoItExitRegister("restart")
MsgBox(0, "", "Test")
Func restart()
$var = FileOpen(@TempDir & "restart.txt", 9)
FileWriteLine($var, "wscript.sleep(1000)")
FileWriteLine($var, "dim filesys")
FileWriteLine($var, 'set shell = WScript.CreateObject("WScript.Shell")')
FileWriteLine($var, 'pgm = "tooltip.exe"')
FileWriteLine($var, 'shell.Run pgm')
FileWriteLine($var, 'Set filesys = CreateObject("Scripting.FileSystemObject")')
FileWriteLine($var, 'filesys.DeleteFile "' & @TempDir & 'restart.vbs"')
FileClose($var)
FileMove(@TempDir & "restart.txt", @TempDir & "restart.vbs", 1)
Sleep(500)
ShellExecute("cscript.exe", @TempDir & "restart.vbs", "", "", @SW_HIDE)
EndFunc
Edited by JLogan3o13

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

Maybe this will help:

#Region Header
#cs
    Title:        Restart script UDF Library for AutoIt3
    Filename:      Restart.au3
    Description:    Accurate restarting the script (AU3 or EXE)
    Author:      Yashied
    Version:        1.0
    Requirements:   AutoIt v3.3 +, Developed/Tested on WindowsXP Pro Service Pack 2
    Uses:          None
    Notes:        The library uses OnAutoItStart() function
    Available functions:
    _ScriptRestart
    Example:
        #NoTrayIcon
        #Include <Misc.au3>
        #Include <Restart.au3>
        _Singleton('MyProgram')
        If MsgBox(36, 'Restarting...', 'Press OK to restart this script.') = 6 Then
            _ScriptRestart()
        EndIf
#ce
#Include-once
#OnAutoItStartRegister "OnAutoItStart"
#EndRegion Header
#Region Local Variables and Constants
Global $__Restart = False
#EndRegion Local Variables and Constants
#Region Public Functions
; #FUNCTION# ====================================================================================================================
; Name...........: _ScriptRestart
; Description....: Initiates a restart of the current script.
; Syntax.........: _ScriptRestart ( [$fExit] )
;                 $fExit  - Specifies whether terminates the current script, valid values:
;                 |TRUE   - Terminates script. (Default)
;                 |FALSE  - Does not terminates script.
; Return values..: Success - 1 ($fExit = TRUE)
;                 Failure - 0 and sets the @error flag to non-zero.
; Author.........: Yashied
; Modified.......:
; Remarks........:
; Related .......:
; Link...........:
; Example........: Yes
; ===============================================================================================================================
Func _ScriptRestart($fExit = 1)
Local $Pid
If Not $__Restart Then
  If @compiled Then
   $Pid = Run(@ScriptFullPath & ' ' & $CmdLineRaw, @ScriptDir, Default, 1)
  Else
   $Pid = Run(@AutoItExe & ' "' & @ScriptFullPath & '" ' & $CmdLineRaw, @ScriptDir, Default, 1)
  EndIf
  If @error Then
   Return SetError(@error, 0, 0)
  EndIf
  StdinWrite($Pid, @AutoItPID)
;  If @error Then
;
;  EndIf
EndIf
$__Restart = 1
If $fExit Then
  Sleep(50)
  Exit
EndIf
Return 1
EndFunc   ;==>_ScriptRestart
#EndRegion Public Functions
#Region OnAutoItStart
Func OnAutoItStart()
Sleep(50)
Local $Pid = ConsoleRead(1)
If @extended Then
  While ProcessExists($Pid)
   Sleep(100)
  WEnd
EndIf
EndFunc   ;==>OnAutoItStart
#EndRegion OnAutoItStart

It's the restart script by Yashied - I use it.

/edit:

Forgot to add the file and source.

Original link:

Restart.au3

Edited by VixinG

[indent=3][/indent]

Link to comment
Share on other sites

VixinG,

In cases such as this it's always best to link to the forum post instead of reduplicating code, because overtime old code becomes scattered around the forum.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

Hi, Emiel. This would not work on a machine without AutoIt installed though, would it? This tooltip will be placed on 5000+ machines, so it needs to be a stand-alone solution.

Edit: My apologies, Emiel, I was apparently ignorant of @AutoitExe and how it works. I tried this out, and it does the job fine (in one line, no less) if the executable closes in a "normal" fashion. The customer also wants it to restart if the process is killed, but I don't seen any option for that beyond a second script to watch the first, or bundling the executable as a Windows service.

Thanks again, Emiel. Learn something new every day :)

Edited by JLogan3o13

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

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