AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

AHK Functions : FileMD5() / MD5() [Updated]
Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9  Next
 
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions
View previous topic :: View next topic  
Author Message
Laszlo



Joined: 14 Feb 2005
Posts: 4517
Location: Boulder, CO

PostPosted: Mon Nov 17, 2008 7:42 pm    Post subject: Reply with quote

It is good for associative arrays. The problem is not random collisions, but finding strings with the same hash is not very difficult, if you know the algorithm. I am not sure, how hard it is, because MSDN does not tell the algorithm.

For longer (<=7 bytes) hash you could try
Code:
Hash(Str, L=4, nSz=0) {
  Static HashData
  If (HashData="")
      HashData := DllCall("GetProcAddress", UInt,DllCall("LoadLibrary", Str,"shlwapi.dll"), Str,"HashData")
  DllCall(HashData, UInt,&Str, UInt,nSz<1 ? StrLen(Str):nSz, Int64P,Hash, UInt,8)
  FI := A_FormatInteger
  SetFormat Integer, H
  Hash := SubStr(Hash+0x100000000000000,1-2*L)
  StringUpper Hash, Hash
  SetFormat Integer, %FI%
  Return Hash
}
It computes 8 bytes hash even when less than 8 bytes are requested, and discards the unused part. A general solution was VarsetCapacity and Str type for the returned value, and convert the result to hex with a loop.

Sprintf handles the padding and hex conversion for up to 8 Bytes input, so the following code is better, little shorter, and could be faster
Code:
Hash(Str, L=4, nSz=0) { ; L Bytes, 2*L HEX digits output, 1<=L<=8
  Static HashData, sprintf, S=1234567890123456
  If (HashData="")
      HashData := DllCall("GetProcAddress", UInt,DllCall("LoadLibrary", Str,"shlwapi.dll"),Str,"HashData")
      ,sprintf := DllCall("GetProcAddress", UInt,DllCall("LoadLibrary", Str,"msvcrt.dll"), Str,"sprintf")
  DllCall(HashData, UInt,&Str, UInt,nSz<1 ? StrLen(Str):nSz, Int64P,Hash, UInt,8) ; 8-Byte= 64-bit hash
  DllCall(sprintf, Str,S, Str,"%016I64X", Int64,Hash) ; 0-padded (left), 16 HEX digits
  Return SubStr(S, 1-2*L) ; only 2L digits
}


Edit 20081120: shorter code added


Last edited by Laszlo on Thu Nov 20, 2008 5:45 pm; edited 1 time in total
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Wed Nov 19, 2008 12:06 am    Post subject: Reply with quote

Laszlo wrote:
It is good for associative arrays.


Glad to hear it..

Code:
DllCall(HashData, UInt,&Str, UInt,nSz<1 ? StrLen(Str):nSz, Int64P,Hash, UInt,8)


I missed that part Shocked .. Thank you.

Laszlo wrote:
It computes 8 bytes hash even when less than 8 bytes are requested, and discards the unused part. A general solution was VarsetCapacity and Str type for the returned value, and convert the result to hex with a loop.


Thank you very much Sir. Very useful info for me.

Smile
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Thu Nov 20, 2008 8:55 am    Post subject: Re: HashData() Reply with quote

Quote:
ProcessOwner()

Returns the Owner for a given Process ID. To make it fully functional, one needs to call SetDebugPrivilege() prior to ProcessOwner()



Code:
ProcessOwner( PID ) {
 ; PROCESS_QUERY_INFORMATION=0x400, TOKEN_READ:=0x20008 , TokenUser:=0x1
 hProcess := DllCall( "OpenProcess", UInt,0x400,Int,0,UInt,PID )
 DllCall( "Advapi32.dll\OpenProcessToken", UInt,hProcess, UInt,0x20008, UIntP,Tok )
 DllCall( "Advapi32.dll\GetTokenInformation", UInt,Tok, UInt,0x1, Int,0, Int,0, UIntP,RL )
 VarSetCapacity( TI,RL,0 )
 DllCall( "Advapi32.dll\GetTokenInformation"
          , UInt,Tok, UInt,0x1, UInt,&TI, Int,RL, UIntP,RL ),           pSid := NumGet(TI)
 DllCall( "CloseHandle", UInt,hProcess ), DllCall( "CloseHandle", UInt,Tok )
 ; following code taken from www.autohotkey.com/forum/viewtopic.php?p=116487 - Author Sean
 DllCall( "Advapi32\LookupAccountSidA"
         , Str,"", UInt,pSid, UInt,0, UIntP,nSizeNM, UInt,0, UIntP,nSizeRD, UIntP,eUser )
 VarSetCapacity( sName,nSizeNM,0 ), VarSetCapacity( sRDmn,nSizeRD,0 )
 DllCall( "Advapi32\LookupAccountSidA"
    , Str,"", UInt,pSid, Str,sName, UIntP,nSizeNM, Str,sRDmn, UIntP,nSizeRD, UIntP,eUser )
 DllCall( "LocalFree", UInt,pSid )
Return sName


; usage example follows

; SetDebugPrivilege() ; www.autohotkey.com/forum/viewtopic.php?p=232199#232199
Process Exist, svchost.exe
PID := ErrorLevel
MsgBox, % ProcessOwner( PID )


Smile
Back to top
View user's profile Send private message
Sean



Joined: 12 Feb 2007
Posts: 2222

PostPosted: Thu Nov 20, 2008 1:23 pm    Post subject: Reply with quote

Very nice. This is another one which surprised me at that it's not been done earlier.
BTW, as the first ones which attract my eyes are the flags as they are in red, I'd like to mention that TOKEN_QUERY ( :=8 ) is enough in place of TOKEN_READ although it's cosmetic one.
And one request: it may depend on an user, but I'd always like to include (referenced) domain name too like:
Code:
sRDmn . "\" . sName
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Thu Nov 20, 2008 5:08 pm    Post subject: Reply with quote

Sean wrote:
Very nice. This is another one which surprised me at that it's not been done earlier.


Many thanks for your help Sean. Smile

Quote:
TOKEN_QUERY ( :=8 ) is enough in place of TOKEN_READ although it's cosmetic one.


I was wondering about it.. just adapted it : http://nibuthomas.wordpress.com/2008/01/08/how-to-get-name-of-owner-of-a-process/

Quote:
And one request: it may depend on an user, but I'd always like to include (referenced) domain name too


Honestly, I did not notice it at all. I took your code for granted and all I did was to remove quote around Arg Types. . Smile
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Sun Nov 23, 2008 7:56 pm    Post subject: FileGetVersionInfo() Reply with quote

Quote:
FileGetVersionInfo()

Extracts and returns version information ( any one at a time ) from an executable file.
AHK's FileGetVersion command will fetch you the FileVersion, but there are more - that this function would fetch. Following are Windows Standard Names
Code:
FileGetVersionInfo( peFile="", StringFileInfo="" ) {
 FSz := DllCall( "Version\GetFileVersionInfoSizeA",Str,peFile,UInt,0 )
 IfLess, FSz,1, Return -1
 VarSetCapacity( FVI, FSz, 0 ), VarSetCapacity( Trans,8 )
 DllCall( "Version\GetFileVersionInfoA", Str,peFile, Int,0, Int,FSz, UInt,&FVI )
 If ! DllCall( "Version\VerQueryValueA", UInt,&FVI, Str,"\VarFileInfo\Translation"
                                       , UIntP,Translation, UInt,0 )
   Return -2
 If ! DllCall( "msvcrt.dll\sprintf", Str,Trans, Str,"%08X", UInt,NumGet(Translation+0) )
   Return -4
 subBlock := "\StringFileInfo\" SubStr(Trans,-3) SubStr(Trans,1,4) "\" StringFileInfo
 If ! DllCall( "Version\VerQueryValueA", UInt,&FVI, Str,SubBlock, UIntP,InfoPtr, UInt,0 )
   Return
 VarSetCapacity( Info, DllCall( "lstrlen", UInt,InfoPtr ) )
 DllCall( "lstrcpy", Str,Info, UInt,InfoPtr )
Return Info
}

SetBatchLines -1
Loop, %A_WinDir%\System32\*.??l
  Files .= "|" A_LoopFileLongPath
Files := A_AhkPath . Files

Loop, Parse, Files, |
  MsgBox, 0, % (PeFile:=A_LoopField)
  , % "FileDescription      `t:`t" FileGetVersionInfo( PeFile, "FileDescription"  ) "`n"
    . "FileVersion          `t:`t" FileGetVersionInfo( PeFile, "FileVersion"      ) "`n"
    . "InternalName         `t:`t" FileGetVersionInfo( PeFile, "InternalName"     ) "`n"
    . "LegalCopyright       `t:`t" FileGetVersionInfo( PeFile, "LegalCopyright"   ) "`n"
    . "OriginalFilename     `t:`t" FileGetVersionInfo( PeFile, "OriginalFilename" ) "`n"
    . "ProductName          `t:`t" FileGetVersionInfo( PeFile, "ProductName"      ) "`n"
    . "ProductVersion       `t:`t" FileGetVersionInfo( PeFile, "ProductVersion"   ) "`n`n`n"
    . "CompanyName          `t:`t" FileGetVersionInfo( PeFile, "CompanyName"      ) "`n"
    . "PrivateBuild         `t:`t" FileGetVersionInfo( PeFile, "PrivateBuild"     ) "`n"
    . "SpecialBuild         `t:`t" FileGetVersionInfo( PeFile, "SpecialBuild"     ) "`n"
    . "LegalTrademarks      `t:`t" FileGetVersionInfo( PeFile, "LegalTrademarks"  ) "`n"






Smile
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Wed Dec 17, 2008 5:48 am    Post subject: ColorAdjL() Reply with quote

Quote:
ColorAdjL()

Adjust Luminance for a given RGB color. In other words, this function can derive a lighter / darker shade for a given RGB color

Parameters.

Luminance : Value between 1 - 239 ( 0 is black and 240 is White )
RGB : The RGB color to be adjusted. If ignored, a random color will be generated and used

Usage Examples:
Code:
; To derive a dark / light shade of red
darkRed := ColorAdjL(  70, 0xFF0000 )
liteRed := ColorAdjL( 235, 0xFF0000 )

Code:
; To derive a random ( but matching ) dark / light shade
darkRandom := ColorAdjL(  70 )
liteRandom := ColorAdjL( 235, "0x" darkRandom )


Code:
ColorAdjL( Lum=235, RGB="" ) {
 IfEqual,RGB,, Random,RGB,1,16777215
 DllCall( "shlwapi\ColorRGBToHLS", UInt,RGB, UIntP,H, UIntP,L, UIntP,S )
 CC := DllCall( "shlwapi\ColorHLSToRGB", UInt,H, UInt,Lum, UInt,S )
 VarSetCapacity(RGB,6,0), DllCall( "msvcrt.dll\sprintf", Str,RGB, Str,"%06X", UInt,CC )
Return RGB
}

Gui +ToolWindow +AlwaysOnTop
Dark  := ColorAdjL(  70, 0xFF0000 )
Light := ColorAdjL( 235, 0xFF0000 )
Gui, Color, %Light%
Gui, Font, s50
Gui, Add, Text, x5 y5 w200 h75 c%Dark% Center vText, Hello
Gui, Font
Gui, Add, Edit, x36 y100 w30 h20 Limit3 Center vLum, 230
Gui, Add, Button, x+5 h20 w100 gChangeGuiColor, Random Color
Gui, Show, w210 h130, % " GuiColor : " Light
Return

ChangeGuiColor:
 GuiControlGet, Lum
 Light := ColorAdjL( Lum )
 Gui, Color, %Light%
 Gui, Show,, % " GuiColor : " Light
Return

GuiClose:
 ExitApp



Smile
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Sun Dec 28, 2008 1:48 pm    Post subject: SoundExClassic() Reply with quote

Quote:
SoundExC() - SoundEx Classic Version

Quote:
http://en.wikipedia.org/wiki/Soundex

Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for names with the same pronunciation to be encoded to the same representation so that they can be matched despite minor differences in spelling. Soundex is the most widely known of all phonetic algorithms and is often used (incorrectly) as a synonym for "phonetic algorithm". Improvements to Soundex are the basis for many modern phonetic algorithms


Quote:
How To: Understanding Classic SoundEx Algorithms

The Algorithm as an Outline
  • Capitalize all letters in the word and drop all punctuation marks. Pad the word with rightmost blanks as needed during each procedure step.
  • Retain the first letter of the word.
  • Change all occurrence of the following letters to '0' (zero):
    'A', E', 'I', 'O', 'U', 'H', 'W', 'Y'.
  • Change letters from the following sets into the digit given:
    1 = 'B', 'F', 'P', 'V'
    2 = 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z'
    3 = 'D','T'
    4 = 'L'
    5 = 'M','N'
    6 = 'R'
  • Remove all pairs of digits which occur beside each other from the string that resulted after step (4).
  • Remove all zeros from the string that results from step 5.0 (placed there in step 3)
  • Pad the string that resulted from step (6) with trailing zeros and return only the first four positions, which will be of the form <uppercase letter> <digit> <digit> <digit>.

The algorithm presented above is slightly improved over the originally patented algorithm.
The original Soundex algorithm of 1918 starts to fail when the number of words in the database gets to be large. For example, the diversity of names in a large database with many foreign spellings starts to put more and more phonetically unlike names into the same code.

The slightly improved algorithm presented here differs from the original in step three, where the vowel sounds are replaced with zeros ('0'), and in step (6.0) where those zeros are removed. The original algorithm eliminated the vowels completely in step 3.0, before duplicate adjacent digits are removed.

This improved version will produce SoundEx codes with duplicate digits in them; for example, "HERMAN" will code to "H06505" which will then reduce to "H655" in the last step. In the original version, "HERMAN" would code to "H655" which will then reduce to "H65" and finally to "H650" in the last step.


Code:
SoundExC( Wrd="" ) {
 Static A=0, B=1, C=2, D=3, E=0, F=1, G=2, H=0, I=0, J=2, K=2, L=4, M=5
 Static N=5, O=0, P=1, Q=2, R=6, S=2, T=3, U=0, V=1, W=0, X=2, Y=0, Z=2
 StringUpper, Wrd, Wrd
 Pre:=SubStr( Wrd,1,1 ), Prv:=%Pre%, Word:=SubStr(Wrd,2)
 Loop, Parse, Word
  If ( Asc(A_LoopField)>64 && Asc(A_LoopField)< 91 )
       StringReplace, Word, Word, %A_LoopField%, % %A_LoopField%
  Else StringReplace, Word, Word, %A_LoopField%
 Loop, Parse, Word
   SE .= A_LoopField=Prv ? "" : Prv:=A_LoopField
 StringReplace,SE,SE,0,, All
Return Pre SubStr( SE "000", 1,3 )
}

words=crazy|crazie|craezie|crazi|crasie|cracie|crecie|crazee|crezie|crraazziiee
Loop, Parse, words, |
  List .= A_LoopField "`t=  " SoundExC( A_LoopField ) "`n"
MsgBox, % List


Note: Leading spaces, if any, should be trimmed out before passing it to SoundExC()

Smile
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Sun Jan 11, 2009 12:06 am    Post subject: Reply with quote

Quote:
FA() - A Tiny 2L Function to maintain a single dimension UINT array

Code:
FA(E=0,V="",S="") { ; www.autohotkey.com/forum/viewtopic.php?p=242750#242750
 Static C,P
Return ((E+0)>=0&&V="")?(NumGet(P+0,E*4)):(E&&(V+0)>=0)?(NumPut(V,P+0,E*4)-4):(S="+"&&V
 >0)?((O:=NumPut((V:=NumGet(E*4+P)+V),E*4+P))-O+V):(S="-"&&V>0)?((O:=NumPut((V:=NumGet(E*4
 +P)-V),E*4+P))-O+V):(E>0&&V="Init")?(VarSetCapacity(C,(E+1)*4,0)+(P:=NumPut(E,C)-4)-P):(E
 ="Rel"&&P)?((P:=0)+VarSetCapacity(C,0)+1):(E="Ptr"&&P) ? P : ""
}

; The above ternary version was derived from following code

/*

FA( E=0,V="",S="" ) {
 Static C,P

 If ((E+0)>=0&&V="")                                           ;  NumGet
  Return (NumGet(P+0,E*4))

 If (E&&(V+0)>=0)                                              ;  NumPut
  Return (NumPut(V,P+0,E*4)-4)

 If (S="+"&&V>0)                                               ;  NumAdd
  Return ((O:=NumPut((V:=NumGet(E*4+P)+V),E*4+P))-O+V)

 If (S="-"&&V>0)                                               ;  NumSub
  Return ((O:=NumPut((V:=NumGet(E*4+P)-V),E*4+P))-O+V)

 If (E>0&&V="Init")                                            ;  Init Var
  Return,(VarSetCapacity(C,(E+1)*4,0)+(P:=NumPut(E,C)-4)-P)

 If (E="Rel"&&P)                                               ;  Release Var
  Return ((P:=0)+VarSetCapacity(C,0)+1)

 If (E="Ptr"&&P)                                               ;  Obtain Pointer
  Return P
}

*/



The primary objective of this function is to provide a mechanism to share Integers between functions, thereby avoiding a clutter of Global variables.
In short, FA() is a function that acts as an single dimension array

The parameters are cumbersome to document, and so, I provide here example calls, instead.

Basic:
Code:
FA(10,"Init")   ; Initialise capacity for 10 UINT elements
               ; Returns the Static Variable's size

FA(6,25000)     ; Put 25000 in element 6
               ; Returns the pointer to the UINT

FA(4,0)         ; Nullify element 4
               ; same as above

FA(7)           ; Return the value stored in element 7



Extended:
Support for counters.

Code:
FA(6,1230,"+")  ; Increment the value stored in element 6 by 1230
               ; Returns the new value

FA(6,1230,"-")  ; Decrement the value stored in element 6 by 1230
               ; Returns the new value


For any further manipulation, the pointer to the array can be retrieved..

Code:
FA("Ptr")


..and to release/reset the array

Code:
FA("Rel")



My Requirement:
With forth-coming release: 1.0.48, using ProcAddress directly in DllCall() would increase the performance significantly. I needed a mechanism to initialise the and share the ProcAddresses between many functions of the same wrapper - without creating global variables, and hence I wrote FA()

The following is a dumb, but working example of my intended use.

Code:
MsgBox, % FormatBytes( GetFileSize( A_AhkPath ) )
MsgBox, % FormatBytes( GetFileSize( A_ScriptFullPath ) )

GetFileSize( File ) { ; 4GB Limit
 Static Init,FOpen,FSeek,FClose
 If !Init
   Init:=InitAPI(), FOpen:=FA(1),FSeek:=FA(3),FClose:=FA(4)
 If ( H := DllCall(FOpen,Str,File,Int,0x0) ) < 1
    Return H
 FilePointer := DllCall(FSeek,Int,H,Int,0,Int,2), DllCall(FClose,UInt,H)
Return FilePointer
}

FormatBytes( Bytes ) {
 Static FormatBytes
 If !FormatBytes
     FormatBytes:=FA(11), VarSetCapacity(Formatted,16)
 DllCall(FormatBytes, Int64,Bytes, Str,Formatted, UInt,16 )
Return Formatted
}

InitAPI() {
 Static Funx
 IfNotEqual,Funx,,Return,Funx
 FA( 20, "Init" ) ; Initialise 20 UINT elements

 Kernel32 := DllCall( "GetModuleHandle", Str,"Kernel32.dll" )
 FA( 1, DllCall( "GetProcAddress", UInt,Kernel32, Str,"_lopen"  ) )
 FA( 2, DllCall( "GetProcAddress", UInt,Kernel32, Str,"_lread"  ) )
 FA( 3, DllCall( "GetProcAddress", UInt,Kernel32, Str,"_llseek" ) )
 FA( 4, DllCall( "GetProcAddress", UInt,Kernel32, Str,"_lclose" ) )
 FA( 5, DllCall( "GetProcAddress", UInt,Kernel32, Str,"_lcreat" ) )
 FA( 6, DllCall( "GetProcAddress", UInt,Kernel32, Str,"_lwrite" ) )
 FA( 7, DllCall( "GetProcAddress", UInt,Kernel32, Str,"RtlMoveMemory" ) )

 ShlwAPI := DllCall( "LoadLibrary", Str,"Shlwapi.dll" )
 FA( 11, DllCall( "GetProcAddress", UInt,ShlwAPI, Str,"StrFormatByteSize64A" ) )
 ; unused elements are for future use
Return (Funx:=1)
}

FA(E=0,V="",S="") { ; www.autohotkey.com/forum/viewtopic.php?p=242750#242750
Static C,P
Return ((E+0)>=0&&V="")?(NumGet(P+0,E*4)):(E&&(V+0)>=0)?(NumPut(V,P+0,E*4)-4):(S="+"&&V
 >0)?((O:=NumPut((V:=NumGet(E*4+P)+V),E*4+P))-O+V):(S="-"&&V>0)?((O:=NumPut((V:=NumGet(E*4
 +P)-V),E*4+P))-O+V):(E>0&&V="Init")?(VarSetCapacity(C,(E+1)*4,0)+(P:=NumPut(E,C)-4)-P):(E
 ="Rel"&&P)?((P:=0)+VarSetCapacity(C,0)+1):(E="Ptr"&&P) ? P : ""
}



Last edited by SKAN on Sun Jul 12, 2009 7:13 am; edited 2 times in total
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Sun May 31, 2009 9:42 am    Post subject: GetDeviceSerialFromUSBdrive() Reply with quote

Quote:
GetDeviceSerialFromUSBdrive()

2009-06-08: Deprecated, does not work in Vista! Use USBD_GetDeviceSerial() instead

Given an USB Storage Drive Letter, this function will retrieve the Serial Number and the Friendly name of the USB device by looking up the registry.

Reference: Ask for Help topic: possible to tell une usb stick from another?

Quote:
Note: Limited testing done only in XP SP2 - with available HW ( Flash Sticks, DSC, MP3 Player and Card Reader ) and results were compared with USBDeview


Code:
MsgBox, % GetDeviceSerialFromUSBdrive( "J:" ) ; Usage Example

GetDeviceSerialFromUSBdrive( Drv="" ) {
 DriveGet, DriveType, Type, %Drv%
 IfNotEqual,DriveType,Removable, Return
 RegRead, Hex, HKLM, SYSTEM\MountedDevices, \DosDevices\%Drv%
 VarSetCapacity(U,(Sz:=StrLen(Hex)//2)),  VarSetCapacity(A,Sz+1)
 Loop % Sz
  NumPut( "0x" . SubStr(hex,2*A_Index-1,2), U, A_Index-1, "Char" )
 DllCall( "WideCharToMultiByte", Int,0,Int,0, UInt,&U,UInt,Sz, Str,A,UInt,Sz, Int,0,Int,0)
 StringSplit, Part, A, #
 ParentIdPrefixCheck := SubStr( Part3,1,InStr(Part3,"&",0,0)-1 )
 Loop, HKLM, SYSTEM\CurrentControlSet\Enum\USBSTOR,1,0
 { Device := A_LoopRegName
   Loop, HKLM, SYSTEM\CurrentControlSet\Enum\USBSTOR\%Device%,1,0
 { Serial := A_LoopRegName
   RegRead, PIPrefix, HKLM, SYSTEM\CurrentControlSet\Enum\USBSTOR\%Device%\%Serial%
          , ParentIdPrefix
   If ( PIPrefix = ParentIdPrefixCheck ) {
   RegRead, DeviceFN, HKLM, SYSTEM\CurrentControlSet\Enum\USBSTOR\%Device%\%Serial%
          , FriendlyName
   Return, SubStr( Serial,1,InStr(Serial,"&",0,0)-1 ) " " DeviceFN
}}
}}


Smile



Snippet 1: Use a Removable Drive as a Key ( to lock / unlock your computer.. etc. )

Code:
DeviceFound := False
DriveFN := "GDLL4HW4 JetFlash TS4GJFV30 USB Device"
DriveGet, Drvs, List, Removable
Loop, Parse, Drvs
 If ( GetDeviceSerialFromUSBdrive( A_LoopField ":" ) == DriveFN ) {
      DeviceFound := True,  Drv := A_LoopField ":"
      Break
   }
If DeviceFound
     MsgBox, 64, USB Device Found, % DriveFN "`nfound in Drive " Drv
Else MsgBox, 16, USB Device Not Found, %DriveFN%
Return

; Copy/Paste GetDeviceSerialFromUSBdrive()


Snippet 2: Force your Compiled script to load only from a particular Removable Drive

Code:
SplitPath, A_ScriptFullPath,,,,, Drv
If ! ( GetDeviceSerialFromUSBdrive( Drv ) == "GDLL4HW4 JetFlash TS4GJFV30 USB Device" ) {
  MsgBox, 16, MySofwareName, Software Access Denied!`nThe Application will quit now, 7
  ExitApp
   }
   
; Copy/Paste GetDeviceSerialFromUSBdrive()
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Mon Jun 08, 2009 12:10 pm    Post subject: PixelCheckSum() Reply with quote

Quote:
PixelCheckSum()

Generates a CheckSum for a region of pixels in Screen/Window

Credit: Thanks to Sean. Screen Capture with Transparent Windows and Mouse Cursor

Code:
PixelCheckSum( X=0, Y=0, W=3, H=3, Title="" ) {
 hWn := WinExist( Title ), hDC := DllCall( "GetDC", UInt,hWn )
 mDC := DllCall( "CreateCompatibleDC", UInt,hDC )
 NumPut( VarSetCapacity(BI,40,0),BI ), NumPut( W,BI,4 ) , NumPut( H,BI,8 )
 NumPut( 32,NumPut( 1,BI,12,"UShort" ),0,"UShort" )     , NumPut( 0,BI,16 )
 hBM := DllCall( "CreateDIBSection", UInt,mDC, UInt,&BI , Int,0, UIntP,pB, Int,0,Int,0 )
 oBM := DllCall( "SelectObject", UInt,mDC, UInt,hBM )   , Rop := 0x40000000|0x00CC0020
 DllCall( "BitBlt", UInt,mDC, Int,0,Int,0, Int,W,Int,H, UInt,hDC, Int,X,Int,Y, UInt,Rop )
 DllCall( "shlwapi\HashData", UInt,pB, UInt,W*H*4, Int64P,Hash, UInt,8 )
 VarSetCapacity(HH,16,0), DllCall( "msvcrt\sprintf", Str,HH, Str,"%016I64X",UInt64,Hash )
 DllCall( "DeleteObject", UInt,hBM ), DllCall( "DeleteObject", UInt,oBM )
 DllCall( "DeleteDC", UInt,mDC ), DllCall( "ReleaseDC", UInt,hWn, UInt,hDC )
Return HH
}


Code:
; Example - Wait for a Screen Region to change
ChkSum := PixelChecksum( 0,0,10,10 )
While % ( ChkSum = PixelChecksum( 0,0,10,10 ) )
  Sleep, 100
MsgBox, Screen Region Change Detected!
Return



Smile
Back to top
View user's profile Send private message
n-l-i-d
Guest





PostPosted: Tue Jun 09, 2009 6:12 pm    Post subject: Reply with quote

Excellent! (as always)...

Cool
Back to top
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Wed Jun 17, 2009 1:35 pm    Post subject: Reply with quote

@daonlyfreez: Thanks friend Very Happy
Back to top
View user's profile Send private message
SKAN



Joined: 26 Dec 2005
Posts: 7187

PostPosted: Thu Jun 18, 2009 3:11 pm    Post subject: FileMD5() / MD5() Reply with quote

Quote:
FileMD5()

Computes and returns MD5 hash [ RFC1321 Specification ] for a File passed as parameter, with speeds comparable to Hashes.DLL.
You may refer MSDN for Message Digest API
    Parameters:

    sFile : The fullpath of filename to hash
    cSz : *Chunk size factor. Values accepted are 0 thru 8. Default value is 4

Quote:
* To hash large files, the function has to read the file in manageable chunks into a buffer variable.
The size of this buffer is derived from cSz parameter as follows:

0 = 256 KB, 1 = 512 KB, 2 = 1.00 MB, 3 = 2.00 MB, 4 = 4.00 MB, 5 = 8.00 MB, 6 = 16.0 MB, 7 = 32.0 MB, 8 = 64.0 MB

Refer AHK Documentation for #MaxMem


Code:
FileMD5( sFile="", cSz=4 ) { ; www.autohotkey.com/forum/viewtopic.php?p=275910#275910
 cSz  := (cSz<0||cSz>8) ? 2**22 : 2**(18+cSz), VarSetCapacity( Buffer,cSz,0 )
 hFil := DllCall( "CreateFile", Str,sFile,UInt,0x80000000, Int,1,Int,0,Int,3,Int,0,Int,0 )
 IfLess,hFil,1, Return,hFil
 DllCall( "GetFileSizeEx", UInt,hFil, Str,Buffer ),   fSz := NumGet( Buffer,0,"Int64" )
 VarSetCapacity( MD5_CTX,104,0 ),    DllCall( "advapi32\MD5Init", Str,MD5_CTX )
 Loop % ( fSz//cSz+!!Mod(fSz,cSz) )
   DllCall( "ReadFile", UInt,hFil, Str,Buffer, UInt,cSz, UIntP,bytesRead, UInt,0 )
 , DllCall( "advapi32\MD5Update", Str,MD5_CTX, Str,Buffer, UInt,bytesRead )
 DllCall( "advapi32\MD5Final", Str,MD5_CTX ), DllCall( "CloseHandle", UInt,hFil )
 Loop % StrLen( Hex:="123456789ABCDEF0" )
  N := NumGet( MD5_CTX,87+A_Index,"Char"), MD5 .= SubStr(Hex,N>>4,1) . SubStr(Hex,N&15,1)
Return MD5
}


Code:
MsgBox, % FileMD5( A_AhkPath ) ; Usage Example



    Edit 2009-06-18 :
  • An important bug fixed: Changed VarSetCapacity( MD5_CTX,24,0 ) to VarSetCapacity( MD5_CTX,128,0 )
  • Corrected again to VarSetCapacity( MD5_CTX,104,0). Thanks to Laszlo.




Quote:
MD5()

Computes and returns MD5 hash [ RFC1321 Specification ] for memory variable contents.

Code:
MD5( ByRef V, L=0 ) { ; www.autohotkey.com/forum/viewtopic.php?p=275910#275910
 VarSetCapacity( MD5_CTX,104,0 ), DllCall( "advapi32\MD5Init", Str,MD5_CTX )
 DllCall( "advapi32\MD5Update", Str,MD5_CTX, Str,V, UInt,L ? L : VarSetCapacity(V) )
 DllCall( "advapi32\MD5Final", Str,MD5_CTX )
 Loop % StrLen( Hex:="123456789ABCDEF0" )
  N := NumGet( MD5_CTX,87+A_Index,"Char"), MD5 .= SubStr(Hex,N>>4,1) . SubStr(Hex,N&15,1)
Return MD5
}

; Usage Example

V := "The quick brown fox jumps over the lazy dog"
L := StrLen(V)
MsgBox, % MD5( V,L )




Last edited by SKAN on Sun Jun 21, 2009 7:34 pm; edited 3 times in total
Back to top
View user's profile Send private message
infogulch



Joined: 27 Mar 2008
Posts: 378

PostPosted: Thu Jun 18, 2009 4:32 pm    Post subject: Reply with quote

Cool MD5 functions!

AutoHotkey Doesn't have an md5 function on rosetta code yet:
http://www.rosettacode.org/wiki/Tasks_not_implemented_in_AutoHotkey

You (or somebody) should post on Rosetta Code's MD5 page: http://www.rosettacode.org/wiki/MD5

Thanks!
_________________

Scripts
- License
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions All times are GMT
Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9  Next
Page 8 of 9

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group