A collection of small ahk functions

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

A collection of small ahk functions

08 May 2014, 05:40

A collection of small (maybe useful) ahk functions
Table of Contents
  • Convert Base - Convert Base from 2 - 36 via DllCall.
  • CRC32 - Cyclic redundancy check.
  • CryptBinToHex - Convert binary buffer to hex.
  • Disp - Takes the content of a var and creates a displayable string for it.
  • DnsFlushResolverCache - Flush entire DNS cache, same as ipconfig /flushdns.
  • GCD / MCode GCD (32 bit only) - Find the greatest common divisor of two numbers.
  • GetDnsAddress - Get a list of DNS servers used by the local computer.
  • GetMacAddress - Get a list of computers MAC address.
  • GetVersion - Get Windows Major-, Minor- & Build-Version.
  • HasVal - Checks if a value exists in an array (similar to objects/Object.htm#HasKey)
  • hexToStr - Convert Hex to Text Strings.
  • InArr - Similar to InStr(), just the array is searched for a string.
  • IniParser - Parse ini files and return an array of objects with "__SECTION" and relative keys as properties.
  • isGUID - Check if GUID is valid.
  • isRegKey - Check if RegKey is valid.
  • julka_msgbox - msgbox with custom buttons.
  • Minimum / Maximum - Find the minimum of 2 vars / Find the maximum of 2 vars.
  • min / max
  • OSInstallDate - Returns the install date of your operating system.
  • PopCount - Get a number's population count.
  • Random using RtlRandom
    Random using RtlRandomEx
  • RefreshPolicy - Causes policy to be applied immediately on the computer like gpupdate does
  • repr - Return a string containing a printable representation of an object.
  • RSHash - Robert Sedgewick's string hashing algorithm.
  • ScaleToFit - Returns the dimensions of the scaled source rectangle that fits within the destination rectangle.
  • Start Control Panel Applications (Shortcuts)
  • StringReverse
  • strToHex - Convert Text Strings to Hex.
  • StrTrim - Removes specified leading and trailing characters from a string.
    StrToInt - Converts a string that represents a decimal value to an integer.
    StrToIntEx - Converts a string representing a decimal or hexadecimal number to an integer.
    StrToInt64Ex - Converts a string representing a decimal or hexadecimal value to a 64-bit integer.
  • UpdateScript - Update running (.ahk) script in realtime (~ 500-1000 ms) if you change something in the script.
  • WheelScrollLines - Retrieves or sets the number of lines to scroll when the vertical mouse wheel is moved.

Feel free to add more

example:

Title
Small description

Code: Select all

MsgBox % "Your code here"
output:

Code: Select all

output
Last edited by jNizM on 08 May 2014, 06:42, edited 1 time in total.
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

08 May 2014, 05:43

strToHex
Convert Text Strings to Hex

Code: Select all

strToHex(str)
{
    static v := A_IsUnicode ? "_i64tow" : "_i64toa"
    loop, parse, str
    {
        VarSetCapacity(s, 65, 0)
        DllCall("msvcrt.dll\" v, "Int64", Asc(A_LoopField), "Str", s, "UInt", 16, "CDECL")
        hex .= "0x" s " "
    }
    return SubStr(hex, 1, (StrLen(hex) - 1))
}
example:

Code: Select all

MsgBox % "Text:`tAutHotkey`nHex:`t" strToHex("AutHotkey")
output:

Code: Select all

Text:    AutoHotkey
Hex:     0x41 0x75 0x74 0x48 0x6f 0x74 0x6b 0x65 0x79
Last edited by jNizM on 03 Jun 2014, 03:53, edited 6 times in total.
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

08 May 2014, 05:48

hexToStr
Convert Hex to Text Strings

Code: Select all

hexToStr(hex)
{
    static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64"
    loop, parse, hex, " "
    {
        char .= Chr(DllCall("msvcrt.dll\" u, "Str", A_LoopField, "Uint", 0, "UInt", 16, "CDECL Int64"))
    }
    return char
}
example:

Code: Select all

MsgBox % "Hex:`t0x41 0x75 0x74 0x48 0x6f 0x74 0x6b 0x65 0x79`nHex:`t" hexToStr("0x41 0x75 0x74 0x48 0x6f 0x74 0x6b 0x65 0x79")
output:

Code: Select all

Hex:     0x41 0x75 0x74 0x48 0x6f 0x74 0x6b 0x65 0x79
Text:    AutoHotkey
Last edited by jNizM on 03 Jun 2014, 03:52, edited 3 times in total.
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

08 May 2014, 07:05

Convert Base
Convert Base from 2 - 36 via DllCall (thanks to Laszlo & Gogo)

Code: Select all

ConvertBase(InputBase, OutputBase, nptr)
{
    static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64"
    static v := A_IsUnicode ? "_i64tow"    : "_i64toa"
    VarSetCapacity(s, 66, 0)
    value := DllCall("msvcrt.dll\" u, "Str", nptr, "UInt", 0, "UInt", InputBase, "CDECL Int64")
    DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL")
    return s
}
example:

Code: Select all

MsgBox, % "Decimal:`t`t42`n"
        . "to Binary:`t`t"      ConvertBase(10, 2, 42)       "`n"
        . "to Octal:`t`t"       ConvertBase(10, 8, 42)       "`n"
        . "to Hexadecimal:`t"   ConvertBase(10, 16, 42)      "`n`n"
        . "Hexadecimal:`t2A`n"
        . "to Decimal:`t"       ConvertBase(16, 10, "2A")    "`n"
        . "to Octal:`t`t"       ConvertBase(16, 8, "2A")     "`n"
        . "to Binary:`t`t"      ConvertBase(16, 2, "2A")     "`n`n"
ExitApp
output:

Code: Select all

Decimal:       42
Binary:        101010
Octal:         52
Hexadecimal:   2a
Last edited by jNizM on 03 Jun 2014, 03:57, edited 3 times in total.
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
cyruz
Posts: 346
Joined: 30 Sep 2013, 13:31

Re: A collection of small ahk functions

08 May 2014, 09:29

I like this thread!

IniParser
Parse ini files and return an array of objects with "__SECTION" and relative keys as properties.

Code: Select all

IniParser(sFile) {
    arrSection := Object(), idx := 0
    Loop, READ, %sFile%
        If ( RegExMatch(A_LoopReadline, "S)^\s*\[(.*)\]\s*$", sSecMatch) )
            ++idx, arrSection[idx] := Object("__SECTION", sSecMatch1)
        Else If ( RegExMatch(A_LoopReadLine, "S)^\s*(\w+)\s*\=\s*(.*)\s*$", sKeyValMatch) )
            arrSection[idx].Insert(sKeyValMatch1, sKeyValMatch2)
    Return arrSection
}
Example

Code: Select all

obj := IniParser("test.ini")
For idx, item in obj
    For k, v in item
        If (k == "__SECTION")
            MsgBox, Ini Section: %v%
        Else
            MsgBox, % k . " - " . v 
Return
Last edited by cyruz on 08 May 2014, 09:41, edited 1 time in total.
ABCza on the old forum.
My GitHub.
User avatar
cyruz
Posts: 346
Joined: 30 Sep 2013, 13:31

Re: A collection of small ahk functions

08 May 2014, 09:38

CryptBinToHex
Convert binary buffer to hex.
Thanks to nnnik: http://ahkscript.org/boards/viewtopic.p ... 1242#p8376.

Code: Select all

CryptBinToHex(ByRef sHex, ByRef cBuf) {
    szBuf := VarSetCapacity(cBuf)
    DllCall( "Crypt32.dll\CryptBinaryToString", Ptr,&cBuf, UInt,szBuf, UInt,4, Ptr,0, UIntP,szHex )
    VarSetCapacity(cHex, szHex*2, 0)
    DllCall( "Crypt32.dll\CryptBinaryToString", Ptr,&cBuf, UInt,szBuf, UInt,4, Ptr,&cHex, UIntP,szHex )
    sHex := RegExReplace(StrGet(&cHex, szHex, "UTF-16"), "S)\s")
}
Example

Code: Select all

FileRead, cBuf, *C C:\Windows\System32\drivers\etc\hosts
(FileExist(A_WinDir "\System32\Crypt32.dll")) ? CryptBinToHex(sHex, cBuf)
MsgBox, %sHex%
ABCza on the old forum.
My GitHub.
User avatar
jballi
Posts: 723
Joined: 29 Sep 2013, 17:34

Re: A collection of small ahk functions

08 May 2014, 17:34

jNizM wrote:Convert Base
Convert Base from 2 - 36 via DllCall (thanks to Laszlo & Gogo)
This function will only work if using Unicode. A small enhancement so that the function will be Unicode-aware should do the trick. Something like...

Code: Select all

DllCall(A_IsUnicode ? "msvcrt\_wcstoui64":"msvcrt\_strtoui64"
etc.
etc.
I hope this helps.
Builder
Posts: 14
Joined: 20 Apr 2014, 11:31

Re: A collection of small ahk functions

13 May 2014, 09:29

YMD(Date)

Converts a date from YYYYMMDDHH24MISS to YYYY-MM-DD

If Date is left blank, it converts the current date

ex... x=YMD()

if A_Now is 20140513092817 then the value of x as a string is 2014-05-13

YMD(DDate:="")
{
FormatTime, YMD, %DDate%, yyyy-MM-dd
return (YMD)
}
Last edited by Builder on 13 May 2014, 10:46, edited 1 time in total.
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: A collection of small ahk functions

13 May 2014, 10:40

Builder wrote:Converts a date from YYYYMMDDHH24MISS to YYYY-MM-DD
Something like:

Code: Select all

FormatTime, date,, yyyy-MM-dd
Builder
Posts: 14
Joined: 20 Apr 2014, 11:31

Re: A collection of small ahk functions

13 May 2014, 10:49

Doh!

I forgot to paste the actual code... Corrected with edit

Yes, it uses the format time function...

This just makes it easier to use in an expression...
User avatar
LinearSpoon
Posts: 156
Joined: 29 Sep 2013, 22:55

Re: A collection of small ahk functions

14 May 2014, 00:44

ScaleToFit
Accepts the dimensions of a source rectangle and the dimensions of a destination rectangle.
Returns the dimensions of the scaled source rectangle that fits within the destination rectangle, at the largest possible size and while maintaining aspect ratio.
Also returns the x and y offsets which center the scaled source rectangle within the destination rectangle.

Code: Select all

ScaleToFit(width_max, height_max, width_actual, height_actual)
{
  width_ratio := width_actual / width_max
  height_ratio := height_actual / height_max
  if (width_ratio > height_ratio)
  {
    new_height := height_actual // width_ratio
    return {width:width_max, height:new_height, x:0, y:(height_max-new_height)//2}
  }
  else
  {
    new_width := width_actual // height_ratio
    return {width:new_width, height:height_max, x:(width_max-new_width)//2, y:0}
  }
}
Example usage

Code: Select all

ActualWidth := 200
ActualHeight := 300

Gui, Add, Picture, w%ActualWidth% h%ActualHeight% Border vpictureControl
Gui, +Resize
Gui, Show

GuiSize:
  dimensions := ScaleToFit(A_GuiWidth, A_GuiHeight, ActualWidth, ActualHeight)
  GuiControl, Move, pictureControl, % "w" dimensions.width " h" dimensions.height " x" dimensions.x " y" dimensions.y
return

GuiClose:
  ExitApp
return
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

30 May 2014, 08:29

@jballi
thx for info.. fixed
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

13 Jun 2014, 07:08

isGUID
Check if GUID is valid

Code: Select all

isGUID(GUID) ; https://en.wikipedia.org/wiki/Globally_unique_identifier
{
    return RegExMatch(GUID, "^(?:\{){0,1}[[:xdigit:]]{8}-(?:[[:xdigit:]]{4}-){3}[[:xdigit:]]{12}(?:\}){0,1}$") = 1
}
example:

Code: Select all

MsgBox % isGUID("{21EC2020-3AEA-4069-A2DD-08002B30309D}")
MsgBox % isGUID("21EC2020-3AEA-4069-A2DD-08002B30309D")
MsgBox % isGUID("21EC2020-3AEA-4069-A2DD-08002B30309")
output:

Code: Select all

1
1
0
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

13 Jun 2014, 07:28

isRegKey
Check if RegKey is valid

Code: Select all

isRegKey(RegistryKey, FullPath := True)
{
    return RegExMatch(RegistryKey, "(?i)\A\h*HK(CC|CR|CU|LM|U|EY_CLASSES_ROOT|EY_LOCAL_MACHINE|EY_USERS|EY_CURRENT_(USER|CONFIG))(64)?(?:\\[^\\]*)" ((FullPath) ? "+" : "*") "\z") = 1
}
example:

Code: Select all

MsgBox % isRegKey("HKEY_CURRENT_USER\Software\AutoHotkey")
MsgBox % isRegKey("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion")
MsgBox % isRegKey("HKEY_CORRENT_USER\Software\AutoHotkey")
output:

Code: Select all

1
1
0
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

16 Jun 2014, 07:21

GetVersion
Get Windows Major-, Minor- & Build-Version

Code: Select all

GetVersion()
{
    return { 1 : DllCall("Kernel32.dll\GetVersion") & 0xff
           , 2 : DllCall("Kernel32.dll\GetVersion") >> 8 & 0xff
           , 3 : DllCall("Kernel32.dll\GetVersion") >> 16 & 0xffff }
}
example:

Code: Select all

GetVersion := GetVersion()
MsgBox, % "Major:`t"     GetVersion[1]   "`n"
        . "Minor:`t"     GetVersion[2]   "`n"
        . "Build:`t"     GetVersion[3]
output: (Windows 7 - SP1)

Code: Select all

Major:    6
Minor:    1
Build:    7601
=========================================================================
example 2:

Code: Select all

MajorVersion := DllCall("Kernel32.dll\GetVersion") & 0xff
MinorVersion := DllCall("Kernel32.dll\GetVersion") >> 8 & 0xff
BuildVersion := DllCall("Kernel32.dll\GetVersion") >> 16 & 0xffff

MsgBox, % MajorVersion "." MinorVersion "." BuildVersion
output 2: (Windows 7 - SP1)

Code: Select all

6.1.7601
#########################################################################
example 3: (one-line)

Code: Select all

MsgBox % ((M := (B := DllCall("Kernel32.dll\GetVersion")) & 0xFFFF) & 0xFF) "." (M >> 8) "." (B >> 16)
output 3: (Windows 7 - SP1)

Code: Select all

6.1.7601
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: A collection of small ahk functions

29 Jul 2014, 00:58

Minimum
Find the minimum of 2 vars

Code: Select all

min(x, y)
{
    return y ^ ((x ^ y) & -(x < y))
}

MsgBox % min(27, 64)    ; ==> 27
======================================================================================

Maximum
Find the maximum of 2 vars

Code: Select all

max(x, y)
{
    return x ^ ((x ^ y) & -(x < y))
}

MsgBox % max(27, 64)    ; ==> 64
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: A collection of small ahk functions

29 Jul 2014, 02:10

Disp()
This is a very short function I wrote for debugging purposes.
It just takes the content of a var and creates a displayable string for it.

Code: Select all

Disp(Obj)
{
    OutStr:=""
	If !IsObject(Obj)
	{
		If (Obj|0="")
		{
			If ((Strlen(obj)="")&&VarSetCapacity(Obj))
				return "BINARY" ;Todo *binary
			Else If (Strlen(obj)!="")
				return "" . obj . ""
		}
		return	Obj
	}
	Else If IsFunc(Obj)
		return "func(""" . Obj.name . """)"
	Else
		For Each in Obj
			If !(Each~="\d+")
				NonNumeric:=1
	If NonNumeric
		For Each,Val in Obj
			OutStr.=Each . ":" . Disp(Val) . ","
	Else
		For Each,Val in Obj
			OutStr.=Disp(Val) . ","
	StringTrimRight,outstr,outstr,1
	If NonNumeric
		outstr:="{" . OutStr . "}"
	Else
		outstr:="[" . OutStr . "]"
    return outstr
}
Example:

Code: Select all

Msgbox % Disp("ABC")
Msgbox % Disp({a:{b:{c:[func("Test")]}}})
Test(){
return 42
}
Output:
ABC
{a:{b:{c:[func("Test")]}}}
Recommends AHK Studio
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: A collection of small ahk functions

29 Jul 2014, 03:07

Here's something I use similar to nnnik's Disp():

Code: Select all

/* Function: repr
 * Return a string containing a printable representation of an object*.
 * Syntax:
 *     sobj := repr( obj )
 * Parameter(s):
 *     obj       [in] - An object, string or number. If 'obj' is string,
 *                      output is surrounded in double quotes. Escape
 *                      sequences are represented as is.
 * Remarks:
 *     Object* can be an AHK object, a string or a number (integer OR float).
 *     Only generic AHK object(s) are supported. Other types such as COM, Func,
 *     File, RegExMatch, etc. objects are not supported.
 */
repr(obj) {
	q := Chr(34) ;// Double quotes, make it work for both v1.1 and v2.0-a
	if IsObject(obj) {
		for k in obj
			arr := (k == A_Index)
		until !arr
		str := "", len := NumGet(&obj+4*A_PtrSize)
		for k, v in obj {
			val := repr(v)
			str .= (arr ? val : repr(k) ": " val) . (A_Index < len ? ", " : "")
		}
		return arr ? "[" str "]" : "{" str "}"
	}
	if ([obj].GetCapacity(1) == "") ;// not a string, assume number
		return obj
	float := "float"
	if obj is %float%
		return obj
	esc_seq := {          ;// AHK escape sequences
	(Join Q C
		(q):  "``" . q,   ;// double-quotes
		"`n": "``n",      ;// newline
		"`r": "``r",      ;// carriage return
		"`b": "``b",      ;// backspace
		"`t": "``t",      ;// tab
		"`v": "``v",      ;// vertical tab
		"`a": "``a",      ;// alert (bell)
		"`f": "``f"       ;// formfeed
	)}
	i := 0
	while (i := InStr(obj, "``",, i+1))
		obj := SubStr(obj, 1, i-1) . "````" . SubStr(obj, i+=1)
	for k, v in esc_seq {
		/* StringReplace/StrReplace routine for v1.1 & v2.0-a compatibility
		 * TODO: Compare speed with RegExReplace()
		 */
		i := 0
		while (i := InStr(obj, k,, i+1))
			obj := SubStr(obj, 1, i-1) . v . SubStr(obj, i+=1)
	}
	return q . obj . q
}
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: A collection of small ahk functions

29 Jul 2014, 06:30

Nice functions!
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
toralf
Posts: 868
Joined: 27 Apr 2014, 21:08
Location: Germany

Re: A collection of small ahk functions

29 Jul 2014, 09:59

jNizM wrote:Minimum

Code: Select all

min(x, y){
    return y ^ ((x ^ y) & -(x < y))
}
What is the advantage of bitwise-and and bitwise-exclusiv-or over the tenary operator?

Code: Select all

min(x, y){
  Return x < y ? x : y
}
Same should apply for Maximum (x < y ? y : x).
ciao
toralf

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: Descolada and 113 guests