Snippets ( Miscellaneous )

From AutoIt Wiki
Jump to navigation Jump to search

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


Basic Installer Example

Author: guinness








; Basic idea for an installer.
#include <GUIConstantsEx.au3>
#include <TabConstants.au3>

Example()

Func Example()
    Local $aArray[11] = [10], $hGUI, $iBack, $iHeight = 500, $iIndex = 0, $iNext, $iTab, $iWidth = 500

    $hGUI = GUICreate("", $iWidth, $iHeight)

    $iBack = GUICtrlCreateButton("Back", $iWidth - 180, $iHeight - 30, 85, 25)
    $iNext = GUICtrlCreateButton("Next", $iWidth - 90, $iHeight - 30, 85, 25)

    $iTab = GUICtrlCreateTab(-99, -99, 0, 0) ; Create a Tab group.
    For $i = 1 To $aArray[0]
        GUICtrlCreateTabItem($i)
        GUICtrlCreateLabel('Page ' & $i, 10, 10)
    Next
    GUICtrlCreateTabItem("") ; Close the Tab group.

    _Toggle_EnableOrDisable($iBack, 0) ; Disable the back button.

    GUISetState(@SW_SHOW, $hGUI)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $iBack
                If $iIndex = ($aArray[0] - 1) Then ; Enabled the next button if the index is currently at the maximum number of tabs minus 1.
                    _Toggle_EnableOrDisable($iNext, 1) ; Enable the next button.
                EndIf

                $iIndex -= 1 ; Decrease the item index.
                If $iIndex <= 0 Then ; Disable the back button if the index is less than the number of tab items.
                    $iIndex = 0
                    _Toggle_EnableOrDisable($iBack, 0) ; Disable the back button.
                EndIf
                GUICtrlSendMsg($iTab, $TCM_SETCURFOCUS, $iIndex, 0)

            Case $iNext
                $iIndex += 1 ; Increase the item index.
                If $iIndex = 1 Then
                    _Toggle_EnableOrDisable($iBack, 1) ; Enable the back button if the index is equal to 1.
                EndIf

                If $iIndex >= ($aArray[0] - 1) Then ; Disable the next button if the index is greater than the number of tab items minus 1.
                    $iIndex = ($aArray[0] - 1)
                    _Toggle_EnableOrDisable($iNext, 0) ; Disable the next button.
                EndIf
                GUICtrlSendMsg($iTab, $TCM_SETCURFOCUS, $iIndex, 0)

        EndSwitch
    WEnd
EndFunc   ;==>Example

Func _Toggle_EnableOrDisable($iControlID, $iOverride = -1) ; By guinness.
    Local $aState[2] = [$GUI_ENABLE, $GUI_DISABLE]
    If $iOverride > -1 Then
        $iOverride = Number(Not $iOverride)
    Else
        $iOverride = Number(BitAND(GUICtrlGetState($iControlID), $aState[0]) = $aState[0])
    EndIf
    GUICtrlSetState($iControlID, $aState[$iOverride])
EndFunc   ;==>_Toggle_EnableOrDisable

ReturnToContents

_DummyFile

Author: guinness








#include <WinAPI.au3>

; Create a dummy file that is 1MB in size.
_DummyFile(@ScriptDir & "\Test.txt", 1, 1) ; Initial idea by trancexx who created it in AutoIt code.

Func _DummyFile($sFilePath, $iSizeMB, $iOverwrite = 0)
    Local $hFile = _WinAPI_CreateFile($sFilePath, 0 + $iOverwrite, 4)
    If Not $hFile Then
        Return SetError(1, 0, 0)
    EndIf
    _WinAPI_SetFilePointer($hFile, 1048576 * $iSizeMB)
    _WinAPI_SetEndOfFile($hFile)
    Return Number(_WinAPI_CloseHandle($hFile))
EndFunc   ;==>_DummyFile

ReturnToContents

_nDaysTrial_Check_Proc

Author: MrCreatoR








;#include-once ;Can be used as Include, only an idea ;)
#include <String.au3>

_nDaysTrial_Check_Proc("My_App", "Your registration period (%s Hour :) ) has expired!", 1)
;=================== Here goes your script code ===================

;==================================================================

Func _nDaysTrial_Check_Proc($sTrialExp_Title, $sTrialExp_Msg, $nTrial=30)
    Local $nDays_Over = $nTrial
    Local $iFiles_Counter = 0

    Local $iTotal_Files = 4
    Local $aTrial_File[$iTotal_Files+1]

    $aTrial_File[0] = $iTotal_Files-1
    $aTrial_File[1] = @WindowsDir & "\" & $sTrialExp_Title & ".sys"
    $aTrial_File[2] = @SystemDir & "\" & $sTrialExp_Title & ".sys"
    $aTrial_File[3] = @UserProfileDir & "\Local Settings\Application Data\" & $sTrialExp_Title & ".sys"
    $aTrial_File[4] = @AppDataCommonDir & "\" & $sTrialExp_Title & ".sys"

    For $i = 1 To $aTrial_File[0]
        $iFiles_Counter += FileExists($aTrial_File[$i])
    Next

    If $iFiles_Counter > 0 And $iFiles_Counter < $aTrial_File[0] Then ;One of the files doesn't exists, that means that we got uncovered
        $nDays_Over += 1
    ElseIf $iFiles_Counter = 0 Then ;All files are missing, that means one of two: we got uncovered, or this is the first run :)
        $iTimer_Init = TimerInit()

        For $i = 1 To $aTrial_File[0]
            FileWriteLine($aTrial_File[$i], _
                _StringEncrypt(1, @YEAR & @MON & @UserName & @MIN & @SEC, @ComputerName) & @CRLF & _
                _StringEncrypt(1, $aTrial_File[$i] & "=" & $iTimer_Init, @ComputerName) & @CRLF & _
                _StringEncrypt(1, @ComputerName & @UserName & @MIN & @YEAR & @HOUR & @SEC, @ComputerName))

            FileSetAttrib($aTrial_File[$i], "+SH")
            FileSetTime($aTrial_File[$i], "") ;Only as an option to check in the future...
        Next
    ElseIf $iFiles_Counter = $aTrial_File[0] Then ;All files found, now we check the synchronization and the times..
        Local $sCurent_Decrypted_Line
        Local $aTimer_Inits[$aTrial_File[0]+1]
        $aTimer_Inits[0] = $aTrial_File[0]

        ;Here we get the Encrypted timer inits...
        For $i = 1 To $aTrial_File[0]
            $aReadFile = StringSplit(FileRead($aTrial_File[$i]), @CRLF)

            For $j = 1 To UBound($aReadFile)-1
                $sCurent_Decrypted_Line = _StringEncrypt(0, $aReadFile[$j], @ComputerName)
                If StringInStr($sCurent_Decrypted_Line, $aTrial_File[$i]) Then
                    $aTimer_Inits[$i] = Int(StringReplace($sCurent_Decrypted_Line, $aTrial_File[$i] & "=", ""))
                    ExitLoop
                EndIf
            Next
        Next

        ;Now we check if all the init are the same values (to insure that they all is untouched)...
        For $i = $aTimer_Inits[0] To 2 Step -1
            If $aTimer_Inits[$i] <> $aTimer_Inits[$i-1] Or Int($aTimer_Inits[$i]) < 1 Then
                $nDays_Over += 1
                ExitLoop
            EndIf
        Next

        ;Ok, if the Timer Inits all the same, we check the time differences...
        If $nDays_Over = $nTrial Then
            ;If has been over $nTrial Hours, then we declare a state that our trial has expired
            If Round(Int(TimerDiff($aTimer_Inits[1])) / 1000 / 60 / 60, 2) >= $nTrial Then $nDays_Over += 1
        EndIf
    EndIf

    If $nDays_Over > $nTrial Then
        MsgBox(262144+48, "*" & $sTrialExp_Title & "*", StringFormat($sTrialExp_Msg, $nTrial))
        Exit
    EndIf
EndFunc

ReturnToContents

_PasswordCrypt

Author: Valuater




Modified: guinness





#include <Crypt.au3>

Local $sGenericPassword_1 = 'Password@AutoIt', $sGenericPassword_2 = 'NewPassword@AutoIt', $sSavePath = @ScriptDir & '\License.dat'
ConsoleWrite('1. ' & _PasswordCrypt($sGenericPassword_1, $sSavePath) & @CRLF) ; Write the password to a file located in the @ScriptDir. The password we wrote is returned by the function.
ConsoleWrite('2. ' & _PasswordCrypt($sGenericPassword_1, $sSavePath) & @CRLF) ; Since the password has been written already, we now want to check if the user has entered the password correctly. Returns True or False.
ConsoleWrite('3. ' & _PasswordCrypt($sGenericPassword_2, $sSavePath, 1) & @CRLF) ; Overwrite the old password with a new one.
ConsoleWrite('4. ' & _PasswordCrypt($sGenericPassword_1, $sSavePath) & @CRLF) ; Check the password matches. This will fail as we're checking the old password against the new one.
FileDelete($sSavePath)

Func _PasswordCrypt($sPassword, $sFilePath, $iOverwrite = 0) ; By guinness, idea by Valuater.
    If FileExists($sFilePath) And $iOverwrite = 0 Then
        Return BinaryToString(_Crypt_DecryptData(IniRead($sFilePath, 'PasswordKey', 'Password', ''), @ComputerName, $CALG_AES_256)) == $sPassword
    Else
        If IniWrite($sFilePath, 'PasswordKey', 'Password', _Crypt_EncryptData($sPassword, @ComputerName, $CALG_AES_256)) Then
            Return $sPassword
        EndIf
    EndIf
    Return SetError(1, 0, '')
EndFunc   ;==>_PasswordCrypt

ReturnToContents

_RandomText

Author: guinness








ConsoleWrite(_RandomText() & @CRLF) ; Generates a random block of text

Func _RandomText($iLength = 10)
    Local $sData = "", $sRandom
    For $A = 1 To $iLength
        $sRandom = Random(55, 116, 1)
        $sData &= Chr($sRandom + 6 * ($sRandom > 90) - 7 * ($sRandom < 65))
    Next
    Return $sData
EndFunc   ;==>_RandomText

ReturnToContents

_ReturnCard

KentonBomb








;===============================================================================
; Function Name:     _ReturnCard()
; Description:   Returns a random card W/ Face value, Includes optional "Joker" card W/ No face valie
; Syntax:   _ReturnCard([$nJoker)
; Parameter(s):   $nJoker- Boolean representing whether or not the "Joker" is a possible card
;                         0 - (default) Joker is not included
; Requirement(s):
; Return Value(s):   $nJoker = 1: Card "Of" Face Value OR "Joker"
;                           $nJoker = 0: Card "Of" Face Value
; Author(s):     KentonBomb (KentonBomb@gmail.com)
; Modification(s):   None
; Note(s):   This UDF may be useful for games, but Autoit's Random function may not be just "Random" Enough
; Example(s):   MsgBox(0, "Your Card", "Your card was " & _ReturnCard())
;===============================================================================
MsgBox(0, "Your Card", "Your card was " & _ReturnCard())

Func _ReturnCard($nJoker = 0)
    Local $nNumbers, $azSplits, $nRandom, $nReturn, $sFace, $sFaces, $nRandom2
    $nNumbers = "Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,King,Queen,Ace"
    If $nJoker Then
        $nNumbers &= ",Joker"
    EndIf
    $azSplits = StringSplit($nNumbers, ",")
    $sReturn = $azSplits[Random(1, $azSplits[0], 1)]
    $sFaces = StringSplit("Spades|Clubs|Hearts|Diamonds", "|")
    $nRandom2 = Random(1, $sFaces[0] - 1)
    $sFace = $sFaces[Round($nRandom2)]
    If $sReturn = "Joker" Then
        Return $sReturn
    Else
        Return $sReturn & " Of " &$sFace
    EndIf
EndFunc   ;==>_ReturnCard

ReturnToContents

_ReturnCard

Author: guinness








ConsoleWrite( _ReturnCard() & @LF)

Func _ReturnCard()
    Local $aFaces[5] = [4, "Clubs", "Diamonds", "Hearts", "Spades"], _
            $aNumbers[14] = [13, "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
    Return $aNumbers[Random(1, $aNumbers[0], 1)] & " Of " & $aFaces[Random(1, $aFaces[0], 1)]
EndFunc   ;==>_ReturnCard

ReturnToContents

_TextSize

Author: JScript








; Author: JScript - Snippet Version No. = 1.0
; Snippet was Created Using AutoIt Version = 3.3.8.1, Creation Date = 23/05/12.

Local $sText = "Sample text to determine the dimensions!"
Local $aiSize = _TextSize($sText)

MsgBox(4096, "TextSize", "String: " & $sText & @CRLF & @CRLF & "Width: " & $aiSize[0] & @CRLF & "Height: " & $aiSize[1])

Func _TextSize($sString, $iSize = 9, $iWeight = 400, $sFontName = "")
    Local $hWnd, $hGuiSwitch, $aCtrlSize, $aRetSize[2] = [0, 0]

    $hWnd = GUICreate($sString, 0, 0, 0, 0, BitOR(0x80000000, 0x20000000), BitOR(0x00000080, 0x00000020))
    $hGuiSwitch = GUISwitch($hWnd)
    GUISetFont($iSize, $iWeight, -1, $sFontName, $hWnd)
    $aCtrlSize = ControlGetPos($hWnd, "", GUICtrlCreateLabel($sString, 0, 0))
    GUIDelete($hWnd)
    GUISwitch($hGuiSwitch)

    If IsArray($aCtrlSize) Then
        $aRetSize[0] = $aCtrlSize[2]; Width
        $aRetSize[1] = $aCtrlSize[3]; Height
        Return SetError(0, 0, $aRetSize)
    EndIf
    Return SetError(1, 0, $aRetSize)
EndFunc   ;==>_TextSize

ReturnToContents

_UnExpandEnvStrings

Author: guinness







A simple wrapper for _WinAPI_PathUnExpandEnvStrings which will return a blank string if no replacements are made though this will return the original path.


#include <WinAPIEx.au3>

ConsoleWrite(_UnExpandEnvStrings(@AppDataDir) & @CRLF)
ConsoleWrite(_UnExpandEnvStrings('C:') & @CRLF)
ConsoleWrite(_UnExpandEnvStrings('E:Scripts') & @CRLF) ; Would normally be blank with _WinAPI_PathUnExpandEnvStrings.

; Version: 1.00. AutoIt: V3.3.8.1
; Is a simple wrapper for _WinAPI_PathUnExpandEnvStrings which will return a blank string if no replacements are made, though this will return the original path.
Func _UnExpandEnvStrings($sFilePath)
    Local $sUnExpanded = _WinAPI_PathUnExpandEnvStrings($sFilePath)
    If StringStripWS($sUnExpanded, 8) = '' Then
        Return $sFilePath
    EndIf
    Return $sUnExpanded
EndFunc   ;==>_UnExpandEnvStrings

ReturnToContents