# AutoIt Snippets

## Recommended Posts

On-place array transpose with minimum move/copy:

```Func _ArrayTranspose(ByRef \$aArr)
If UBound(\$aArr, 0) <> 2 Then
SetError(-1)
Return
EndIf
Local \$element, \$x = UBound(\$aArr, 1), \$y = UBound(\$aArr, 2), \$z = \$y
If \$x > \$y Then \$z = \$x
ReDim \$aArr[\$z][\$z]
For \$i = 0 To \$z - 2
For \$j = \$i + 1 To \$z - 1
\$element = \$aArr[\$i][\$j]
\$aArr[\$i][\$j] = \$aArr[\$j][\$i]
\$aArr[\$j][\$i] = \$element
Next
Next
ReDim \$aArr[\$y][\$x]
EndFunc

Local \$a[3][5] = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
_ArrayDisplay(\$a)
_ArrayTranspose(\$a)
_ArrayDisplay(\$a)

Local \$a[2][2] = [[1,2],[3,4]]
_ArrayDisplay(\$a)
_ArrayTranspose(\$a)
_ArrayDisplay(\$a)

Local \$a[2][3] = [[1,2,3],[4,5,6]]
_ArrayDisplay(\$a)
_ArrayTranspose(\$a)
_ArrayDisplay(\$a)

Local \$a[3][2] = [[1,2],[3,4],[5,6]]
_ArrayDisplay(\$a)
_ArrayTranspose(\$a)
_ArrayDisplay(\$a)

Local \$a[1][1] = [[1]]
_ArrayDisplay(\$a)
_ArrayTranspose(\$a)
_ArrayDisplay(\$a)```

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

##### Share on other sites

_ArrayConcatenate2D

-cb

Edited by cyberbit

[hr]

50% of the time, it works all the time. -PezoFaSho

##### Share on other sites

Checks whether the folder is empty

```Func _IsEmptyFolder(\$sPath)
Local \$s = FileFindFirstFile(\$sPath & '\*')
If \$s = -1 Then Return 1
FileClose(\$s)
Return 0
EndFunc   ;==>_IsEmptyFolder```

.

##### Share on other sites

Aero Flip.

`DllCall("dwmapi.dll", "int", 105)`

Not especially useful, but fun all the same.

Edited by cyberbit

[hr]

50% of the time, it works all the time. -PezoFaSho

##### Share on other sites

[hr]

50% of the time, it works all the time. -PezoFaSho

##### Share on other sites

This function (micro Lookup) receives either an IPv4 address or a hostname or an DomainName and returns an array with:

[1] Hostname.DomainName

[2] Hostname (alone)

to determine if the incoming data is an ip address it uses an regular expression pattern found here

```#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
#include <iNet.au3>

; example of use:

Local \$Net_Result[3]
For \$i = 0 To UBound(\$NetAdrs) - 1
ConsoleWrite(\$Net_Result[0] & @TAB & \$Net_Result[1] & @CRLF)
Next

; This Function accepts either an IPaddress or a Host/Domain name and returns
; a 3 elements array element[0]=IPaddress element[1]=hostname.domain element[2]=hostnameOnly
Func _mLookup(\$Net_ID)
Local \$Net_Names[3]
TCPStartup()
If StringRegExp(\$Net_ID, "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}\$") Then
\$Net_Names[1] = _TCPIpToName(\$Net_ID) ; Resolves IP adress to Hostname
If @error Then \$Net_Names[1] = "Hostname_error"
\$Net_Names[0] = \$Net_ID
Else
\$Net_Names[0] = TCPNameToIP(\$Net_ID) ; Resolves Hostname to IP adress
If @error Then \$Net_Names[0] = "IP_error"
\$Net_Names[1] = \$Net_ID
EndIf
TCPShutdown()

Local \$temp = StringSplit(\$Net_Names[1], ".")
\$Net_Names[2] = \$temp[1]
Return \$Net_Names

EndFunc   ;==>_mLookup```

bye

Edited by Pincopanco
• 1

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

##### Share on other sites

I tested the latest AutoIt Beta with my scripts that have TCP Functions in them,

and found that some of my functions are broken because the error handling has

been changed as of (AutoIt v3.3.9.18 Beta).

So, you might be needing this function or something similar, to determine an error:

```;=============================================================
; #FUNCTION _WSAGetLastErrorEx()
;
; Application: TCPConnect, TCPRecv, TCPSend
; Description: Windows Sockets Error Return + Translation
;
; WSAGetLastError:
; http://msdn.microsoft.com/en-us/library/ms740668.aspx
;
; FormatMessage:
; http://msdn.microsoft.com/en-us/library/ms679351.aspx
;
; Related: DllCall('Kernel32.dll', 'int', 'GetLastError')
;
; Example: YES
;=============================================================
Func _WSAGetLastErrorEx()
Local \$a = DllCall('ws2_32.dll', 'int', 'WSAGetLastError')
If (\$a[0] < 6) Then Return SetError(0, 0, 0)
;
\$a = DllCall('kernel32.dll', 'int', 'FormatMessage', _
'int', 0x00001000, _; dwFlags FORMAT_MESSAGE_FROM_SYSTEM
'ptr', 0, _; lpSource (opt)
'int', \$a[0], _; dwMessageId (error#)
'int', 0, _; dwLanguageId (default 0)
'str', '', _; lpBuffer (string)
'int', 2048, _; nSize (buffer-size)
'ptr', 0); va_list arg (opt)
Return SetError(1, \$a[3], '[' & \$a[3] & '] ' & \$a[5])
EndFunc
;

;Example:
Local \$sRtn
TCPStartup()
Local \$nSocket = TCPConnect('0.0.0.0', '1'); <-- invalid address
If @error Then
\$sRtn = _WSAGetLastErrorEx()
If \$sRtn Then
MsgBox(0, '_WSAGetLastErrorEx() ' & @extended, \$sRtn)
EndIf
EndIf
TCPShutdown()
;```

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

##### Share on other sites

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

;==========================================================================================================
; * Original Code taken from: http://www.autoitscript.com/wiki/Snippets_%28_Time_%26_Date_%29#CopyrightYear
; * Author of Original Code: guinness
;==========================================================================================================

; * A simple function to display a small AboutBox with name of app, version, and copyright year.

Global \$gAppName = "SomeApp"
Global \$gAppVersion = "1.0"

EndFunc```

EDIT: Let stay on Earth.

Edited by NewPlaza

##### Share on other sites

```; \$aItems[0] is the number of the items
; "" = separator
Local \$aItems[6] = [5, "Hello!", "AutoIt Script", "Popup", "", "Cancel"]
\$iSel = _Popup(\$aItems)

MsgBox(64, "Selection", \$aItems[\$iSel])
Exit

Func _Popup(\$aItems, \$hWnd = 0, \$iX = Default, \$iY = Default)
; Get the handle of the AutoIt window if \$hWnd is 0
Local \$hWndBg
If IsHWnd(\$hWnd) Then
\$hWndBg = \$hWnd
Else
\$hWndBg = WinGetHandle(AutoItWinGetTitle())
EndIf

If IsKeyword(\$iX) Then \$iX = MouseGetPos(0)
If IsKeyword(\$iY) Then \$iY = MouseGetPos(1)

Local \$hPopup = DllCall("user32.dll", "handle", "CreatePopupMenu")
If @error Then Return SetError(1, 0, 0)
\$hPopup = \$hPopup[0]

For \$i = 1 To \$aItems[0]
Local \$iFlag = 0    ; MF_STRING = 0x00000000
If \$aItems[\$i] == "" Then \$iFlag = 0x00000800   ; MF_SEPARATOR = 0x00000800

Local \$aRet = DllCall("user32.dll", "bool", "AppendMenuW", "handle", \$hPopup, "uint", \$iFlag, "uint", \$i, "wstr", \$aItems[\$i])
If @error Then Return SetError(2, \$i, 0)
Next

; 0x0182 = TPM_NONOTIFY + TPM_RETURNCMD + TPM_RIGHTBUTTON
Local \$aSel = DllCall("user32.dll", "bool", "TrackPopupMenuEx", "handle", \$hPopup, "uint", 0x0182, "int", \$iX, "int", \$iY, "hwnd", \$hWndBg, "ptr", 0)
If @error Then Return SetError(3, 0, 0)

Local \$aRet = DllCall("user32.dll", "bool", "DestroyMenu", "handle", \$hPopup)
If @error Then Return SetError(4, 0, 0)

Return \$aSel[0]
EndFunc ;==>_Popup```
Edited by Starg

##### Share on other sites

`MsgBox(0+0+0+4096+262144`

Are you trying to reach Proxima Centauri ?
• 1

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

##### Share on other sites

Are you trying to reach Proxima Centauri ?

LOL.. That's the only way I have remembered the values.  One-by-one.. I suck at math

##### Share on other sites

Use constants to avoid magic numbers, or remove at least useless zeroes

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

##### Share on other sites

Tidy style file backup.

```Func _FileBackup(\$sFile, \$sBackupDir = "BackUp")
Local \$sDrive, \$sDir, \$sFileName, \$sExtension

_PathSplit(_PathFull(\$sFile), \$sDrive, \$sDir, \$sFileName, \$sExtension)

If \$sBackupDir <> "" Then
Local \$sBakFileName, \$sBakExtension
_PathSplit(_PathFull(\$sBackupDir) & "\", \$sDrive, \$sDir, \$sBakFileName, \$sBakExtension)
EndIf

Local \$sNewFile, \$i = 0

Do
\$i += 1
\$sNewFile = _PathMake(\$sDrive, \$sDir, \$sFileName & "_old" & \$i, \$sExtension)
Until Not FileExists(\$sNewFile)

Return FileCopy(\$sFile, \$sNewFile, 8)
EndFunc   ;==>_FileBackup```

##### Share on other sites

Created this for my debugging needs, spruced it up a bit and here it is:

```#include <Array.au3>

; #AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6

Global \$aiStuff[5] = [1, 2, 3, 4, 5]
Global \$aiMultiDimension[2][5] = [[1, 2, 3, 4, 5],[5, 4, 3, 2, 1]]
Global \$sString = "Some text"

ConsoleWrite("+ Normal var:" & @CRLF &  _
_DebugVarGetText("\$sString") & @CRLF & @CRLF)

ConsoleWrite("+ Single-Dimension array:" & @CRLF & _
_DebugVarGetText("\$aiStuff") & @CRLF & @CRLF)

ConsoleWrite("+ This var doesn't exist:" & @CRLF & _
_DebugVarGetText("\$DOESNOTEXIST") & @CRLF & @CRLF)

ConsoleWrite("+ Multi-Dimension array:" & @CRLF & _
_DebugVarGetText("\$aiMultiDimension") & @CRLF & @CRLF)

Func _DebugVarGetText(\$sVar, \$vDelim = @CRLF, \$fPadDelim = False)
Local \$vVarData = Execute(\$sVar)
If @error Then
Return "! Error reading var data, var - " & \$sVar
EndIf
If IsArray(\$vVarData) Then
Local \$iTotalElements = 1, \$iVarTotalDim = UBound(\$vVarData, 0)
Local \$aiArrayMax[\$iVarTotalDim], \$aiArrayCur[\$iVarTotalDim]
For \$i = 0 To \$iVarTotalDim - 1
\$iTotalElements *= UBound(\$vVarData, \$i + 1)
\$aiArrayMax[\$i] = UBound(\$vVarData, \$i + 1)
\$aiArrayCur[\$i] = 0
Next

Local \$sOutBuffer = "", \$vCurExecData, \$sExecStr
For \$iNumIterations = 1 To \$iTotalElements
; Build and add next element
\$sExecStr = \$sVar
For \$i = 0 To \$iVarTotalDim - 1
\$sExecStr &= "[" & \$aiArrayCur[\$i] & "]"
Next
\$vCurExecData = Execute(\$sExecStr)
\$sOutBuffer &= \$sExecStr & " (" & VarGetType(\$vCurExecData) & ") = " & \$vCurExecData & \$vDelim

; Iterative increment
\$aiArrayCur[\$iVarTotalDim - 1] += 1
If \$aiArrayCur[\$iVarTotalDim - 1] >= \$aiArrayMax[\$iVarTotalDim - 1] Then
For \$i = \$iVarTotalDim - 1 To 0 Step -1
If \$aiArrayCur[\$i] >= \$aiArrayMax[\$i] Then
If \$i = 0 Then
ExitLoop 2
EndIf
\$aiArrayCur[\$i - 1] += 1
\$aiArrayCur[\$i] = 0
EndIf
Next
EndIf
Next

\$sOutBuffer = StringTrimRight(\$sOutBuffer, StringLen(\$vDelim))
Else
Return \$sVar & " (" & VarGetType(\$vVarData) & ") = " & \$vVarData & \$sPadText
EndIf
EndFunc   ;==>_DebugVarGetText```

Does the array part have any bugs?

Edited by DatMCEyeBall

"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

##### Share on other sites

```Func SelectInString(\$String, \$SplitVar, \$SplitIndex)
Local \$OutPut = @error
\$var = StringSplit(\$String, \$SplitVar, 1)
If \$SplitIndex <= \$var[0] Then \$OutPut = \$var[\$SplitIndex]
Return \$OutPut
EndFunc```

Explanation:

The purpose of this function is to return a certain part from string.

for example this is the string that i will use for the example:

`index1|index2|index3`

if i will call to that function this way:

\$output = SelectInString("index1|index2|index3", "|", 2)

then \$output will be "index2".

if i will call it with other number, for example:

SelectInString("index1|index2|index3", "|", 1)

then the \$output will be "index1".

Another example - let's say I want to select bbb  in this string:

aaa[1]bbb[2]eee[2]fffff[1]ggg

with using my function it is more simple.

all you need to do is this:

\$output = SelectInString(SelectInString("aaa[1]bbb[2]eee[2]fffff[1]ggg", "[1]", 2), "[2]", 1)

Edited by gil900

My recommended codes (that I worte):

_SharedVar - declare shared variables between 2 or more process directly on memory

CODENAME-SW_130416
If the English is not good in this post/code, please correct it (But do only PM).

##### Share on other sites

Hello everyone. Just made this one - represent a number as sum of powers of two:

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

; Returns number as sum of powers of two

Func _GetPowersofTwo(\$mynum)
\$mynumseed = \$mynum
\$i=0
Global \$STRING
while (\$mynumseed <> 0)
do
\$i+=1
until NOT (\$mynumseed >= (2^\$i))
\$STRING &= 2^(\$i-1)
\$mynumseed = \$mynumseed - (2^(\$i-1))
If \$mynumseed <> 0 then
\$STRING &= "+"
EndIf
\$i=0
wend
msgbox(64, "", \$STRING)
EndFunc

_GetPowersofTwo(45)```

----------------------------------------

:bye: Hey there, was I helpful?

----------------------------------------

My Current OS: Win8 PRO (64-bit); Current AutoIt Version: v3.3.8.1

##### Share on other sites

CharAt Function

This function returns the character at a given position(index) in a string.

While it's a fairly simple thing to do, and we have the StringInStr and StringMid native functions which can be setup to get the same result, sometimes what we need is a simple approach to this. I hope any of you can find it useful.

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

;Given a String and an Index, returns the character at that position.
;The index count starts in zero

;Test variables
Dim \$test = "test String"
Dim \$index = 10

;Function
Func CharAt(\$String,\$Index)
Dim \$char ;==> \$char will contain the desired character
\$length=StringLen(\$String)
If \$length <= \$Index Then ;==> This IF will check wether the index is valid for the given String or not
Return "ERROR:Index is out of bounds"
Else
\$count=\$length-(\$Index+1)
\$char=StringTrimLeft(StringTrimRight(\$String,\$count),\$Index)
EndIf
Return \$char
EndFunc

;Test run
\$c = CharAt(\$test,\$index)

MsgBox(0, "String length is:", \$c)```

##### Share on other sites

CharAt Function

This function returns the character at a given position(index) in a string.

While it's a fairly simple thing to do, and we have the StringInStr and StringMid native functions which can be setup to get the same result, sometimes what we need is a simple approach to this. I hope any of you can find it useful.

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

;Given a String and an Index, returns the character at that position.
;The index count starts in zero

;Test variables
Dim \$test = "test String"
Dim \$index = 10

;Function
Func CharAt(\$String,\$Index)
Dim \$char ;==> \$char will contain the desired character
\$length=StringLen(\$String)
If \$length <= \$Index Then ;==> This IF will check wether the index is valid for the given String or not
Return "ERROR:Index is out of bounds"
Else
\$count=\$length-(\$Index+1)
\$char=StringTrimLeft(StringTrimRight(\$String,\$count),\$Index)
EndIf
Return \$char
EndFunc

;Test run
\$c = CharAt(\$test,\$index)

MsgBox(0, "String length is:", \$c)```

That is far from a simple approach.

```Local \$test = "test String"
Local \$Index = 10

\$c = CharAt2(\$test, \$Index)
If @error Then
MsgBox(0, "Error", @error)
Exit
EndIf

MsgBox(0, "Char at pos " & \$Index & " is:", \$c)

Func CharAt2(\$sString, \$iIndex)
If \$iIndex <= 0 Then Return SetError(1, 0, "")
If StringLen(\$sString) = 0 Or StringLen(\$sString) < \$iIndex Then Return SetError(2, 0, "")
Return StringMid(\$sString, \$iIndex, 1)
EndFunc   ;==>CharAt2```

Monkey's are, like, natures humans.

##### Share on other sites

That is far from a simple approach.

```Local \$test = "test String"
Local \$Index = 10

\$c = CharAt2(\$test, \$Index)
If @error Then
MsgBox(0, "Error", @error)
Exit
EndIf

MsgBox(0, "Char at pos " & \$Index & " is:", \$c)

Func CharAt2(\$sString, \$iIndex)
If \$iIndex <= 0 Then Return SetError(1, 0, "")
If StringLen(\$sString) = 0 Or StringLen(\$sString) < \$iIndex Then Return SetError(2, 0, "")
Return StringMid(\$sString, \$iIndex, 1)
EndFunc   ;==>CharAt2```

Well, the "simple" I was talking about was the function itself, with the only variables being the String and the index, thanks for the improvements you made!!

##### Share on other sites

Not Improvements mate, just an alternative.

As you know.

Monkey's are, like, natures humans.

## Create an account

Register a new account