Snippets ( AutoIt ): Difference between revisions

From AutoIt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 217: Line 217:
     Return $sReturn
     Return $sReturn
EndFunc  ;==>_FunctionSort
EndFunc  ;==>_FunctionSort
</syntaxhighlight>
[[#top | ReturnToContents]]
== _IsBeta ==
{{Snippet Header
| AuthorURL = 10673-mlipok
| AuthorName = mLipok
}}
<syntaxhighlight lang="autoit">
#include <Array.au3>
#include <MsgBoxConstants.au3>
Example()
Func Example()
    Local $aTest[10]
    _ArrayUnique($aTest, 0, 5)
    Local $iError = @error
    ConsoleWrite('$iError = ' & $iError & @CRLF)
    If _IsBeta() Then
        If $iError = 3 Then
            MsgBox($MB_SYSTEMMODAL, '@error', '3 - $iBase or $iCase contains an invalid value' & @CRLF & @AutoItVersion)
        EndIf
    Else
        If $iError = 2 Then
            MsgBox($MB_SYSTEMMODAL, '@error', '2 - $iBase or $iCase contains an invalid value' & @CRLF & @AutoItVersion)
        EndIf
    EndIf
EndFunc  ;==>Example
Func _IsBeta()
      Return Mod(StringSplit(@AutoItVersion, '.')[3], 2) == 1
EndFunc  ;==>_IsBeta
</syntaxhighlight>
</syntaxhighlight>



Revision as of 06:27, 20 June 2014


Please always credit an author in your script if you use their code. It is only polite.


AutoItWinShow

Author: guinness








#include <GUIConstantsEx.au3>

Example()

Func Example()
    ; Display AutoIt's Hidden Window. See AutoItWinGetTitle and AutoItWinSetTitle for more details.
    AutoItWinShow()

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
        EndSwitch
    WEnd
EndFunc   ;==>Example

; Display AutoIt's Hidden Window. Returns the handle of the window.
Func AutoItWinShow()
    Local Const $hWnd = WinGetHandle(AutoItWinGetTitle()) ; Get the handle of the AutoIt Hidden Window by finding out the title of the AutoIt Hidden Window.
    WinMove($hWnd, '', (@DesktopWidth / 2) - 250, (@DesktopHeight / 2) - 250, 500, 500) ; Move the AutoIt Hidden Window and re-size for a better view of the data that will be set.
    WinSetState($hWnd, '', @SW_SHOW) ; Show the AutoIt Hidden Window, normally this is hidden, but in the interest of this example I'm displaying it.
    Return $hWnd
EndFunc   ;==>AutoItWinShow

ReturnToContents

AutoItWinGetText

Author: guinness








Example()

Func Example()
    ; Display AutoIt's Hidden Window. See AutoItWinGetTitle and AutoItWinSetTitle for more details.
    AutoItWinShow()

    ; Add a text string to AutoIt's Hidden Window. Compile to see the text in AutoIt's Hidden Window.
    AutoItWinSetText('Welcome to AutoIt V' & @AutoItVersion & @CRLF)

    ; Add a text string to AutoIt's Hidden Window. Compile to see the text in AutoIt's Hidden Window.
    AutoItWinSetText('Windows Type: ' & @OSType & @CRLF)

    ; Display the text stored in AutoIt's Hidden Window.
    MsgBox(4096, '', AutoItWinGetText())

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
        EndSwitch
    WEnd
EndFunc   ;==>Example

; Retrieve the text in AutoIt's Hidden Window.
Func AutoItWinGetText()
    Local Const $hWnd = WinGetHandle(AutoItWinGetTitle()) ; Get the handle of the AutoIt Hidden Window by finding out the title of the AutoIt Hidden Window.
    Return ControlGetText($hWnd, '', ControlGetHandle($hWnd, '', 'Edit1'))
EndFunc   ;==>AutoItWinGetText

; Add text to AutoIt's Hidden Window.
Func AutoItWinSetText($sString)
    Local Const $hWnd = WinGetHandle(AutoItWinGetTitle()) ; Get the handle of the AutoIt Hidden Window by finding out the title of the AutoIt Hidden Window.
    Return ControlSetText($hWnd, "", ControlGetHandle($hWnd, "", 'Edit1'), ControlGetText($hWnd, '', ControlGetHandle($hWnd, '', 'Edit1')) & $sString)
EndFunc   ;==>AutoItWinSetText

; Display AutoIt's Hidden Window. Returns the handle of the window.
Func AutoItWinShow()
    Local Const $hWnd = WinGetHandle(AutoItWinGetTitle()) ; Get the handle of the AutoIt Hidden Window by finding out the title of the AutoIt Hidden Window.
    WinMove($hWnd, '', (@DesktopWidth / 2) - 250, (@DesktopHeight / 2) - 250, 500, 500) ; Move the AutoIt Hidden Window and re-size for a better view of the data that will be set.
    WinSetState($hWnd, '', @SW_SHOW) ; Show the AutoIt Hidden Window, normally this is hidden, but in the interest of this example I'm displaying it.
    Return $hWnd
EndFunc   ;==>AutoItWinShow

ReturnToContents

_DockToWindow

Author: guinness








#include <GUIConstantsEx.au3>
#include <WinAPI.au3>
#include <WindowsConstants.au3>

If (Not ProcessExists("SciTE.exe")) Then
    Exit MsgBox(4096, '', "Please start SciTE.exe")
EndIf

Example()

Func Example()
    ; Create a GUI, similar to SciTE Jump's GUI.
    Local Const $hGUI = GUICreate('', 215, 400, -1, -1, BitOR($GUI_SS_DEFAULT_GUI, $WS_MAXIMIZEBOX, $WS_SIZEBOX))

    GUISetState(@SW_SHOWNORMAL, $hGUI)

    ; Dock the first window to left and adjust the width based on the width of the second GUI.
    _DockToWindow(WinGetHandle("[CLASS:SciTEWindow]"), $hGUI)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
        EndSwitch
    WEnd

    GUIDelete($hGUI)
EndFunc   ;==>Example

Func _DockToWindow(Const $hHandle_1, Const $hHandle_2)
    ; Retrieve the working area, this is minus the taskbar dimensions so slightly different to @DesktopHeight and @DesktopWidth which is the
    ; monitors height and width.
    Local Const $SPI_GETWORKAREA = 48
    Local Const $tWorkArea = DllStructCreate($tagRECT)
    _WinAPI_SystemParametersInfo($SPI_GETWORKAREA, 0, DllStructGetPtr($tWorkArea))

    ; Retieve the position of the second GUI.
    Local Const $aClientSize_2 = WinGetPos($hHandle_2)

    ; Set the state of the windows to 'Restore'.
    WinSetState($hHandle_1, '', @SW_RESTORE)
    WinSetState($hHandle_2, '', @SW_RESTORE)

    ; Move the first to the far left of the screen and adjust the width to the total screen width minus the width of the second GUI. e.g. 1366 - 215
    WinMove($hHandle_1, '', DllStructGetData($tWorkArea, 'Left'), DllStructGetData($tWorkArea, 'Top'), DllStructGetData($tWorkArea, 'Right') - DllStructGetData($tWorkArea, 'Left') - $aClientSize_2[2], DllStructGetData($tWorkArea, 'Bottom') - DllStructGetData($tWorkArea, 'Top'))

    ; Move the second window to the far right in between the remaining space and adjust the height of the GUI.
    WinMove($hHandle_2, '', DllStructGetData($tWorkArea, 'Right') - DllStructGetData($tWorkArea, 'Left') - $aClientSize_2[2], DllStructGetData($tWorkArea, 'Top'), $aClientSize_2[2], DllStructGetData($tWorkArea, 'Bottom') - DllStructGetData($tWorkArea, 'Top'))
EndFunc   ;==>_DockToWindow

ReturnToContents

_FuncExists

Author: GEOSoft








MsgBox(0, "TEST", "Function Exists = " & _FuncExists("_FuncExists", @ScriptFullPath))

Func _FuncExists($sFunc, $sPath)
   If Not FileExists($sPath) Then Return SetError(1)
   Local Const $sStr = FileRead($sPath)
   Local Const $sRegEx = "(?i)(?m:^|\n)\s*Func\s+(" & $sFunc & ")\s*\("
   Local Const $aRegEx = StringRegExp($sStr, $sRegEx, 1)
   If IsArray($aRegEx) Then Return 1
   Return 0
EndFunc

ReturnToContents

_FunctionSort

Author: guinness








; Get the list of Functions in a script and sort by alphabetical order.

#include <Array.au3>
#include <String.au3>

Local $sFile = FileOpenDialog(@ScriptName, "Select an AutoIt file.", "Au3 (*.au3)")

If @error Then
    Exit
EndIf
ClipPut(_FunctionSort($sFile))

Func _FunctionSort($sFilePath)
    Local Const $sRead = FileRead($sFilePath)

	Local $aReturn = StringRegExp("Func _Count()" & @CRLF & "EndFunc ;==>_Count" & $sRead, '(?s)(?i)Func(.*?)EndFunc', 3)

    If @error Then
        Return SetError(1, 0, 0)
    EndIf

    $aReturn[0] = UBound($aReturn, 1) - 1

    _ArraySort($aReturn, 0, 1)

    Local $sReturn

    For $A = 1 To $aReturn[0]
        $sReturn &= "Func" & $aReturn[$A] & "EndFunc" & @CRLF & @CRLF
    Next

    Return $sReturn
EndFunc   ;==>_FunctionSort

ReturnToContents

_IsBeta

Author: mLipok








#include <Array.au3>
#include <MsgBoxConstants.au3>

Example()

Func Example()
    Local $aTest[10]
    _ArrayUnique($aTest, 0, 5)
    Local $iError = @error
    ConsoleWrite('$iError = ' & $iError & @CRLF)
    If _IsBeta() Then
        If $iError = 3 Then
            MsgBox($MB_SYSTEMMODAL, '@error', '3 - $iBase or $iCase contains an invalid value' & @CRLF & @AutoItVersion)
        EndIf
    Else
        If $iError = 2 Then
            MsgBox($MB_SYSTEMMODAL, '@error', '2 - $iBase or $iCase contains an invalid value' & @CRLF & @AutoItVersion)
        EndIf
    EndIf
EndFunc   ;==>Example

Func _IsBeta()
       Return Mod(StringSplit(@AutoItVersion, '.')[3], 2) == 1
EndFunc   ;==>_IsBeta

ReturnToContents

_IsButton

Author: guinness








#include <ButtonConstants.au3>
#include <Constants.au3>
#include <WinAPI.au3>

Example()

Func Example()
    Local Const $hGUI = GUICreate('')
    Local Const $iLabel = GUICtrlCreateButton('', 0, 0, 50, 50)
    Local Const $iCheckbox = GUICtrlCreateCheckbox('', 0, 0, 100, 20) ; This is considered a 'Button' by _WinAPI_GetClassName too.

    GUISetState(@SW_SHOWNORMAL, $hGUI)

    MsgBox(4096, '', 'AutoIt Button ID: ' & _IsButton($iLabel) & @CRLF & _
            'AutoIt Button Handle: ' & _IsButton(GUICtrlGetHandle($iLabel)) & @CRLF & _
            'AutoIt Checkbox ID: ' & _IsButton($iCheckbox) & @CRLF & _
            'AutoIt Checkbox Handle: ' & _IsButton(GUICtrlGetHandle($iCheckbox)) & @CRLF)

    Return GUIDelete($hGUI)
EndFunc   ;==>Example

; Check if a variable is referencing a Button control.
Func _IsButton($hWnd)
    If IsHWnd($hWnd) = 0 Then
        $hWnd = GUICtrlGetHandle($hWnd)
    EndIf

    Local Const $sClassName = _WinAPI_GetClassName($hWnd)

    If $sClassName = 'Button' Then
        Local Const $aStyle[5] = [4, $BS_CHECKBOX, $BS_AUTOCHECKBOX, $BS_RADIOBUTTON, $BS_AUTORADIOBUTTON]

        Local Const $iLong = _WinAPI_GetWindowLong($hWnd, $GWL_STYLE)

		For $i = 1 To $aStyle[0]
            If BitAND($iLong, $aStyle[$i]) = $aStyle[$i] Then
                Return False
            EndIf
        Next

        Return True
    EndIf

    Return False
EndFunc   ;==>_IsButton

ReturnToContents

_IsControlID

Author: guinness








; Check if a Control ID is a native AutoIt control.

#include <GUIListView.au3>
#include <WinAPI.au3>

Example()

Func Example()
    Local Const $hGUI = GUICreate('')
    Local Const $iControlID = GUICtrlCreateLabel('', 0, 0, 500, 500)
    Local Const $hListView = _GUICtrlListView_Create($hGUI, 'Example', 0, 0, 500, 500)

	GUISetState(@SW_SHOWNORMAL, $hGUI)

    MsgBox(4096, '', 'AutoIt ControlID: ' & _IsControlID($iControlID) & @CRLF & _
            'Random Number: ' & _IsControlID(Random(42, 99, 1)) & @CRLF & _
            'AutoIt ControlID Handle: ' & _IsControlID(GUICtrlGetHandle($iControlID)) & @CRLF & _
            'ListView UDF Handle: ' & _IsControlID($hListView) & @CRLF & _
            'ListView UDF Handle: ' & _IsControlID(GUICtrlGetHandle($hListView)) & @CRLF)

    _GUICtrlListView_Destroy($hListView)

    Return GUIDelete($hGUI)
EndFunc   ;==>Example

Func _IsControlID($iControlID)
    If IsHWnd($iControlID) Then
        $iControlID = _WinAPI_GetDlgCtrlID($iControlID)
    EndIf

    Return IsHWnd(GUICtrlGetHandle($iControlID)) = 1
EndFunc   ;==>_IsControlID

ReturnToContents

_GetAutoItIncludesFromSciTE

Author: guinness








#include <WinAPIEx.au3>

ConsoleWrite(_GetAutoItIncludesFromSciTE() & @CRLF)

; Retrieve the AutoIt includes path from the SciTE process.
Func _GetAutoItIncludesFromSciTE()
    Local $sRelativePath = '..\Include'
	Local Const $sWorkingDir = @WorkingDir
    FileChangeDir(_WinAPI_PathRemoveFileSpec(_WinAPI_GetProcessFileName(ProcessExists('SciTE.exe'))))
    $sRelativePath = _WinAPI_GetFullPathName($sRelativePath)
    FileChangeDir($sWorkingDir)
    Return _WinAPI_PathRemoveBackslash($sRelativePath)
EndFunc   ;==>_GetAutoItIncludesFromSciTE

ReturnToContents

_GetAutoItInstall

Author: guinness








; Get the AutoIt installation folder.

ConsoleWrite(_GetAutoItInstall() & @CRLF)

Func _GetAutoItInstall()
    Return StringLeft(@AutoItExe, StringInStr(@AutoItExe, "\", 2, -1) - 1)
EndFunc   ;==>_GetAutoItInstall

ReturnToContents

_GetAutoItInstallEx

Author: guinness








ConsoleWrite(_GetAutoItInstallEx() & @CRLF)

; Get the installation of AutoIt. An improved version of _GetAutoItInstall.
Func _GetAutoItInstallEx()
    Local $aWow6432Node[2] = ['', 'Wow6432Node\'], $aFiles[4] = [3, @ProgramFilesDir, EnvGet("PROGRAMFILES"), EnvGet("PROGRAMFILES(X86)")]
    Local $sFilePath = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\' & $aWow6432Node[@AutoItX64] & 'AutoIt v3\AutoIt\', 'InstallDir')
    If @error Then
        For $A = 1 To $aFiles[0]
            $aFiles[$A] &= '\AutoIt'
            If FileExists($aFiles[$A]) Then
                Return $aFiles[$A]
            EndIf
        Next
        Return SetError(1, 0, '')
    Else
        Return $sFilePath
    EndIf
EndFunc   ;==>_GetAutoItInstallEx

ReturnToContents

_GetAutoItInstallFromSciTE

Author: guinness








ConsoleWrite(_GetAutoItInstallFromSciTE() & @CRLF)

; Retrieve the AutoIt installation path from the SciTE process.
Func _GetAutoItInstallFromSciTE()
    Local $sRelativePath = '..\', $sWorkingDir = @WorkingDir
    FileChangeDir( _WinAPI_PathRemoveFileSpec(_WinAPI_GetProcessFileName(ProcessExists("SciTE.exe"))))
    $sRelativePath = _WinAPI_GetFullPathName($sRelativePath)
    FileChangeDir($sWorkingDir)
    Return _WinAPI_PathRemoveBackslash($sRelativePath)
EndFunc   ;==>_GetAutoItInstallFromSciTE

ReturnToContents

_GetClasses

Author: CyberSlug








; Get ALL Controls Info

Example()

Func Example()
	; Run Calculator
	Run("calc.exe")

	; Wait 10 seconds for the Calculator window to appear.
	Local const $hWnd = WinWait("[CLASS:CalcFrame]", '', 10)

	; Retrieve a list of all the controls in the Calculator window using the handle returned by WinWait.
	MsgBox(4096, '', _GetClasses($hWnd))

	; Close the Calculator window using the handle returned by WinWait.
	WinClose($hWnd)
EndFunc   ;==>Example

; This function returns an @LF-separated list of controls on the specified window.
Func _GetClasses($sTitle, $sText = '')
	Local $iCount_Button = 0, $iCount_Edit = 0, $iCount_Static = 0
	Local $aClasses = StringSplit(WinGetClassList($sTitle, $sText), @LF)
	Local $aClassID[$aClasses[0] + 1] = [$aClasses[0]]

	For $i = 1 To $aClasses[0]
		Select
			Case $aClasses[$i] = "Button"
				$iCount_Button += 1
				$aClassID[$i] = $aClasses[$i] & $iCount_Button
			Case $aClasses[$i] = "Edit"
				$iCount_Edit += 1
				$aClassID[$i] = $aClasses[$i] & $iCount_Edit
				$aClasses[$i] = "Input"
			Case $aClasses[$i] = "Static"
				$iCount_Static += 1
				$aClassID[$i] = $aClasses[$i] & $iCount_Static
				$aClasses[$i] = "Label"
			Case Else
				If $aClasses[$i] <> "" Then
					$aClassID[$i] = $aClasses[$i] & "?"
				EndIf
		EndSelect
	Next

	; Combine the results.
	Local $sReturn = ""

	For $i = 1 To $aClassID[0]
		$sReturn &= $aClassID[$i] & @LF
	Next

	Return $sReturn
EndFunc   ;==>_GetClasses

ReturnToContents

_GetFile

Author: guinness








; FileRead Alternative

Func _GetFile($sFile, $iFormat = 0)
    Local $hFileOpen = FileOpen($sFile, $iFormat)
    If $hFileOpen = -1 Then
        Return SetError(1, 0, "")
    EndIf
    Local $sData = FileRead($hFileOpen)
    FileClose($hFileOpen)
    Return $sData
EndFunc   ;==>_GetFile

ReturnToContents

_GetTitle

Author: guinness








; Get the title of your program.

ConsoleWrite(_GetTitle('Example') & @CRLF)
; The second parameter would normally be @ScriptDir & '\Uninstall.exe' for example, but for this demonstration I'm using the full path.
ConsoleWrite(_GetTitle('Example', @ScriptFullPath) & @CRLF)

Func _GetTitle($sProgramName, $sInstallPath = '')
    Local $aOSArch[2] = ['', ' (64-bit)'], $aPortable[2] = [' (Portable)', '']
    Return $sProgramName & $aOSArch[@AutoItX64] & $aPortable[FileExists($sInstallPath)]
EndFunc   ;==>_GetTitle

ReturnToContents

_GetXML

Author: guinness








; Simple Way Of Parsing XML Data.

#include <Array.au3>

Global $aReturn, $sXMLData

$sXMLData = "<data>This is a Simple example of XML</data><data>This is a Simple example of XML and is the Second String.</data>"
$aReturn = _GetXML($sXMLData, "data")
_ArrayDisplay($aReturn, "_GetXML()")

Func _GetXML($sString, $sData)
    Local $aError[2] = [1, $sString], $aReturn
    $aReturn = StringRegExp('<' & $sData & '></' & $sData & '>' & $sString, '(?s)(?i)<' & $sData & '>(.*?)</' & $sData & '>', 3)
    If @error Then
        Return SetError(1, 0, $aError)
    EndIf
    $aReturn[0] = UBound($aReturn, 1) - 1
    Return SetError(0, 0, $aReturn)
EndFunc   ;==>_GetXML

ReturnToContents

Include Source With Exe

Author: JLogan3o13








;recover source .au3 file with /Extract switch
; The above code would be copied into the top of your script. The source location (C:\Test.au3 in my example) is the full path to your script file.
;Once compiled, if you run the script from the Run line with the /Extract switch, it will extact the original .au3 file into the Temp directory and will exit without actually executing the script.
If StringInStr($cmdlineRaw, "/Extract") Then
	FileInstall("C:\Test.au3", @TempDir & "\Test.au3", 1)
	Exit
EndIf

ReturnToContents

_IsANSIFile

Author: guinness








#include <FileConstants.au3>

ConsoleWrite(_IsANSIFile(@ScriptFullPath) & @LF) ; Returns True.

Func _IsANSIFile($sFilePath)
    Return FileGetEncoding($sFilePath) = $FO_READ
EndFunc   ;==>_IsUnicodeFile

ReturnToContents

_IsUnicodeFile

Author: guinness








#include <FileConstants.au3>

ConsoleWrite(_IsUnicodeFile(@ScriptFullPath) & @LF) ; Returns False.

Func _IsUnicodeFile($sFilePath)
    Return FileGetEncoding($sFilePath) = $FO_UNICODE
EndFunc   ;==>_IsUnicodeFile

ReturnToContents

_IsAu3File

Author: guinness








ConsoleWrite(_IsAu3File(@AutoItExe) & @CRLF)
ConsoleWrite(_IsAu3File(@ScriptFullPath) & @CRLF)

; Checks whether the filepath is an au3 file.
Func _IsAu3File($sFilePath)
    Return StringTrimLeft($sFilePath, StringInStr($sFilePath, ".", 2, -1)) = "au3"
EndFunc   ;==>_IsAu3File

ReturnToContents

_IsDefault

Author: guinness








If _IsDefault(Default) Then
    MsgBox(0, "_IsDefault() - 1", "This was a Default variable.")
EndIf

If _IsDefault(-1) Then
    MsgBox(0, "_IsDefault() - 2", "This was a Default variable.")
EndIf

If _IsDefault("Other") Then
    MsgBox(0, "_IsDefault() - 3", "This was a Default variable.")
EndIf

Func _IsDefault($sDefault)
    Return StringRegExp($sDefault, "(?-i)\s|Default|-1|0")
EndFunc   ;==>_IsDefault

ReturnToContents

_IsInTrial

Author: guinness








#include <Date.au3> ; Required for _DateDiff()

ConsoleWrite('Date trial started: ' & @YEAR & '/' & @MON & '/01' & @CRLF & _
        'Today''s date: ' & @YEAR & '/' & @MON & '/' & @MDAY & @CRLF & _
        'Trial period: 30 days' & @CRLF & _
        'Is the trial period still valid: ' & _IsInTrial(@YEAR & '/' & @MON & '/01', 30) & @CRLF)

; Check if a trial period date is still valid.
Func _IsInTrial($sDateString, $iDays) ; Based on the idea found here: http://www.autoitscript.com/forum/topic/...ial-time/page__view__findpost_
    Return (_DateDiff('D', $sDateString, @YEAR & '/' & @MON & '/' & @MDAY) < $iDays)
EndFunc   ;==>_IsInTrial

ReturnToContents

_IsVisible

Author: guinness








; Check if the Notepad Window is visible.

Example()

Func Example()
    ; Run Notepad
    Run("notepad.exe")

    ; Wait 10 seconds for the Notepad window to appear.
    Local $hWnd = WinWait("[CLASS:Notepad]", "", 10)

    ; Check if the Notepad window is visible and display the appropriate message box.
    If _IsVisible($hWnd) Then
        MsgBox(4096, "", "Notepad is visible.")
    Else
        MsgBox(4096, "", "Notepad isn't visible.")
    EndIf

    ; Close the Notepad window using the handle returned by WinWait.
    WinClose($hWnd)
EndFunc   ;==>Example

; Check if the window is visible.
Func _IsVisible($hWnd)
    Return BitAND(WinGetState($hWnd), 2) = 2
EndFunc   ;==>_IsVisible

ReturnToContents

Open Help File to Desired Page

Author: GaryFrost








; Open help file / Open a desired page

Global Const $sAutoItPath = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\AutoIt v3\AutoIt", "InstallDir")

Run(@WindowsDir & "\hh.exe " & $sAutoItPath & "\AutoIt3.chm::/html/functions/GUICtrlCreateUpdown.htm")

ReturnToContents

_RunAU3

Author: guinness








_RunAU3("AU3_Example.txt", '"This is a commandline example!"')

Func _RunAU3($sFilePath,  $sCommandLine = "", $sWorkingDir = "", $iShowFlag = @SW_SHOW, $iOptFlag = 0)
    Return Run('"' & @AutoItExe & '" /AutoIt3ExecuteScript "' & $sFilePath & '" ' & $sCommandLine, $sWorkingDir, $iShowFlag, $iOptFlag)
EndFunc   ;==>_RunAU3

Func _RunWaitAU3($sFilePath, $sCommandLine = "", $sWorkingDir = "", $iShowFlag = @SW_SHOW, $iOptFlag = 0)
    Local $iPID
    $iPID = RunWait('"' & @AutoItExe & '" /AutoIt3ExecuteScript "' & $sFilePath & '" ' & $sCommandLine, $sWorkingDir, $iShowFlag, $iOptFlag)
    If @error Then
        Return SetError(@error, 1, 0)
    EndIf
    Return $iPID
EndFunc   ;==>_RunWaitAU3

ReturnToContents

Run Any au3 File From Your Program

Author: Valuater








; Run Any Au3 File From Your Program

Global Const $sFilePath = @ScriptDir & "\Test.au3"

If @Compiled Then
	Global Const $sFileExe = FileGetShortName(@AutoItExe & ' /AutoIt3ExecuteScript "' & $sFilePath & '"')
	Run($sFileExe)
Else
	Global Const $sFileAu3 = FileGetShortName($sFilePath)
	Run(@AutoItExe & " " & $sFileAu3, "", @SW_HIDE)
EndIf

ReturnToContents

_ScriptName

Author: guinness








ConsoleWrite(_ScriptName() & @CRLF)

; Return the @ScriptName minus the .exe or .au3 extension.
Func _ScriptName()
	Return StringLeft(@ScriptName, StringInStr(@ScriptName, '.', 2, -1) - 1)
EndFunc   ;==>_ScriptName

ReturnToContents

_ScriptVersion

Author: MilesAhead








#NoTrayIcon

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Res_Fileversion=1.2.3.4
#AutoIt3Wrapper_Res_LegalCopyright=2012  www.favessoft.com
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

Global $version = _ScriptVersion()

Global $msg = "ScriptVerDemo" & " " & $version & "  Copyright (c) 2012  www.favessoft.com" & @CRLF & @CRLF

MsgBox(0x1040, "", $msg)

; return File Version string from compiled or .au3 script
; returns "" if no version info available
; Note: The .au3 script must contain #AutoItWrapper
; directives with file version or "" is returned.
Func _ScriptVersion(Const $Script = @ScriptFullPath)
    If StringRight($Script,4) = ".exe" Then
        Return FileGetVersion($Script)
    Else
        Local Const $scriptHandle = FileOpen($Script)
		Local $ver
		Local $found = False
		Local $pos

        If $scriptHandle <> -1 Then
            Do
                $ver = FileReadLine($scriptHandle)
                $sPos = StringInStr($ver, "_Fileversion=")

                If $sPos Then
                    $ver = StringMid($ver, $sPos + StringLen("_Fileversion="))
                    $found = True
                    ExitLoop
                EndIf
            Until StringLeft($ver, 1) <> "#"

            FileClose($scriptHandle)
        EndIf
    EndIf

    If Not $found Then $ver = ""

    Return $ver
EndFunc   ;==>_ScriptVersion

ReturnToContents

_SetFile

Author: guinness








; FileWrite Alternative

Func _SetFile(Const $sString, Const $sFile, Const $iOverwrite = 0)
    Local Const $hFileOpen = FileOpen($sFile, $iOverwrite + 1)

    FileWrite($hFileOpen, $sString)
    FileClose($hFileOpen)

    If @error Then
        Return SetError(1, 0, $sString)
    EndIf

    Return $sString
EndFunc   ;==>_SetFile

ReturnToContents

_ShowHelp

Author: Chimaera








HotKeySet("{F1}", "_ShowHelp")

Func _ShowHelp()
	Return ShellExecute(@ProgramFilesDir & "\AutoIt3\AutoIt3Help.exe") ; change this to the location of your own helpfile.
EndFunc   ;==>_ShowHelp

ReturnToContents

_SingletonPID

Author: guinness








Local $iSingleton = _SingletonPID('RandomName', 1)

If $iSingleton = 0 Then
    MsgBox(4096, '', 'This is the first instance of the program running: ' & $iSingleton)
Else
    MsgBox(4096, '', 'There is another instance running. This PID is: ' & $iSingleton)
EndIf

; #FUNCTION# ====================================================================================================================
; Name ..........: _SingletonPID
; Description ...: Enforce a design paradigm where only one instance of the script may be running.
; Syntax ........: _SingletonPID($sOccurenceName[, $iFlag = 0])
; Parameters ....: $sOccurenceName      - String to identify the occurrence of the script.
;                  $iFlag               - [optional] Optional parameters. Default is 0.
;                  0 - Exit the script with the exit code -1 if another instance already exists.
;                  1 - Return the PID of the main executable and without exiting the script too.
; Return values .: Success - 0 No other process is running.
;                  Failure - The PID of the main executable.
; Author ........: guinness with initial ideas by Valik for _Singleton & KaFu for _EnforceSingleInstance.
; Example .......: Yes
; ===============================================================================================================================
Func _SingletonPID(Const $sOccurenceName, Const $iFlag = 0)
    Local $hHandle = WinGetHandle($sOccurenceName)

    If @error Then
        AutoItWinSetTitle($sOccurenceName)
        $hHandle = WinGetHandle($sOccurenceName)
        ControlSetText($hHandle, '', ControlGetHandle($hHandle, '', 'Edit1'), @AutoItPID)
    Else
        If BitAND($iFlag, 1) Then
            Return Number(ControlGetText($hHandle, '', ControlGetHandle($hHandle, '', 'Edit1')))
        Else
            Exit -1
        EndIf
    EndIf

    Return 0
EndFunc   ;==>_SingletonPID

ReturnToContents

_Sort

Author: guinness








#include <Constants.au3>

ConsoleWrite(_Sort("$sVariable" & @CRLF & "$iVariable" & @CRLF & "$tVariable" & @CRLF & "$pVariable"))

Func _Sort(Const $sSortList)
    Local Const $iPID = Run("sort.exe", @SystemDir, @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD), $sOutput = ""

    StdinWrite($iPID, $sSortList)
    StdinWrite($iPID)

    While 1
        $sOutput &= StdoutRead($iPID)

        If @error Then
            ExitLoop
        EndIf
    WEnd

    Return $sOutput
EndFunc   ;==>_Sort

ReturnToContents

Speak Object and Save to WAV File

Author: SolidSnake26








; Speak Object and save to wav file

_SpeakToWAV("AutoIt Snippets", @ScriptDir & "\SavedFile.wav")

Func _SpeakToWAV(Const $sText, Const $sFilePath)
	Local $ObjVoice = ObjCreate("Sapi.SpVoice")

	Local $ObjFile = ObjCreate("Sapi.SpFileStream.1")

	$ObjVoice.Speak($sText)

	$ObjFile.Open($sFilePath, 3)

	$ObjVoice.AudioOutputStream = $ObjFile
EndFunc   ;==>_SpeakToWAV

ReturnToContents

_VariableSwap

Author: guinness








Global $sString_1 = 'This is string 1.'
Global $sString_2 = 'This is string 2.'

ConsoleWrite('$sString_1: ' & $sString_1 & @CRLF)
ConsoleWrite('$sString_2: ' & $sString_2 & @CRLF & @CRLF)

_VariableSwap($sString_1, $sString_2)

ConsoleWrite('$sString_1: ' & $sString_1 & @CRLF)
ConsoleWrite('$sString_2: ' & $sString_2 & @CRLF & @CRLF)

; Swap the contents of two variables.
Func _VariableSwap(ByRef $vVariable_1, ByRef $vVariable_2) ; Similar to _ArraySwap though not obvious to some this isn't limited to arrays.
    Local Const $vTemp = $vVariable_1
    $vVariable_1 = $vVariable_2
    $vVariable_2 = $vTemp
EndFunc   ;==>_VariableSwap

ReturnToContents

_WinAPI_CharLower

Author: guinness








;Convert characters to upper or lower case

ConsoleWrite(_WinAPI_CharLower("EXAMPLE") & @CRLF) ; Similar to StringLower.

; Convert characters to lowercase.
Func _WinAPI_CharLower($sString)
    Local $aReturn = DllCall('user32.dll', 'wstr', 'CharLowerW', 'wstr', $sString)
    If @error Then
        Return SetError(1, 0, $sString)
    EndIf
    Return $aReturn[0]
EndFunc   ;==>_WinAPI_CharLower

ReturnToContents

_WinAPI_CharUpper

Author: guinness








;Convert characters to upper or lower case

ConsoleWrite(_WinAPI_CharLower("EXAMPLE") & @CRLF) ; Similar to StringLower.

; Convert characters to lowercase.
Func _WinAPI_CharLower($sString)
    Local $aReturn = DllCall('user32.dll', 'wstr', 'CharLowerW', 'wstr', $sString)
    If @error Then
        Return SetError(1, 0, $sString)
    EndIf
    Return $aReturn[0]
EndFunc   ;==>_WinAPI_CharLower

ReturnToContents

_WinAPI_PathFileExists

Author: guinness








; An API Alternative To FileExist.

ConsoleWrite(_WinAPI_PathFileExists(@ScriptFullPath) & @LF) ; File.
ConsoleWrite(_WinAPI_PathFileExists("C:\") & @LF) ; Drive.
ConsoleWrite(_WinAPI_PathFileExists(@ProgramFilesDir) & @LF) ; Directory.
ConsoleWrite(_WinAPI_PathFileExists("Z:\File.txt") & @LF) ; Shouldn't exist!

Func _WinAPI_PathFileExists($sFilePath)
    Local $aReturn = DllCall('shlwapi.dll', 'int', 'PathFileExistsW', 'wstr', $sFilePath)
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    Return $aReturn[0]
EndFunc   ;==>_WinAPI_PathFileExists

ReturnToContents

_WinActiveByExe

Author: SmOke_N








; Window Active/Activate by Exe, Open Notepad whilst script is running

While 1
    If _WinActiveByExe('notepad.exe', False) Then MsgBox(64, 'info', 'true')
    Sleep(100)
WEnd

Func _WinActiveByExe($sExe, $iActive = True);False to WinActivate, True to just see if it's active
    If Not ProcessExists($sExe) Then Return SetError(1, 0, 0)
    Local $aPL = ProcessList($sExe)
    Local $aWL = WinList()
    For $iCC = 1 To $aWL[0][0]
        For $xCC = 1 To $aPL[0][0]
            If $aWL[$iCC][0] <> '' And _
                WinGetProcess($aWL[$iCC][1]) = $aPL[$xCC][1] And _
                BitAND(WinGetState($aWL[$iCC][1]), 2) Then
                If $iActive And WinActive($aWL[$iCC][1]) Then Return 1
                If Not $iActive And Not WinActive($aWL[$iCC][1]) Then
                    WinActivate($aWL[$iCC][1])
                    Return 1
                EndIf
            EndIf
        Next
    Next
    Return SetError(2, 0, 0)
EndFunc

ReturnToContents

_WindowShake

Author: guinness








; Shake a window left to right.

Example()

Func Example()
    ; Run Notepad
    Run("notepad.exe")

    ; Wait 10 seconds for the Notepad window to appear.
    Local $hWnd = WinWait("[CLASS:Notepad]", "", 10)

    ; Wait for 1 second.
    Sleep(1000)

    ; Shake the Notepad window left to right.
    _WindowShake($hWnd)

    ; Wait for 1 second.
    Sleep(1000)

    ; Close the Notepad window using the handle returned by WinWait.
    WinClose($hWnd)
EndFunc   ;==>Example

Func _WindowShake($sTitle, $sText = '', $iDistance = 20)
    Local $hWnd = WinGetHandle($sTitle, $sText)
    Local $aWinGetPos = WinGetPos($hWnd)
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    Local $aArray[5] = [4, $aWinGetPos[0] + $iDistance, $aWinGetPos[0], $aWinGetPos[0] + $iDistance, $aWinGetPos[0]]

    For $i = 1 To $aArray[0]
        WinMove($hWnd, '', $aArray[$i], Default)
        Sleep(100)
    Next
EndFunc   ;==>_WindowShake

ReturnToContents

_WinGetDetails

Author: guinness








#include <Array.au3>

Global $aArray = _WinGetDetails('[ACTIVE]') ; Returns the Window's title, PID, folder path filename.

If @error Then
    Exit
EndIf

_ArrayDisplay($aArray)

Func _WinGetDetails($sTitle, $sText = '') ; Based on code of _WinGetPath by GaryFrost.
    Local $aReturn[5] = [4, '-WinTitle', '-PID', '-FolderPath', '-FileName'], $aStringSplit

    If StringLen($sText) > 0 Then
        $aReturn[1] = WinGetTitle($sTitle, $sText)
    Else
        $aReturn[1] = WinGetTitle($sTitle)
    EndIf
    $aReturn[2] = WinGetProcess($aReturn[1])

    Local $oWMIService = ObjGet('winmgmts:\\.\root\CIMV2')
    Local $oItems = $oWMIService.ExecQuery('Select * From Win32_Process Where ProcessId = ' & $aReturn[2], 'WQL', 0x30)
    If IsObj($oItems) Then
        For $oItem In $oItems
            If $oItem.ExecutablePath Then
                $aStringSplit = StringSplit($oItem.ExecutablePath, '\')
                $aReturn[3] = ''
                For $A = 1 To $aStringSplit[0] - 1
                    $aReturn[3] &= $aStringSplit[$A] & '\'
                Next
                $aReturn[3] = StringTrimRight($aReturn[3], 1)
                $aReturn[4] = $aStringSplit[$aStringSplit[0]]
                Return $aReturn
            EndIf
        Next
    EndIf
    Return SetError(1, 0, $aReturn)
EndFunc   ;==>_WinGetPath

ReturnToContents

_WinGetNumeratedClassList

Author: MrCreatoR








; Description: Retrieves the numerated classes from a window.

Func _WinGetNumeratedClassList($sTitle)
    Local $sClassList = WinGetClassList($sTitle)
    Local $aClassList = StringSplit($sClassList, @LF)
    Local $sRetClassList = "", $sHold_List = "|"
    Local $aiInHold, $iInHold

    For $i = 1 To UBound($aClassList) - 1
        If $aClassList[$i] = "" Then ContinueLoop

        If StringRegExp($sHold_List, "\|" & $aClassList[$i] & "~(\d+)\|") Then
            $aiInHold = StringRegExp($sHold_List, ".*\|" & $aClassList[$i] & "~(\d+)\|.*", 1)
            $iInHold = Number($aiInHold[UBound($aiInHold)-1])

            If $iInHold = 0 Then $iInHold += 1

            $aClassList[$i] &= "~" & $iInHold + 1
            $sHold_List &= $aClassList[$i] & "|"

            $sRetClassList &= $aClassList[$i] & @LF
        Else
            $aClassList[$i] &= "~1"
            $sHold_List &= $aClassList[$i] & "|"
            $sRetClassList &= $aClassList[$i] & @LF
        EndIf
    Next

    Return StringReplace(StringStripWS($sRetClassList, 3), "~", "")
EndFunc

ReturnToContents

_WinGetHandleByPID

Author: SmOke_N








; Get Window Handle by PID

#include <Array.au3>

Global $a1 = _WinGetHandleByPID(232)
Global $a2 = _WinGetHandleByPID("notepad.exe", -1)
Global $a3 = _WinGetHandleByPID("notepad.exe", 0)
Global $a4 = _WinGetHandleByPID("notepad.exe", 1)

_ArrayDisplay($a1, "1")
_ArrayDisplay($a2, "2")
_ArrayDisplay($a3, "3")
_ArrayDisplay($a4, "4")

;$nVisible = -1 "All (Visble or not)", $nVisible = 0 "Not Visible Only", $nVisible = 1 "Visible Only"
Func _WinGetHandleByPID($vProc, $nVisible = 1)
    $vProc = ProcessExists($vProc);

    If Not $vProc Then Return SetError(1, 0, 0)

    Local $aWL = WinList()

    Local $aTemp[UBound($aWL)][2]

	Local $nAdd = 0

    For $iCC = 1 To $aWL[0][0]
        If $nVisible = -1 And WinGetProcess($aWL[$iCC][1]) = $vProc Then
            $nAdd += 1
            $aTemp[$nAdd][0] = $aWL[$iCC][0]
            $aTemp[$nAdd][1] = $aWL[$iCC][1]
        ElseIf $nVisible = 0 And WinGetProcess($aWL[$iCC][1]) = $vProc And _
                BitAND(WinGetState($aWL[$iCC][1]), 2) = 0 Then
            $nAdd += 1
            $aTemp[$nAdd][0] = $aWL[$iCC][0]
            $aTemp[$nAdd][1] = $aWL[$iCC][1]
        ElseIf $nVisible > 0 And WinGetProcess($aWL[$iCC][1]) = $vProc And _
                BitAND(WinGetState($aWL[$iCC][1]), 2) Then
            $nAdd += 1
            $aTemp[$nAdd][0] = $aWL[$iCC][0]
            $aTemp[$nAdd][1] = $aWL[$iCC][1]
        EndIf
    Next

    If $nAdd = 0 Then Return SetError(2, 0, 0) ; No windows found

    ReDim $aTemp[$nAdd + 1][2]

    $aTemp[0][0] = $nAdd

    Return $aTemp
EndFunc

ReturnToContents