Jump to content

AutoIt Snippets


Chimaera
 Share

Recommended Posts

reducing it to 2 passes with no regex and accounting for ridiculous edge cases. I am oddly proud of this one, but I am disappointed in the lack of competition. Come get some, you are being judged on simplicity and understandability (Dcoder's rules).

 

edit:  meant to write that on the last post, but cant delete stuff so...

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

  • 1 month later...

load a theme/deskthemepack in Win10 from a command line is a pain an unfriendly affair, so I resorted to this:

If Int(FileGetVersion("winver.exe")) = 10 Then ; this is for Win10
;~  ShellExecute("shell:::{ED834ED6-4B5A-4bfe-8F11-A626DCB6A921}")
    ShellExecute("\\WPACS\share$\[w10customize]\defTheme.deskthemepack") ; your path
    If WinWait("[CLASS:CabinetWClass;]","",10) Then WinClose("[CLASS:CabinetWClass;]")
EndIf

Shared in hopes it will help someone.

Edited by argumentum
nicer code

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

  • 2 weeks later...

Implode or explode your GUI from anywhere on your screen:  holding the mouse pressed on the GUI while dragging will resize the GUI preserving it's dimension
 

#include <GuiconstantsEx.au3>
#include <WinAPISys.au3>
#include <WinAPIGdi.au3>
#include <Misc.au3>

Opt("GUIResizeMode", 904)

$hDLL = DllOpen("user32.dll")
OnAutoItExitRegister("On_Exit")

Global $iWidth = 380, $iHeight = 180

Global $hGUI = GUICreate("X", $iWidth, $iHeight, -1, -1)
GUISetBkColor(0X5c6e8c, $hGUI)

$iWidth = _WinAPI_GetClientWidth($hGUI)
$iHeight = _WinAPI_GetClientHeight($hGUI)
$ButtonWidth = 40
$ButtonHeight = 20
$idnew = GUICtrlCreateButton("Change Dimension", ($iWidth / 2) - (3 * $ButtonWidth / 2), ($iHeight / 2) - (4 * $ButtonHeight / 2), 3 * $ButtonWidth, $ButtonHeight)
$idCenter = GUICtrlCreateButton("x", ($iWidth / 2) - ($ButtonWidth / 2), ($iHeight / 2) - ($ButtonHeight / 2), $ButtonWidth, $ButtonHeight)
GUICtrlSetFont($idCenter, 10, 200)

Global $PM = _WinAPI_MonitorFromWindow($hGUI)

DllCall("user32.dll", "int", "AnimateWindow", "hwnd", $hGUI, "int", 500, "long", 0x00040010)
GUISetState()

$aGPos = WinGetPos($hGUI)
$iWidth = $aGPos[2]
$iHeight = $aGPos[3]

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_close
            Exit
        Case $idnew
            $iWidth = Random(150, 550, 1)
            $iHeight = Random(150, 550, 1)
            _NewDimension($iWidth, $iHeight)
        Case $idCenter
            _CenterToScreen()
        Case $GUI_EVENT_PRIMARYDOWN
            OnDrag()
    EndSwitch
WEnd

Func OnDrag()
    Local $aPos, $iRoll, $X, $Y, $width, $height, $PH, $PW = 0, $aCurInfo = GUIGetCursorInfo($hGUI)
    If $aCurInfo[4] <> 0 Then Return ; Mouse is over a control
    Local $aGPos = WinGetPos($hGUI)
    Local $aMPos = MouseGetPos()
    Local $MON = _WinAPI_MonitorFromWindow($hGUI)
    Local $aMax = MonitorGetRect($MON)
    If $PM <> $MON Then
        $PM = $MON
        Return _CenterToScreen(1)
    EndIf

    If _SnapToScreen($aGPos, $aMax) Then Return WinMove($hGUI, "", $aGPos[0], $aGPos[1], $aGPos[2], $aGPos[3])

    $width = $aGPos[2]
    $height = $aGPos[3]

    While _IsPressed("01", $hDLL)
        $aPos = MouseGetPos()
        $iRoll = (($aMPos[1] - $aPos[1]) - ($aMPos[0] - $aPos[0])) * 100 / 50

        $height = ($aGPos[3] / $aGPos[2]) * ($aGPos[2] + $iRoll)
        If $height < $iHeight Then ExitLoop
        If $height >= $aMax[3] Then
            Do
                $iRoll -= 1
                $height = Round(($aGPos[3] / $aGPos[2]) * ($aGPos[2] + $iRoll))
            Until $height <= $aMax[3]
        EndIf

        $width = ($aGPos[2] / $aGPos[3]) * $height
        If $width >= ($aMax[2] - $aMax[0]) Then
            Do
                $iRoll -= 1
                $height = Round(($aGPos[3] / $aGPos[2]) * ($aGPos[2] + $iRoll))
                $width = ($aGPos[2] / $aGPos[3]) * $height
            Until $width <= ($aMax[2] - $aMax[0])
        EndIf

        ;Store as Previous Width & Height
        $PW = $width
        $PH = $height

        $X = Round((($aGPos[2] / 2) + $aGPos[0]) - ($width / 2))
        $Y = Round((($aGPos[3] / 2) + $aGPos[1]) - ($height / 2))

        If $X <= $aMax[0] Then
            $X = $aMax[0]
        ElseIf ($X + $width) >= $aMax[2] Then
            $X = ($aMax[2] - $width)
        EndIf

        If $Y <= $aMax[1] Then
            $Y = $aMax[1]
        ElseIf ($Y + $height) >= $aMax[3] Then
            $Y = ($aMax[3] - $height)
        EndIf

        WinMove($hGUI, "", $X, $Y, $width, $height)

        Sleep(20)
    WEnd
    If $height < $iHeight And $PW <> 0 Then
        $tRect = _WinAPI_GetWindowRect($hGUI)
        Return WinMove($hGUI, "", (($PW / 2) + DllStructGetData($tRect, "Left")) - ($iWidth / 2), Ceiling(($PH / 2) + DllStructGetData($tRect, "Top")) - ($iHeight / 2), $iWidth, $iHeight)
    EndIf
EndFunc   ;==>OnDrag

Func _SnapToScreen(ByRef $aGPos, ByRef $aMax) ; Snap the gui back to its full view when moved off screen
    Local $Move = False
    If $aGPos[0] < $aMax[0] Then
        $aGPos[0] = $aMax[0]
        $Move = True
    ElseIf ($aGPos[0] + $aGPos[2]) > $aMax[2] Then
        $aGPos[0] = ($aMax[2] - $aGPos[2])
        $Move = True
    EndIf
    If $aGPos[1] < $aMax[1] Then
        $aGPos[1] = $aMax[1]
        $Move = True
    ElseIf ($aGPos[1] + $aGPos[3]) > $aMax[3] Then
        $aGPos[1] = ($aMax[3] - $aGPos[3])
        $Move = True
    EndIf
    If $Move Then Return True
EndFunc   ;==>_SnapToScreen

Func _NewDimension($width, $height)
    Local $aPos = WinGetPos($hGUI)
    Return WinMove($hGUI, "", ($aPos[2] / 2) + $aPos[0] - ($width / 2), ($aPos[3] / 2) + $aPos[1] - ($height / 2), $width, $height)
EndFunc   ;==>_NewDimension

Func _CenterToScreen($Move =False)
    Local $aMax = MonitorGetRect(_WinAPI_MonitorFromWindow($hGUI)) ; Center & Resize the gui dimension if off screen
    Local $aGPos = WinGetPos($hGUI)
    Local $check = $aGPos[2]
    If $aGPos[3] > ($aMax[3] - $aMax[1]) Then
        $aGPos[2] = Round(($aGPos[2] / $aGPos[3]) * ($aMax[3] - $aMax[1])) ;New Width
        $aGPos[3] = $aMax[3] - $aMax[1] ;New Height
    EndIf
    If $aGPos[2] > ($aMax[2] - $aMax[0]) Then
        $aGPos[3] = Round(($aGPos[3] / $aGPos[2]) * ($aMax[2] - $aMax[0])) ;New Height
        $aGPos[2] = $aMax[2] - $aMax[0] ;New Width
    EndIf
    If $Move and $check = $aGPos[2] then Return
    Return WinMove($hGUI, "", (($aMax[2] + $aMax[0]) / 2) - ($aGPos[2] / 2), (($aMax[1] + $aMax[3]) / 2) - ($aGPos[3] / 2), $aGPos[2], $aGPos[3])
EndFunc   ;==>_CenterToScreen

Func MonitorGetRect($hMonitor)
    Local $aData = _WinAPI_GetMonitorInfo($hMonitor)
    Local $s = DllStructGetData($aData[1], 1) & ',' & DllStructGetData($aData[1], 2) & ',' & DllStructGetData($aData[1], 3) & ',' & DllStructGetData($aData[1], 4)
    Local $a = StringSplit($s, ',', 2)
    Return $a
EndFunc   ;==>MonitorGetRect

Func On_Exit()
    DllClose($hDLL)
EndFunc   ;==>On_Exit

 

Edited by Deye
Updated
Link to comment
Share on other sites

  • Moderators

@Namber1 this thread is to share your own snippets, not random Non-English videos from YouTube.

"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

  • Developers

@Namber1,I have actually already removed 3 of those video posts in other threads so YES, stop plugging the video or else will impose a posting ban.

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

I have a hack this time, not a function: Generate custom/fake/pseudo events in OnEvent mode in AutoIt

; This snippet will show you a "hack" that you can use in GUI OnEvent mode in AutoIt
; With this hack you can create fake/pseudo events for a control in a OnEvent "handler"
; function which is registered with multiple controls.

; Usually you can get around this by using a unique function for every control
; but I like to use a single function that I use as a handler for a group of related
; controls. Looks neat and organized :)

; Let's get started!

; Include the important stuff
#include <AutoItConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

Opt("GUIOnEventMode", 1)

; This function will create the GUI and make it visible
Func CreateGUI()
    GUICreate("Example", 60, 60)
    ; Functions with parameters will not be called, unless all of their parameters are optional (undocumented)
    GUISetOnEvent($GUI_EVENT_CLOSE, HandleGUI)
    Global $idToggleButton = GUICtrlCreateButton("", 5, 05, 50, 50)
    GUICtrlSetOnEvent($idToggleButton, HandleGUI)
EndFunc

; This is our most important piece of code, the Handler function which handles
; any events generated by the GUI!
Func HandleGUI($iCtrlID = Default)
    ; As mentioned previously, when a function is called by AutoIt's OnEvent handler,
    ; the optional parameters are NOT defined at all! So their default values are meaningless
    ; Therefore we can use IsDeclared to see if a parameter is declared, effective way to know
    ; if it was called by AutoIt's OnEvent handler.
    ;
    ; The switch expression is a ternary operation, it first checkes if $iCtrlID is defined,
    ; then if it is declared locally, the expression is evaluated to $iCtrlID's value. This
    ; would be the case when a psedo/fake event has been generated by the script manually
    ;
    ; If it was called by AutoIt, then the expression would evaluate to @GUI_CtrlID
    ;
    ; This allows for seamless integration with the code, you won't have to use ControlClick to
    ; create a mouse press or something similar!
    Switch (IsDeclared("iCtrlID") = $DECLARED_LOCAL ? $iCtrlID : @GUI_CtrlId)
        Case $GUI_EVENT_CLOSE
            Exit
        Case $idToggleButton
            Local Static $bOn = True
            If $bOn Then
                GUICtrlSetData($idToggleButton, "Off")
                $bOn = False
            Else
                GUICtrlSetData($idToggleButton, "On")
                $bOn = True
            EndIf
    EndSwitch
EndFunc

; A practical use case:
; Often when there is a button which toggles/switches between values, the default value will have
; to be repeated when creating the control, this is fine for small things but is a good way to do
; if you have something more that needs to be done. This is just a simple example of a button which
; toggles between On and Off. The speciality is that those values will not be repeated in the code :)
;
; This is not very easy to read or as simple as setting the value of the button to the default state
; during the creation of the GUI, but it is a good practise that helps you avoid replicating text

CreateGUI()

HandleGUI($idToggleButton) ; This will generate a fake event which will trigger the same action as clicking on the button

GUISetState() ; Show the GUI

While True
    Sleep(10)
WEnd

; Link to this code snippet on Gist: https://git.io/vbRQ5

 

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

  • 4 weeks later...

This function offers a simple way to roughly calibrate the speed of animations on various computers and OSes. It calculates the number of loops iterated within a given number of milliseconds.

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7

Global $iAnimSpeed
_SetAnimSpeed()
AdlibRegister("_SetAnimSpeed", 300000) ;wait 5 minutes for Windows startup to finish, then every 5 minutes, recalibrate animation speed

Func _SetAnimSpeed()
    $iAnimSpeed = _CalibrateLoopTime(1000, 1) ;get the number of loops within a second with 1 Sleep()
    ;AdlibUnRegister("_SetAnimSpeed") ;uncomment this line if you only want to recalibrate once
EndFunc   ;==>_SetAnimSpeed

ConsoleWrite("On this computer, 1 second of animation = " & $iAnimSpeed & " for-next loops, including 1 sleep." & @CRLF)

; #FUNCTION# ====================================================================================================================
; Name ..........: _CalibrateLoopTime
; Description ...: Calculates the number of loops iterated within a given number of milliseconds. A simple way to *roughly*
;                   calibrate the speed of animations on various computers and OSes.
; Syntax ........: _CalibrateLoopTime($iMilliseconds[, $iSleep = 0])
; Parameters ....: $iMilliseconds       - number of milliseconds to calibrate. Longer is more accurate, shorter is less disruptive.
;                   Remember to divide or multiply to get the length of the animation.
;                  $iSleep              - [optional] manually adjust this to correct for the how fast animation gets generated.
;                   Default is 0.
; Return value ..: integer number of loops within given milliseconds
; Author ........: Tim Curran (tim/at/timcurran/dot/com)
; Modified ......:
; Remarks .......: The longer the Sleep() adjustment, the less accurate this calibration, as computer speed performing the task
;                   (e.g. building the animation) becomes a greater factor.
; Example .......: See above.
; ===============================================================================================================================

Func _CalibrateLoopTime($iMilliseconds, $iSleep = 0)
    Local $iLoopCounter, $hCaliTimer
    $hCaliTimer = TimerInit()
    Do
        $iLoopCounter += 1
        Sleep($iSleep)
    Until TimerDiff($hCaliTimer) >= $iMilliseconds
    Return $iLoopCounter
EndFunc   ;==>_CalibrateLoopTime

 

Edited by tcurran
Link to comment
Share on other sites

  • 1 month later...

Hello mates.

I would like to share simple but very important function required durning code many *au3 files.

Such as function is used by a few scripts developers on forum but most of users waste a lot of time to make his functions/tool free from errors and bugs.

How is working?

This function do not check errors like Scite debugger. You can be able to make something like call exceptions in Python.

Think about this and think when you ran some code, no error but also do nothing. 0 information and you have to jump into own or other script to find out reason.

Function

;=======================================================================================================================
; Function:         Exception ([ $sInfo="" [, $vReturnValue=Null [, $iErrorLine=@ScriptLineNumber [, $iErrorNr=@error [, $vExtended=@extended [, $sScriptPath=@ScriptFullPath]]]]]])
;
; Description:      Call exceptions in different *au3 files.
;
; Parameter(s):     $sInfo -        Information about exception in code, created by yourself.
;                   $vReturnValue - (Default=Null) Set value to return durning exception.
;                   $iErrorLine -   (Default=@ScriptLineNumber) Set the line manually.
;                   $iErrorNr -     (Default=@error) Set the error manually by adding a number.
;                   $vExtended -    (Default=@extended) Set extended manually.
;                   $sScriptPath -  Internal use, do not change.
;
; Return Value(s):  $vReturnValue,
;                   Additional: Output string in Scite Console about debug trace.
;
; Author (s):       Who cares?
;========================================================================================================================

Func Exception($sInfo="", $vReturnValue=Null, $iErrorLine=@ScriptLineNumber, $iErrorNr=@error, $vExtended=@extended, $sScriptPath=@ScriptFullPath)

    Local $aFile = FileReadToArray(sScriptPath)
    Local $sFunctionName, $sLine
    Local $vFound = False

    For $i = 0 To $iErrorLine - 1
        If $vFound Then ExitLoop
        $sLine = StringReplace($aFile[$iErrorLine - $i], @TAB, "")
        If StringInStr(StringLower($sLine), "func ") Then
            Local $aSortLine = StringSplit($sLine, '')
            $sLine = ""
            For $h = 1 To $aSortLine[0] - 1
                Local $sLowerSort = StringLower($aSortLine[$h])
                If $sLowerSort = "(" Then
                    $vFound = True
                    ExitLoop
                ElseIf $sLowerSort <> @TAB And $sLowerSort <> " " Then
                    If $sLowerSort = "f" Or $sLowerSort = "u" Or $sLowerSort = "n" Or $sLowerSort = "c" Then
                        $sLine &= $aSortLine[$h]
                    Else
                        If Not StringInStr($sLine, "func") Then
                            $sLine = ""
                            ExitLoop
                        Else
                            $sLine &= $aSortLine[$h]
                        EndIf
                    EndIf
                EndIf
            Next
        EndIf
    Next

    $sFunctionName = StringTrimLeft($sLine, 4)

    If StringLen($sFunctionName) < 1 Then
        $sFunctionName = "not recognized"
    Else
        $sFunctionName &= " ( ... )"
    EndIf

    If StringLen($sInfo) < 1 Then
        $sInfo = "nothing about"
    EndIf

    $vRet = $vReturnValue

    If $vRet = Null Then
        $vRet = "Null"
    ElseIf IsArray($vRet) Then
        $vRet = "an Array with " & UBound($vRet) & " items"
    ElseIf IsBinary($vRet) Then
        $vRet = "binary " & $vRet
    ElseIf IsBool($vRet) Then
        $vRet = "bool " & $vRet
    ElseIf IsDllStruct($vRet) Then
        $vRet = "dll struct " & $vRet
    ElseIf IsFloat($vRet) Then
        $vRet = "float " & $vRet
    ElseIf IsHWnd($vRet) Then
        $vRet = "hwnd " & $vRet
    ElseIf IsInt($vRet) Then
        $vRet = "int " & $vRet
    ElseIf IsKeyword($vRet) Then
        $vRet = "keyword " & $vRet
    ElseIf IsNumber($vRet) Then
        $vRet = "number " & $vRet
    ElseIf IsObj($vRet) Then
        $vRet = "object " & $vRet
    ElseIf IsPtr($vRet) Then
        $vRet = "ptr " & $vRet
    ElseIf IsString($vRet) Then
        If $vReturnValue = "" or StringReplace($vRet, " ", "") = "" Then
            $vRet = 'empty string ""'
        Else
            $vRet = 'string "' & $vRet & '"'
        EndIf
    EndIf

    Local $sStruct
    $sStruct &= "! Exception = {" & @CRLF
    $sStruct &= "!" & @CRLF
    $sStruct &= "!" & @TAB & '"date" = ' & @YEAR & "-" & @MON & "-" & @MDAY & ", " & @HOUR & ":" & @MIN & ":" & @SEC & ", " & @MSEC & "ms," & @CRLF
    $sStruct &= "!" & @TAB & '"path" = ' & $sScriptPath & "," & @CRLF
    $sStruct &= "!" & @TAB & '"line" = ' & $iErrorLine & "," & @CRLF
    $sStruct &= "!" & @TAB & '"func" = ' & $sFunctionName & "," & @CRLF
    $sStruct &= "!" & @TAB & '"retn" = ' & $vRet & "," & @CRLF
    $sStruct &= "!" & @TAB & '"exten" = ' & $vExtended & "," & @CRLF
    $sStruct &= "!" & @TAB & '"error" = ' & $iErrorNr & "," & @CRLF
    $sStruct &= "!" & @TAB & '"info" = ' & $sInfo
    $sStruct &= @CRLF
    $sStruct &= "!" & @CRLF
    $sStruct &= "! }" & @CRLF & @CRLF

    ConsoleWrite($sStruct)

    Return $vReturnValue
EndFunc ;==> Exception

 

How to use? - Example 1

Func Example()
    Local $sFile = FileOpen(@ScriptDir & "\example.py")
    If $sFile = -1 Then
        Return Exception("Failed to open 'example.py', File not exist!")
    EndIf
    ; continue working
EndFunc

Example()

Example 1 Output in Scite console:

Exception 1.png

Example 2

Func Example2()
    Local $oHttp = ObjCreate("WinHttp.WinHttpRequest.5.1.Fake") ; added .Fake to make object wrong.
    If Not IsObj($oHttp) Then
        Return Exception("Failed to create Object in variable $oHttp.", 2.2)
    EndIf
    ; continue working
EndFunc

Local $vRet = Example2()

ConsoleWrite("$vRet = " & $vRet & @CRLF)

Example 2 Output in Scite console:

Exception 2.png

Edited by Ascer
Link to comment
Share on other sites

  • 3 weeks later...

Dashlane has recently updated to require manual sign-in every time for non-passworded PC's, the "Keep my session open for 14 days" is greyed out.  (for anyone finding this in a search), download AutoIt, and do a build with these lines.....

WinWaitActive("[TITLE:Dashlane]", "")

Send("YourPasswordHere{ENTER}")

Put this in your startup folder and it will login for you.

Link to comment
Share on other sites

  • 2 months later...

Another stupid snipped, this is for padding (right/left/center)

Center padding: if string passed has an even number of characters, left padding is shorter! (maybe a choice may be given to the user, using a parameter with a default => to be implemented)

Global Const $PAD_Right ="Right"
Global Const $PAD_Left  ="Left"
Global Const $PAD_Center="Center"

#cs
Function that pads a string.
  Parameters
    str_IN: string to be processed
    len_IN: legth to pad
    pad_IN: padding string (default is space)
  Return Value
    Success: value stored in values array
    Failure: PROGRAM FAILURE
    @error : 1 generic error
#CE
Func _StringPad($str_IN, $len_IN, $pad_IN = " ", $padType = $PAD_Right)
    Local $strLen_LOC=StringLen($str_IN)
    Local $missing_LOC=$len_IN-$strLen_LOC
    Switch $padType
        Case $PAD_Right
            Return _StringInsert($str_IN, _StringRepeat($pad_IN, ($missing_LOC)), $strLen_LOC)
        Case $PAD_Left
            Return (_StringRepeat($pad_IN, ($missing_LOC)) & $str_IN)
        Case $PAD_Center
            Return (_StringRepeat($pad_IN, Floor($missing_LOC/2)) & $str_IN & _StringRepeat($pad_IN, Ceiling($missing_LOC/2)))
    EndSwitch
EndFunc ;==> _StringPad

 

Thank you

Link to comment
Share on other sites

This one finds out who is the one who has opened an excel file with write privilege:

#include <File.au3>
Local $sFile = ; fullpath to an excel file
Local $sOpened = _ExcelFileOpened($sFile)
If @error Then ; nobody has opened this excel file
    If @error = 1 Then
        ConsoleWrite("You can open the excel file and write to it." & @CRLF)
    ElseIf @error = 2 Then
        ConsoleWrite("File does not exist." & @CRLF)
    ElseIf @error = 3 Then
        ConsoleWrite("File ist not an excel file." & @CRLF)
    EndIf
ElseIf @extended = 1 Then
    ConsoleWrite("This excel file is already opened by you with write privilege" & @CRLF)
Else
    ConsoleWrite("This excel file is opened by " & $sOpened & @CRLF & "You can't write to the file therefor it will not be opened." & @CRLF)
EndIf
Exit


; #FUNCTION# ====================================================================================================================
; Name ..........: _ExcelFileOpened
; Description ...: Returns who has the excel file opened with write privilege
; Syntax ........: _ExcelFileOpened($sFile)
; Parameters ....: $sFile - must be an excel file
; Return values .: Success - name of who has opened the excel file with write privilege, sets @extended to:
;                  |1 - if I am the one
;                  Failure - 0, sets @error to:
;                  |1 - excel file is not opened
;                  |2 - file does not exist
;                  |3 - file is not an excel file
; Author ........: Simpel
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _ExcelFileOpened($sFile)
    ; check if file exists
    If FileExists($sFile) = 0 Then Return SetError(2, 0, 0)
    ; check if file is an excel file
    Local $iDelimiter = StringInStr($sFile, ".", 0, -1) ; splits suffix
    Local $sExtension = StringTrimLeft($sFile, $iDelimiter) ; only file extension
    If StringLeft($sExtension, 3) <> "xls" Then Return SetError(3, 0, 0)
    ; if excel has created a temporary excel file with a ~$ prefix then it is already opened
    $iDelimiter = StringInStr($sFile, "\", 0, -1) ; splits file from path
    Local $sTempFile = StringLeft($sFile, $iDelimiter) & "~$" & StringTrimLeft($sFile, $iDelimiter) ; adds prefix ~$ at excel filename
    Local $iTempFileExist = FileExists($sTempFile) ; if this file exists then the excel file is opened
    If $iTempFileExist = 0 Then Return SetError(1, 0, 0) ; is not opened
    Local $sOwnerTempFile = _Owner($sTempFile) ; owner of the excel temp file is the one with write privilege
    ; find out who I am
    Local $sTestFile = _TempFile() ; needs file.au3
    FileWrite($sTestFile, "") ; create a test file (I am definitely the owner)
    If @error Then
        Return $sOwnerTempFile ; returns only the one with write privilege to the excel file
    EndIf
    Local $sMe = _Owner($sTestFile) ; this is me
    FileDelete($sTestFile)
    ; look if I am the one created the temp excel file
    If $sOwnerTempFile = $sMe Then
        Return SetError(0, 1, $sMe) ; returns me opened excel file with write privilege and sets @extended to 1
    Else
        Return $sOwnerTempFile ; returns the one with write privilege to the excel file
    EndIf
EndFunc

Func _Owner($sFile) ; the one who saved it last - code by siao?
    Local $secUtil = ObjCreate("ADsSecurityUtility")
    Local $secDesc = $secUtil.GetSecurityDescriptor($sFile, 1, 1)
    Local $sOwner = $secDesc.Owner
    $secUtil = Null
    Return $sOwner
EndFunc

Regards, Conrad

SciTE4AutoIt = 3.7.3.0   AutoIt = 3.3.14.2   AutoItX64 = 0   OS = Win_10   Build = 19044   OSArch = X64   Language = 0407/german
H:\...\AutoIt3\SciTE     H:\...\AutoIt3      H:\...\AutoIt3\Include     (H:\ = Network Drive)

   88x31.png  Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind.

Link to comment
Share on other sites

  • 2 weeks later...

Auto height input box:

  After messing about trying to get my input box the right size for the
  comments I was putting into it, I decided that I ought to be able to write
  a little code to do this for me.  I put my comments in a string and the
  carriage returns in between the comments.  My code uses regex to put the
  @CRLFs into an array and ubound to count the number of elements in the
  array and uses that to determine the height of the box.
 
  I start with a base height of 122 pixels and then added another 13.2 pixels
  for each element beyond the first element.
 
  If you have word wrapping you will have to manually add an additional
  13.2 pixels for each line that wraps.
;Auto height input box
#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
Local $sd
$sd = "1 Line no @CRLF"
InputBox("Input", $sd, "", "", -1, 122 + (13.2 * UBound(StringRegExp($sd, '\R', 3))))
$sd = "1" & @CRLF & "2" & @CRLF & "3" & @CRLF & "4" & @CRLF & "5"
InputBox("Input", $sd, "", "", -1, 122 + (13.2 * UBound(StringRegExp($sd, '\R', 3))))
$sd = "1" & @CRLF & "2" & @CRLF & "3" & @CRLF & "4" & @CRLF & "5" & @CRLF & "6" & @CRLF & "7" & _
@CRLF & "8" & @CRLF & "9" & @CRLF & "10"
InputBox("Input", $sd, "", "", -1, 122 + (13.2 * UBound(StringRegExp($sd, '\R', 3))))

 

Edited by wolflake
I decided to put the comments outside the code.
Link to comment
Share on other sites

My version of getting the actual NTP timestamp if someone needs it.

#include <Date.au3>

TCPStartup()

Global $NtpServer1 = "time.google.com"
Global $NtpServer1_IP = TCPNameToIP($NtpServer1)
Global $sTime = _NTP_GetTimestamp($NtpServer1_IP)
ConsoleWrite("Actual UTC time: " & $sTime & @CRLF)


Func _NTP_GetTimestamp($IP, $maxReadTries = 2)
    ;funkey 2018.05.08
    Local Const $tagNtpPacket = "BYTE li_vn_mode;BYTE stratum;BYTE poll; BYTE precision;DWORD rootDelay;DWORD rootDispersion;DWORD refId;DWORD refTm_s;DWORD refTm_f;DWORD origTm_s;DWORD origTm_f;DWORD rxTm_s;DWORD rxTm_f;DWORD txTm_s;DWORD txTm_f"
    Local Const $tagNtpPacket_Help = "byte NtpPacket[48]"

    Local $NtpPacket = DllStructCreate($tagNtpPacket)
    Local $NtpPacket_Help = DllStructCreate($tagNtpPacket_Help, DllStructGetPtr($NtpPacket))
    Local $sec, $frac, $sTimeStamp

    DllStructSetData($NtpPacket, "li_vn_mode", 0x1b)

    UDPStartup()
    Local $aSock = UDPOpen($IP, 123)
    UDPSend($aSock, DllStructGetData($NtpPacket_Help, "NtpPacket"))

    While $maxReadTries > 0
        Local $data = UDPRecv($aSock, 48)
        If $data <> "" Then
            DllStructSetData($NtpPacket_Help, "NtpPacket", $data)
            $sec = _ntohl(DllStructGetData($NtpPacket, "txTm_s"))
            $frac = _ntohl(DllStructGetData($NtpPacket, "txTm_f"))
            $sTimeStamp = _DateAdd('s', $sec, "1900/01/01 00:00:00") & "," & StringFormat("%06s", Round($frac * 1000000 / 2 ^ 32))
            ExitLoop
        Else
            Sleep(10)
            $maxReadTries -= 1
        EndIf
    WEnd

    UDPCloseSocket($aSock)
    UDPShutdown()
    Return $sTimeStamp
EndFunc   ;==>_NTP_GetTimestamp

Func _ntohl($iNetLong)
    Local $aRet = DllCall("ws2_32.dll", "ULONG", "ntohl", "ULONG", $iNetLong)
    Return $aRet[0]
EndFunc   ;==>_ntohl

 

Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Link to comment
Share on other sites

Another approach of _StringBetween() with different result...

 

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

Global $iStringIN = "59?\nHello\nAutoit\nWorld\n"
Global $aArray = _StringBetween2($iStringIN, "\n", "\n", 0)
_ArrayDisplay($aArray, "_StringBetween2")

Global $aArray2 = _StringBetween($iStringIN, "\n", "\n", 0)
_ArrayDisplay($aArray2, "Standard _StringBetween")

Func _StringBetween2($s_String, $s_Start, $s_End, $v_Case = 0)
    ;funkey 2018.05.24
    Local $iPos1 = 0, $iPos2
    Local $sRes = ""
    Do
        $iPos1 = StringInStr($s_String, $s_Start, $v_Case, 1, $iPos1 + 1)
        $iPos2 = StringInStr($s_String, $s_End, $v_Case, 1, $iPos1 + StringLen($s_Start))
        If $iPos1 > 0 And $iPos2 > 0 Then $sRes &= StringMid($s_String, $iPos1 + StringLen($s_Start), $iPos2 - $iPos1 - StringLen($s_Start)) & $s_Start
    Until $iPos1 <= 0 Or $iPos2 <= 0

    Local $aRes = StringSplit($sRes, $s_Start, 3)
    If UBound($aRes) > 1 Then
        ReDim $aRes[UBound($aRes) - 1]
    Else
        Return SetError(1, 0, 0)
    EndIf
    Return $aRes
EndFunc   ;==>_StringBetween2

 

Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Link to comment
Share on other sites

  • 3 weeks later...

IE readystate tooltips, since statusbar is gone.

#include <IE.au3>

Const $url = inputbox("type url" , "type url" , "www.autoitscript.com")

$oIE = _IECreate($url, 1, 1, 0)
$sText = 0

Do
    tooltip('wait' , 1 , 1 , "wait" , 3)
            ;~ consolewrite($sText & @LF)
    sleep(100)
    $sText = _IEPropertyGet($oIE, "readystate")
Until $sText = 4

    tooltip('loading complete' , 1 , 1 , "complete" , 1)
sleep(5000)



;~     READYSTATE_UNINITIALIZED = 0
;~     READYSTATE_LOADING = 1
;~     READYSTATE_LOADED = 2
;~     READYSTATE_INTERACTIVE = 3
;~     READYSTATE_COMPLETE = 4

 

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

  • 1 month later...

Windows Operating System Information:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
#include <MsgBoxConstants.au3>
OperatingSystemVersion()

Func OperatingSystemVersion($host = @ComputerName)
    Local $product = RegRead('\\' & $host & '\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName')
    Local $build = RegRead('\\' & $host & '\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'CurrentBuild')
    Local $owner = RegRead('\\' & $host & '\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'RegisteredOwner')
    MsgBox(-1, "Operating System Information", "Product Version: " & $product & @CRLF & "Build Version: " & $build & @CRLF & "Owner: " & $owner )
EndFunc   ;==>OperatingSystemVersion



 

Kind Regards
Skeletor

"Coffee: my defense against going postal."

Microsoft Office Splash Screen | Basic Notepad Program (Beginner) | Transparent Splash Screen | Full Screen UI

Link to comment
Share on other sites

My snippit for the modern Yubikeys (where you have USB Descriptor option enabled on it, via the personalisation tool settings screen) This simply waits until it detects that you inserted your Yubikey and then when you remove it, it locks the PC. But you could use it for all kinds of things, make the PC shutdown, sound an alarm, who knows. Just a cool little thing I threw together. I do not know, really, about "Objects" and dealing with the indepth Microsoft device info but I was able to tweak a basic "here's a list of all USB devices" I found, into something that can detect the presence of the Yubikey. I also have an alternative to USB\\ which will look for smartcards but I stopped using that and reverted back to USB since I am not entirely sure if the numbers represented on there are unique, at least the USB one I can clearly see it has the serial number on my Yubikey.

 

AutoItSetOption('TrayAutoPause', 0)

Global $Status, $InitialLaunch = True

While 1
    $checking = CheckForYubikeyExistence()

    Switch $checking
        Case True
            ;;;;;;;; Area to run commands after the Yubikey is inserted BELOW
            ConsoleWrite('DETECTED!' & @LF)

            ;;;;;;;; Area to run commands after the Yubikey is inserted ABOVE

            While 1
                If CheckForYubikeyExistence() = False Then ExitLoop
                Sleep(100)
            WEnd

        Case False
            If $InitialLaunch = True Then ; Treat it as ready but actually nothing will happen until the Yubikey is inserted and then removed...
                ConsoleWrite('Launching and waiting for Yubikey insertion...' & @LF)

                While 1 ; This waits until the Yubikey is plugged in the first time, to initiate the protection readiness or at least, the forthcoming detection of Yubikey removal.
                    If CheckForYubikeyExistence() = True Then
                        $InitialLaunch = False
                        ContinueCase
                    EndIf
                    Sleep(100)
                WEnd
            EndIf

            ;;;;;;;; Area to run commands after the Yubikey is pulled out BELOW
            ConsoleWrite('WARNING, YUBIKEY NOT PRESENT!!' & @LF)
            Run('rundll32.exe user32.dll,LockWorkStation')

            ;;;;;;;; Area to run commands after the Yubikey is pulled out ABOVE

            While 1 ; This waits until the Yubikey is inserted again before doing anything next.
                If CheckForYubikeyExistence() = True Then ExitLoop
                Sleep(100)
            WEnd

    EndSwitch
WEnd


Func CheckForYubikeyExistence($_list_all = False) ; Calling this with a True parameter puts it into debugging mode, to list all the user input or smart card devices depending on what type of devices it is looking for.
    $objWMIService = ObjGet("winmgmts:\\.\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_PnPEntity where DeviceID like 'USB\\%'") ; SCFILTER\\% for smartcards and USB\\% for all USB devices

    If IsObj($colItems) Then
        For $objItem In $colItems
            If $_list_all = True Then ConsoleWrite($objItem.DeviceID & @LF) ; Show all the ID's of all smartcards, so you know which ones are allowed (only plug in ones you want to allow when listing them all)

            Switch $objItem.DeviceID

                Case 'USB\VID_1050&PID_0407\0006297461' ; An allowed Yubikey device ID (Your Yubikey needs enabling, on the Settings section of the YK personalisation tool, the "USB Descriptor" option. Else it won't show up.
                    $InitialLaunch = False
                    SetError(0)
                    Return True

                Case 'USB\VID_1050&PID_0116\0005286976' ; An allowed Yubikey device ID two
                    $InitialLaunch = False
                    SetError(0)
                    Return True

            EndSwitch

        Next

        SetError(1)
        Return False ;Nothing by now was detected as being an authorised Yubikey.
    EndIf

EndFunc   ;==>CheckForYubikeyExistence

 

Edited by Morthawt
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...