Leaderboard
Popular Content
Showing content with the highest reputation on 08/30/2013 in all areas
-
Although serial ports are disappearing, they can still be useful. Here is a COMMs UDF. It provides an easy way to use serial ports without the restrictions and problems some methods have. USB to serial is ok, binary data is ok. This UDF requires my comMG.dll which can be in either the script folder or the Windows folder by default, or in the path specified using the function _CommSetDllPath. Note the following shortcomings: the dll link below is 32 bit so it will not work with a 64 bit apps, but there is a 64 bit version in my post around 25th March 2018 for people to try. The strings and character functions are all AnsiChar. Functions in the UDF are _CommVersion _CommListPorts _CommSetPort _CommPortConnection _CommClearOutputBuffer _CommClearInputBuffer _CommGetInputcount _CommGetOutputcount _CommSendString _CommGetString _CommGetLine _CommReadByte _CommReadChar _CommSendByte _CommSendBreak; not tested!!!!!!!!!! _CommCloseport _CommSwitch _CommReadByteArray _CommSendByteArray _CommsetTimeouts _CommSetXonXoffProperties _CommSetRTS (NB these will not work if Hardware handshaking is selected because _CommSetDTR then these lines are controlled by the data being sent.) _CommSetDllPath _CommGetLineStates -------------------------------------------------------------------------------------------------------------------------------- Go to Download Page For Commgv2 Download includes the dll and udf. Most recent changes 28th March 2014 - dll V2.83 Correct error setting 6 data bits as 7. 11th March 2014 dll V2.82 Allow data bits of 4 to 8 instead of only 7 and 8. 19th August 2013 dll v2.81 removes some unwanted eroor message popups. Might not remove popups for some Windows versions. 27th September 2012 Correct error closing port. New version of UDF if V2.90, new dll is commg.dll V2.79. Thanks to tfabris. 18th January 2012 Corrected typo in UDF V 2.87, and uploaded as V2.88 Increased max baud allowed by the dll from 200000 to 256000. New version now V2.78 17th January 2012 Modified thesleep addition to _CommGetLine so that reading data is not slowed down. 14th January 2012 Corrected _CommReadByte in UDF. Added sleep(20) to while loop in _CommGetLine to reduce CPU usage 20th December 2011 UDF version 2.86. - Changed function GetByte so it returned the error string given by the dll. Dll version 2.77 - removed an unwanted erro message dialogue from GetByte function. (Thanks funkey) 4th December 2011 New dll and example versions. Dll function SetPort corrected because it was not using the parameters passed for DTR and RTS. The example was setting flow control incorrectly: the settings for hardware handshaking and XON./XOFF were reversed. 25th August 2011 corrected function _CommClosePort. Example corrected for setting parity and flow 22nd December 2013 (thanks to MichaelXMike) mgrefcommg CommgExample.au31 point
-
I recently bought an IP Camera to monitor my house. There is a web access to view the video stream but not to record it. Here is the IP Camera in question, it should work with every other similar product. So I made a simple example which does the job. Here is the code : #include <GUIConstants.au3> #include <WindowsConstants.au3> #include <StaticConstants.au3> #include <WinAPI.au3> #include <GDIPlus.au3> #include <Memory.au3> #region Global Vars Global Const $sProgramTitle = "IP Camera stream + record" ;EDIT THE FOLLOWING LINE ONLY: Global Const $iIPAddress = "192.168.1.99", $iPort = 99, $shtauth = "yourauth==" Global Const $STM_SETIMAGE = 0x0172 Global $blRecording = False, $blGUIMinimized = False Global Const $sRecordDir = @ScriptDir & "\ip_camera_stream" Global $bRecvtmp = Binary(""), $bStream = $bRecvtmp Global $iImgLen = 0, $iStreamLen = 0, $iWritten = 0, $iEOH = 0, $iContLenPos = 0, $hImgFile = 0, $pBuffer = 0, $iImgCount = 0 Global Const $iContLengthLen = StringLen("Content-Length: ") Global $sStream = "", $sTrim2ContLen = "" Global $hBMP = 0, $hGraphics = 0, $hHBITMAP2 = 0, $hFamily = 0, $hFont = 0, $tLayout = "", $hFormat = 0, $hBrush = 0 #endregion Global Vars TCPStartup() Global $iSocket = TCPConnect($iIPAddress, $iPort) If @error Then MsgBox(16, $sProgramTitle, "Could not connect !") Exit -1 EndIf TCPSend($iSocket, _ "GET /videostream.cgi HTTP/1.1" & @CRLF & _ "Host: " & $iIPAddress & ":" & $iPort & @CRLF & _ "Connection: keep-alive" & @CRLF & _ "Authorization: Basic " & $shtauth & @CRLF & @CRLF) #region GUI Global $hGUI = 0, $pPic = 0, $hPic = 0, $btnRecord = 0 $hGUI = GUICreate($sProgramTitle, 640, 525) $pPic = GUICtrlCreatePic("", 0, 0, 640, 480, $SS_BITMAP) GUICtrlSetState($pPic, $GUI_DISABLE) $hPic = GUICtrlGetHandle($pPic) $btnRecord = GUICtrlCreateButton("Record", 10, 490, 80, 26) GUIRegisterMsg($WM_SYSCOMMAND, "WM_SYSCOMMAND") GUISetState(@SW_SHOW, $hGUI) #endregion GUI _GDIPlus_Startup() $hFamily = _GDIPlus_FontFamilyCreate("Arial") $hFont = _GDIPlus_FontCreate($hFamily, 17) $tLayout = _GDIPlus_RectFCreate(10, 10, 100, 40) $hFormat = _GDIPlus_StringFormatCreate() $hBrush = _GDIPlus_BrushCreateSolid(0xAFFF0000) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop Case $btnRecord If $blRecording Then GUICtrlSetData($btnRecord, "Record") Else If Not FileExists($sRecordDir) Then DirCreate($sRecordDir) GUICtrlSetData($btnRecord, "Stop recording") EndIf $blRecording = Not $blRecording EndSwitch $bRecvtmp = TCPRecv($iSocket, 4096, 1) ;4kb If @error Then ExitLoop If Not BinaryLen($bRecvtmp) Then ContinueLoop $bStream &= $bRecvtmp If $iImgLen = 0 Then $sStream = BinaryToString($bStream) $iContLenPos = StringInStr($sStream, "Content-Length: ", 2) $iEOH = StringInStr($sStream, @CRLF & @CRLF, 2, 1, $iContLenPos) If $iEOH = 0 Or $iContLenPos = 0 Then ContinueLoop $sTrim2ContLen = StringTrimLeft($sStream, $iContLenPos + $iContLengthLen - 1) $iImgLen = Number(StringLeft($sTrim2ContLen, StringInStr($sTrim2ContLen, @CR, 2) - 1)) $bStream = BinaryMid($bStream, $iEOH + 4) EndIf If $iImgLen = 0 Then ContinueLoop $iStreamLen = BinaryLen($bStream) If $iStreamLen < $iImgLen Then ContinueLoop If Not $blGUIMinimized Then $hBMP = Load_BMP_From_Mem($bStream) If $blRecording Then $hGraphics = _GDIPlus_ImageGetGraphicsContext($hBMP) _GDIPlus_GraphicsDrawStringEx($hGraphics, "[•REC]", $hFont, $tLayout, $hFormat, $hBrush) EndIf $hHBITMAP2 = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBMP) _WinAPI_DeleteObject(_SendMessage($hPic, $STM_SETIMAGE, 0, $hHBITMAP2)) _GDIPlus_ImageDispose($hBMP) If $blRecording Then _GDIPlus_GraphicsDispose($hGraphics) _WinAPI_DeleteObject($hHBITMAP2) EndIf If $blRecording Then $pBuffer = DllStructCreate("byte[" & $iImgLen & "]") If $iStreamLen > $iImgLen Then DllStructSetData($pBuffer, 1, BinaryMid($bStream, 1, $iImgLen)) $bStream = BinaryMid($bStream, $iImgLen) Else DllStructSetData($pBuffer, 1, $bStream) $bStream = Binary("") EndIf $hImgFile = _WinAPI_CreateFile($sRecordDir & "\snap_" & StringFormat("%.4d", $iImgCount) & ".jpg", 3, 4, 4) _WinAPI_WriteFile($hImgFile, DllStructGetPtr($pBuffer), $iImgLen, $iWritten) _WinAPI_CloseHandle($hImgFile) $iImgCount += 1 EndIf $iImgLen = 0 WEnd _GDIPlus_FontDispose($hFont) _GDIPlus_FontFamilyDispose($hFamily) _GDIPlus_StringFormatDispose($hFormat) _GDIPlus_BrushDispose($hBrush) _GDIPlus_Shutdown() TCPCloseSocket($iSocket) TCPShutdown() Func WM_SYSCOMMAND($hWnd, $iMsg, $wParam, $lParam) Local Const $SC_MINIMIZE = 0xF020, $SC_RESTORE = 0xF120 Switch BitAND($wParam, 0xFFF0) Case $SC_MINIMIZE, $SC_RESTORE $blGUIMinimized = Not $blGUIMinimized EndSwitch Return $GUI_RUNDEFMSG EndFunc ;==>WM_SYSCOMMAND Func Load_BMP_From_Mem($bImage) ;_GDIPlus_BitmapCreateFromMemory2 ;Author: UEZ ;Modified: ProgAndy, Yashied, FireFox If Not IsBinary($bImage) Then Return 0 Local $memBitmap = Binary($bImage) Local $iLen = BinaryLen($memBitmap) Local $GMEM_MOVEABLE = 0x0002 Local $aResult = DllCall("kernel32.dll", "handle", "GlobalAlloc", "uint", $GMEM_MOVEABLE, "ulong_ptr", $iLen) Local $hData = $aResult[0] $aResult = DllCall("kernel32.dll", "ptr", "GlobalLock", "handle", $hData) If @error Then Return 0 Local $tMem = DllStructCreate("byte[" & $iLen & "]", $aResult[0]) DllStructSetData($tMem, 1, $memBitmap) DllCall("kernel32.dll", "bool", "GlobalUnlock", "handle", $hData) If @error Then Return 0 $aResult = DllCall("ole32.dll", "int", "CreateStreamOnHGlobal", "handle", $hData, "int", True, "ptr*", 0) $hStream = $aResult[3] If @error Then Return 0 $aResult = DllCall($ghGDIPDll, "uint", "GdipCreateBitmapFromStream", "ptr", $hStream, "int*", 0) If @error Then Return 0 DllCall('oleaut32.dll', 'long', 'DispCallFunc', 'ptr', $hStream, 'ulong_ptr', 8 * (1 + @AutoItX64), 'uint', 4, 'ushort', 23, 'uint', 0, 'ptr', 0, 'ptr', 0, 'str', '') Return $aResult[2] EndFunc ;==>Load_BMP_From_Mem _ Advanced example : Preview : Attachment : IP Camera.au3 IP Camera.au3 (Previous: 34 downloads) Enjoy, I'm watching U !1 point
-
BinaryToAu3Kompressor v1.0.5.4 It's now possible to see the best compression ratio using LZMA, LZNT and Base64 compressions with differents combinations. Nothing too complicate, you drag'n drop a file on the picture and script Test all compression types and return the ratios. ( Test duration depends of file size, slowest compression is LZNT, but all decompressions are fast ) Free to you after, to choose the compression(s) you want... Yes, LZMA needs a dll ( embedded & compressed in script ) but brings a powerfull compression. It opens scite with your file compressed to an au3 script with or without decompression function as you want. Hold Left Shift key when clicking button for just copy script to clipboard. Use the 3 compressions at a time works but doesn't give a good ratio, that's why i don't display it. Usefull for little files you want include in your scripts ! No externals files needed, they are already in script. Previous downloads : 1103 Source and Executable BinaryToAu3Kompressor will be added to the next version of >SciTEHopper Thanks to Ward for his >Base64.au3 and LZMA.au3, and trancexx for his >LZNT functions and his >Base64Decode function.1 point
-
SciTE Hopper : Jump to Any line by one click and many other helpfull functions ! As Ashalshaikh suggested me after leaving me the task to continue >SciTE Hopper, i open a new Topic about it. It will be more easy for futures updates. Many helpfull functions in contextual menu. SciTE Hopper is now multipurpose. • Color Catcher added • BinaryToAu3Kompressor added • TinyAu3Search replaced by StringFinder • RegJumper added • Edit With SciTE added (available in Options) • SpecialCharactersViewer added (available in Tray menu) New Contextual Menu : For a right Click on a function : • Copy function name • Insert a function header • Cut function • Copy function • Delete function • Create a variables List • Remove usseless Blank lines • Remove Debug lines ( all lines starting with ConsoleWrite or _ArrayDisplay ) • Set AutoIt Code Layout • Remove Comments For entire script : • Create a functions List • Create a variables List • Remove usseless Blank lines • Remove Debug lines ( all lines starting with ConsoleWrite or _ArrayDisplay ) • Set AutoIt Code Layout • Remove Comments • ( Open in SciTE a ) Duplicate of current Script in Temp Dir • ( Open in SciTE a ) Duplicate of current Script in Same Dir • Explore Parent Script Folder • Copy Script name • Copy Script path • Find Unused Functions • Find Unused Variables • Set all functions in alphabetic order.( func headers and regions ( in fact, all lines between functions ) are not supported.) SciTE Editor New Contextual Menu if SciTE Hopper is added ( in Options ) to SciTE Editor : when you made a selection in SciTE Editor you can : • Open a Reg Key in Regedit using RegJumper • Open a Url in your default Browser • Search on google in your default Browser • Search on AutoIt Website in your default Browser Now Can be added to windows start (minimized) Options are available by Tray Menu. A double click on tray icon will open clipboard content to SciTE Editor ( Handy when you have copied some code from your browser ) How to proceed for add SciTE Hopper to SciTE Editor : Run Scite Editor, run Scite Hopper ( compiled! ) go to Options and select Add/Remove to SciTE Tab. then click on Add button and it's done ! Right click on SciTE Editor and choose SciTE Hopper in Contextual Menu for run it when you need it ! Update of 07 Dec 2017 TinyAu3Search is replaced by StringFinder Previous downloads : 1287 Script and compiled version are available in the download section Thanks to Ashalshaikh, Melba23, Th3 MMA, Alzri2, taitel, Manadar, taz742, Yashield, Authenticity, Xenobiologist for their help and asdf8 for his >Includes Helper and azjio for his >FileSearch. Hope it help you and happy Scripting !1 point
-
Hello, if an IP address is not reachable then TCPConnect lasts about 21 seconds for me the return with the error. Now I wrote a function using my socket_UDF to set a timeout if the IP address cannot be reached. Have fun. _TCPConnectTimeout example #include "socket_UDF.au3" Global $iTimerStart, $iSock Global $TestIP = "1.2.3.4" Global $TestPort = 800 Global $ConnectionTimeout = 1000 _WSAStartup() Global $iTimerStart = TimerInit() $iSock = _TCPConnectTimeout($TestIP, $TestPort, $ConnectionTimeout) ConsoleWrite("_TCPConnectTimeout error: " & @error & " / new socket: " & $iSock & @CRLF) ConsoleWrite("Function lasts: " & Round(TimerDiff($iTimerStart), 3) & @LF) $iTimerStart = TimerInit() $iSock = TCPConnect($TestIP, $TestPort) ConsoleWrite("TCPConnect error: " & @error & " / new socket: " & $iSock & @CRLF) ConsoleWrite("Function lasts: " & Round(TimerDiff($iTimerStart), 3) & @LF) ; about 21 seconds for me _WSACleanup() Exit Func _TCPConnectTimeout($IP, $Port, $Timeout) Local Const $WSAEWOULDBLOCK = 10035 Local $iSocket, $iResult, $tTimeout, $tWrite, $tErr $iSocket = _socket() If $iSocket = $SOCKET_ERROR Then Return SetError(1, 0, -1) $iResult = _ioctlsocket($iSocket, $FIONBIO, 1) ; nonblocking socket If $iResult <> 0 Then _closesocket($iSocket) Return SetError(2, 0, -1) EndIf $iResult = _connect($iSocket, $IP, $Port) If $iResult = $SOCKET_ERROR Then If _WSAGetLastError() = $WSAEWOULDBLOCK Then $tWrite = DllStructCreate($tagFd_set) $tErr = DllStructCreate($tagFd_set) _FD_SET($iSocket, $tWrite) _FD_SET($iSocket, $tErr) $iResult = _selectEx(0, DllStructGetPtr($tWrite), DllStructGetPtr($tErr), $Timeout) If $iResult <= 0 Then _closesocket($iSocket) Return SetError(3, 0, -1) ;timeout Else If Not _FD_ISSET($iSocket, $tWrite) Then _closesocket($iSocket) Return SetError(4, 0, -1) ; $tErr must have been set EndIf EndIf Else _closesocket($iSocket) Return SetError(5, 0, -1) ; another WSA error EndIf EndIf $iResult = _ioctlsocket($iSocket, $FIONBIO, 0) ; blocking socket again If $iResult <> 0 Then _closesocket($iSocket) Return SetError(6, 0, -1) EndIf Return $iSocket EndFunc ;==>_TCPConnectTimeoutsocket_UDF #include-once ; Some socket functions ; Author: funkey ; Project start 2013.03.12 ; Actual project date 2013.08.27 Global Const $tagIN_ADDR = "ulong S_addr;" Global Const $tagSockAddr = "USHORT sa_family;char sa_data[14]" Global Const $tagSockAddr_In = "short sin_family;USHORT sin_port;ULONG sin_addr;char sin_zero[8]" Global Const $tagSockAddr_Storage = "short ss_family;char ss_pad1[6];INT64 ss_align;char ss_pad1[112]" Global Const $tagTimeVal = "long tv_sec;long tv_usec" Global Const $tagAddrInfo = "int ai_flags;int ai_family;int ai_socktype;int ai_protocol;uint ai_addrlen;ptr ai_canonname;ptr ai_addr;ptr ai_next" Global Const $FD_SETSIZE = 64 Global Const $tagFd_set = "UINT fd_count;UINT fd_array[" & $FD_SETSIZE & "]" Global Const $AF_UNSPEC = 0 Global Const $AF_UNIX = 1 Global Const $AF_INET = 2 Global Const $AF_IMPLINK = 3 Global Const $AF_PUP = 4 Global Const $AF_CHAOS = 5 Global Const $AF_IPX = 6 Global Const $AF_NS = 6 Global Const $AF_ISO = 7 Global Const $AF_OSI = $AF_ISO Global Const $AF_ECMA = 8 Global Const $AF_DATAKIT = 9 Global Const $AF_CCITT = 10 Global Const $AF_SNA = 11 Global Const $AF_DECnet = 12 Global Const $AF_DLI = 13 Global Const $AF_LAT = 14 Global Const $AF_HYLINK = 15 Global Const $AF_APPLETALK = 16 Global Const $AF_NETBIOS = 17 Global Const $AF_VOICEVIEW = 18 Global Const $AF_FIREFOX = 19 Global Const $AF_UNKNOWN1 = 20 Global Const $AF_BAN = 21 Global Const $AF_ATM = 22 Global Const $AF_INET6 = 23 Global Const $SOCKET_ERROR = -1 Global Const $INVALID_SOCKET = -1 Global Const $SOCK_STREAM = 1 Global Const $SOCK_DGRAM = 2 Global Const $SOCK_RAW = 3 Global Const $SOCK_RDM = 4 Global Const $SOCK_SEQPACKET = 5 Global Const $IPPROTO_IP = 0 Global Const $IPPROTO_ICMP = 1 Global Const $IPPROTO_IGMP = 2 Global Const $IPPROTO_GGP = 3 Global Const $IPPROTO_TCP = 6 Global Const $IPPROTO_PUP = 12 Global Const $IPPROTO_UDP = 17 Global Const $IPPROTO_IDP = 22 Global Const $IPPROTO_ND = 77 Global Const $IPPROTO_RAW = 255 Global Const $SOL_SOCKET = 0xFFFF ;SOL_SOCKET Socket Options ;http://msdn.microsoft.com/en-us/library/windows/desktop/ms740532(v=vs.85).aspx Global Const $IP_OPTIONS = 1 Global Const $SO_DEBUG = 1 Global Const $SO_ACCEPTCONN = 2 Global Const $SO_REUSEADDR = 4 ; BOOLEAN Global Const $SO_KEEPALIVE = 8 Global Const $SO_DONTROUTE = 16 Global Const $SO_BROADCAST = 32 ;INT Global Const $SO_USELOOPBACK = 64 Global Const $SO_LINGER = 128 Global Const $SO_OOBINLINE = 256 Global Const $SO_EXCLUSIVEADDRUSE = -5 ; BOOLEAN (~SO_REUSEADDR) Global Const $SO_DONTLINGER = -129 ; (~SO_LINGER) Global Const $SO_SNDBUF = 0x1001 Global Const $SO_RCVBUF = 0x1002 Global Const $SO_SNDLOWAT = 0x1003 Global Const $SO_RCVLOWAT = 0x1004 Global Const $SO_SNDTIMEO = 0x1005 ; DWORD Global Const $SO_RCVTIMEO = 0x1006 ; DWORD Global Const $SO_ERROR = 0x1007 Global Const $SO_TYPE = 0x1008 Global Const $FIONBIO = 0x8004667E Global Const $FIONREAD = 0x4004667F Global Const $FIOASYNC = 0x8004667D Global Const $SIOCSHIWAT = 0x80047300 Global Const $SIOCGHIWAT = 0x80047301 Global Const $SIOCSLOWAT = 0x80047302 Global Const $SIOCGLOWAT = 0x80047303 Global Const $SIOCATMARK = 0x40047307 ;max backlog for listen() Global Const $SOMAXCONN = 0x7fffffff ;flags for send(to) Global Const $MSG_DONTROUTE = 4 Global Const $MSG_OOB = 1 Global $hDLL_WS2_32 = 0 Func _WSAStartup() If $hDLL_WS2_32 = 0 Then $hDLL_WS2_32 = DllOpen("ws2_32.dll") If $hDLL_WS2_32 = -1 Then $hDLL_WS2_32 = 0 Return 0 EndIf If TCPStartup() = 0 Then ;TCPStartup() is equal to WSAStartup function DllClose($hDLL_WS2_32) $hDLL_WS2_32 = 0 Return 0 EndIf EndIf Return 1 EndFunc ;==>_WSAStartup Func _WSACleanup() If $hDLL_WS2_32 <> 0 Then TCPShutdown() ;TCPShutdown() is equal to WSACleanup function DllClose($hDLL_WS2_32) $hDLL_WS2_32 = 0 EndIf Return 1 EndFunc ;==>_WSACleanup Func _setsockopt($iSocket, $iLevel, $iOptName, $tOptVal) Local $iOptLen = DllStructGetSize($tOptVal) Local $aRet = DllCall($hDLL_WS2_32, "int", "setsockopt", "uint", $iSocket, "int", $iLevel, "int", $iOptName, "struct*", $tOptVal, "int", $iOptLen) Return $aRet[0] EndFunc ;==>_setsockopt Func _getsockopt($iSocket, $iLevel, $iOptName, ByRef $tOptVal) Local $iOptLen = DllStructGetSize($tOptVal) Local $aRet = DllCall($hDLL_WS2_32, "int", "setsockopt", "uint", $iSocket, "int", $iLevel, "int", $iOptName, "struct*", $tOptVal, "int", $iOptLen) Return $aRet[0] EndFunc ;==>_getsockopt Func _socket($AF = $AF_INET, $SocketType = $SOCK_STREAM, $Protocol = $IPPROTO_TCP) ; AF_INET, SOCK_STREAM, IPPROTO_TCP Local $aRet = DllCall($hDLL_WS2_32, "int", "socket", "int", $AF, "int", $SocketType, "int", $Protocol) Return $aRet[0] EndFunc ;==>_socket Func _closesocket($iSocket) Local $aRet = DllCall($hDLL_WS2_32, "int", "closesocket", "UINT", $iSocket) Return $aRet[0] EndFunc ;==>_closesocket ;shutdown() allows you to cut off communication in a certain direction, or both ways (just like closesocket() does.) ;0 Further receives are disallowed ;1 Further sends are disallowed ;2 Further sends and receives are disallowed (like closesocket()) ;It's important to note that shutdown() doesn't actually close the file descriptor — it just changes ;its usability. To free a socket descriptor, you need to use closesocket(). Func _shutdown($iSocket, $iHow) Local $aRet = DllCall($hDLL_WS2_32, "int", "shutdown", "UINT", $iSocket, "int", $iHow) Return $aRet[0] EndFunc ;==>_shutdown Func _bind($iSocket, $sIP, $iPort) Local $tSockAddr_In = DllStructCreate($tagSockAddr_In) Local $pSockAddr_In = DllStructGetPtr($tSockAddr_In) Local $iSizeSockAddr_In = DllStructGetSize($tSockAddr_In) DllStructSetData($tSockAddr_In, "sin_family", $AF_INET) DllStructSetData($tSockAddr_In, "sin_port", _htons($iPort)) DllStructSetData($tSockAddr_In, "sin_addr", _inet_addr($sIP)) Local $aRet = DllCall($hDLL_WS2_32, "int", "bind", "UINT", $iSocket, "struct*", $pSockAddr_In, "int", $iSizeSockAddr_In) Return $aRet[0] EndFunc ;==>_bind Func _connect($iSocket, $sIP, $iPort) Local $tSockAddr_In = DllStructCreate($tagSockAddr_In) Local $iSizeSockAddr_In = DllStructGetSize($tSockAddr_In) DllStructSetData($tSockAddr_In, "sin_family", $AF_INET) DllStructSetData($tSockAddr_In, "sin_port", _htons($iPort)) DllStructSetData($tSockAddr_In, "sin_addr", _inet_addr($sIP)) Local $aRet = DllCall($hDLL_WS2_32, "int", "connect", "UINT", $iSocket, "struct*", $tSockAddr_In, "int", $iSizeSockAddr_In) Return $aRet[0] EndFunc ;==>_connect Func _listen($iSocket, $iBacklog = $SOMAXCONN) Local $aRet = DllCall($hDLL_WS2_32, "int", "listen", "UINT", $iSocket, "int", $iBacklog) Return $aRet[0] EndFunc ;==>_listen Func _accept($iSocket, ByRef $sIP, ByRef $iPort) Local $tAddr = DllStructCreate($tagSockAddr_In) Local $aRet = DllCall($hDLL_WS2_32, "UINT", "accept", "UINT", $iSocket, "struct*", $tAddr, "int*", DllStructGetSize($tAddr)) $iPort = _ntohs(DllStructGetData($tAddr, 2)) $sIP = _inet_ntoa(DllStructGetData($tAddr, 3)) Return $aRet[0] EndFunc ;==>_accept Func _select(ByRef $tReadFds, $iTimeout) Local $tTimeout = DllStructCreate($tagTimeVal) DllStructSetData($tTimeout, "tv_sec", Floor($iTimeout / 1000)) DllStructSetData($tTimeout, "tv_usec", ($iTimeout - DllStructGetData($tTimeout, "tv_sec") * 1000) * 1000) Local $aRet = DllCall($hDLL_WS2_32, "int", "select", "int", 0, "struct*", $tReadFds, "ptr", 0, "ptr", 0, "struct*", $tTimeout) Return $aRet[0] ;-1 = error; 0 = timeout; else data! EndFunc ;==>_select Func _selectEx($pReadFds, $pWriteFds, $pExceptFds, $iTimeout) Local $tTimeout = DllStructCreate($tagTimeVal) DllStructSetData($tTimeout, "tv_sec", Floor($iTimeout / 1000)) DllStructSetData($tTimeout, "tv_usec", ($iTimeout - DllStructGetData($tTimeout, "tv_sec") * 1000) * 1000) Local $aRet = DllCall($hDLL_WS2_32, "int", "select", "int", 0, "ptr", $pReadFds, "ptr", $pWriteFds, "ptr", $pExceptFds, "struct*", $tTimeout) Return $aRet[0] ;-1 = error; 0 = timeout; else data! EndFunc ;==>_selectEx Func _FD_ZERO(ByRef $tFd_set) DllStructSetData($tFd_set, "fd_count", 0) EndFunc ;==>_FD_ZERO Func _FD_SET($iSock, ByRef $tFd_set) Local $iCount = DllStructGetData($tFd_set, "fd_count") For $i = 0 To $iCount - 1 If DllStructGetData($tFd_set, "fd_Array", $i + 1) = $iSock Then ExitLoop EndIf Next If $i = $iCount Then If $iCount < $FD_SETSIZE Then DllStructSetData($tFd_set, "fd_array", $iSock, $i + 1) DllStructSetData($tFd_set, "fd_count", $iCount + 1) EndIf EndIf EndFunc ;==>_FD_SET Func _FD_CLR($iSock, ByRef $tFd_set) Local $iCount = DllStructGetData($tFd_set, "fd_count") For $i = 0 To $iCount - 1 If DllStructGetData($tFd_set, "fd_array", $i + 1) = $iSock Then While ($i < $iCount - 1) DllStructSetData($tFd_set, "fd_array", DllStructGetData($tFd_set, "fd_array", $i + 2), $i + 1) $i += 1 WEnd EndIf DllStructSetData($tFd_set, "fd_count", $iCount - 1) ExitLoop Next EndFunc ;==>_FD_CLR Func _FD_ISSET($iSock, ByRef $tFd_set) Local $aRet = DllCall($hDLL_WS2_32, "int", "__WSAFDIsSet", "UINT", $iSock, "struct*", $tFd_set) Return $aRet[0] EndFunc ;==>_FD_ISSET Func _send($iSocket, ByRef $tBuffer, $iFlags = 0) Local $iLen = DllStructGetSize($tBuffer) Local $aRet = DllCall($hDLL_WS2_32, "int", "send", "int", $iSocket, "struct*", $tBuffer, "int", $iLen, "int", $iFlags) Return $aRet[0] EndFunc ;==>_send Func _sendto($iSocket, ByRef $tBuffer, ByRef $tTo, $iFlags = 0) Local $iLen = DllStructGetSize($tBuffer) Local $iLenTo = DllStructGetSize($tTo) Local $aRet = DllCall($hDLL_WS2_32, "int", "sendto", "int", $iSocket, "struct*", $tBuffer, "int", $iLen, "int", $iFlags, "struct*", $tTo, "int", $iLenTo) Return $aRet[0] EndFunc ;==>_sendto Func _recv($iSocket, ByRef $tBuffer, $iFlags = 0) Local $iLen = DllStructGetSize($tBuffer) Local $aRet = DllCall($hDLL_WS2_32, "int", "recv", "uint", $iSocket, "struct*", $tBuffer, "int", $iLen, "int", $iFlags) Return $aRet[0] EndFunc ;==>_recv Func _recvfrom($iSocket, ByRef $tBuffer, ByRef $tFrom, $iFlags = 0) Local $iLen = DllStructGetSize($tBuffer) Local $iLenFrom = DllStructGetSize($tFrom) Local $aRet = DllCall($hDLL_WS2_32, "int", "recvfrom", "uint", $iSocket, "struct*", $tBuffer, "int", $iLen, "int", $iFlags, "struct*", $tFrom, "int", $iLenFrom) Return $aRet[0] EndFunc ;==>_recvfrom Func _inet_addr($sIP) Local $aRet = DllCall($hDLL_WS2_32, "ULONG", "inet_addr", "str", $sIP) Return $aRet[0] EndFunc ;==>_inet_addr Func _inet_ntoa($pIn_Addr) ;only IPv4 (deprecated) --> use _inet_ntop() instead Local $aRet = DllCall($hDLL_WS2_32, "str", "inet_ntoa", "ptr", $pIn_Addr) Return $aRet[0] EndFunc ;==>_inet_ntoa Func _inet_ntop($pIn_Addr, $iFamily = $AF_INET) ;IPv4 and IPv6 --> Vista and above Local $tBuffer = DllStructCreate("char[46]") ;16 for IPv4, 46 for IPv6 Local $aRet = DllCall($hDLL_WS2_32, "str", "inet_ntop", "int", $iFamily, "ptr", $pIn_Addr, "struct*", $tBuffer, "int", DllStructGetSize($tBuffer)) Return DllStructGetData($tBuffer, 1) EndFunc ;==>_inet_ntop ;host byte order to network byte order (double) Func _htond($value) Local $aRet = DllCall($hDLL_WS2_32, "UINT64", "htond", "double", $value) Return $aRet[0] EndFunc ;==>_htond ;host byte order to network byte order (float) Func _htonf($value) Local $aRet = DllCall($hDLL_WS2_32, "UINT", "htonf", "float", $value) Return $aRet[0] EndFunc ;==>_htonf ;host byte order to network byte order (long) Func _htonl($value) Local $aRet = DllCall($hDLL_WS2_32, "ULONG", "htonl", "ULONG", $value) Return $aRet[0] EndFunc ;==>_htonl ;host byte order to network byte order (long long) Func _htonll($value) Local $aRet = DllCall($hDLL_WS2_32, "UINT64", "htonll", "UINT64", $value) Return $aRet[0] EndFunc ;==>_htonll ;host byte order to network byte order (short) Func _htons($iPort) Local $aRet = DllCall($hDLL_WS2_32, "USHORT", "htons", "USHORT", $iPort) Return $aRet[0] EndFunc ;==>_htons ;network byte order to host byte order (double) Func _ntohd($value) Local $aRet = DllCall($hDLL_WS2_32, "double", "ntohd", "UINT64", $value) Return $aRet[0] EndFunc ;==>_ntohd ;network byte order to host byte order (float) Func _ntohf($value) Local $aRet = DllCall($hDLL_WS2_32, "float", "ntohf", "UINT", $value) Return $aRet[0] EndFunc ;==>_ntohf ;network byte order to host byte order (long) Func _ntohl($iNetLong) Local $aRet = DllCall($hDLL_WS2_32, "ULONG", "ntohl", "ULONG", $iNetLong) Return $aRet[0] EndFunc ;==>_ntohl ;network byte order to host byte order (long long) Func _ntohll($value) Local $aRet = DllCall($hDLL_WS2_32, "UINT64", "ntohll", "UINT64", $value) Return $aRet[0] EndFunc ;==>_ntohll ;network byte order to host byte order (short) Func _ntohs($iNetShort) Local $aRet = DllCall($hDLL_WS2_32, "USHORT", "ntohs", "USHORT", $iNetShort) Return $aRet[0] EndFunc ;==>_ntohs Func _WSAGetLastError() Local $aRet = DllCall($hDLL_WS2_32, "int", "WSAGetLastError") Return $aRet[0] EndFunc ;==>_WSAGetLastError Func _GetLocalPort($iSocket) ;funkey Local $tagIN_ADDR = "ulong S_addr;" Local $tagSockAddr_In = "short sin_family;ushort sin_port;ptr sin_addr;char sin_zero[8];" Local $tIn_Addr = DllStructCreate($tagIN_ADDR) Local $tName = DllStructCreate($tagSockAddr_In) DllStructSetData($tName, "sin_addr", DllStructGetPtr($tIn_Addr)) Local $aRes = DllCall($hDLL_WS2_32, "int", "getsockname", "uint", $iSocket, "struct*", $tName, "int*", 512) Local $aRes2 = DllCall($hDLL_WS2_32, "ushort", "ntohs", "ushort", DllStructGetData($tName, 2)) Return $aRes2[0] EndFunc ;==>_GetLocalPort Func _getsockname($iSocket) Local $tIn_Addr = DllStructCreate($tagIN_ADDR) Local $tName = DllStructCreate($tagSockAddr_In) DllStructSetData($tName, "sin_addr", DllStructGetPtr($tIn_Addr)) Local $aRes[2] Local $aRet = DllCall($hDLL_WS2_32, "int", "getsockname", "uint", $iSocket, "struct*", $tName, "int*", 512) If Not @error And $aRet[0] = 0 Then $aRes[0] = _inet_ntoa(DllStructGetData($tName, "sin_addr")) ;IP address $aRes[1] = _ntohs(DllStructGetData($tName, "sin_port")) ;IP port ;~ $aRes[2] = DllStructGetData($tName, "sin_family") ; always AF_INET !? Return $aRes EndIf Return SetError(1, 0, 0) EndFunc ;==>_getsockname ;More than TCPNameToIP(), returns an array of IP addresses Func _getaddrinfo($sNodeName) Local $pResult, $tAddrInfo, $sIP Local $aRet = DllCall($hDLL_WS2_32, "int", "getaddrinfo", "str", $sNodeName, "ptr", 0, "ptr", 0, "ptr*", 0) $pResult = $aRet[4] Do $tAddrInfo = DllStructCreate($tagAddrInfo, $pResult) Local $tName = DllStructCreate($tagSockAddr_In, DllStructGetData($tAddrInfo, "ai_addr")) $sIP &= _inet_ntoa(DllStructGetData($tName, "sin_addr")) & ";" $pResult = DllStructGetData($tAddrInfo, "ai_next") Until $pResult = 0 _freeaddrinfo($aRet[4]) Return StringSplit(StringTrimRight($sIP, 1), ";", 2) EndFunc ;==>_getaddrinfo Func _freeaddrinfo($pAddrInfo) DllCall($hDLL_WS2_32, "none", "freeaddrinfo", "ptr", $pAddrInfo) EndFunc ;==>_freeaddrinfo Func _ioctlsocket($iSocket, $iCmd, $iArg) Local $aRet = DllCall($hDLL_WS2_32, "int", "ioctlsocket", "uint", $iSocket, "long", $iCmd, "ULONG*", $iArg) Return $aRet[0] EndFunc ;==>_ioctlsocket Func _TCPConnectEx($sIP, $iRemPort, $iRcvTimeOut = 0, $iSendTimeOut = 0, $iLocPort = -1) Local $tTimeVal, $iSockError, $iBind, $iConnect, $aIP[1] Local $iSock = _socket($AF_INET, $SOCK_STREAM, $IPPROTO_TCP) If $iRcvTimeOut > 0 Then $tTimeVal = DllStructCreate("DWORD timeout") DllStructSetData($tTimeVal, "timeout", $iRcvTimeOut) $iSockError = _setsockopt($iSock, $SOL_SOCKET, $SO_RCVTIMEO, $tTimeVal) If $iSockError Then _closesocket($iSock) Return SetError(1, _WSAGetLastError(), 0) EndIf EndIf If $iSendTimeOut > 0 Then $tTimeVal = DllStructCreate("DWORD timeout") DllStructSetData($tTimeVal, "timeout", $iSendTimeOut) $iSockError = _setsockopt($iSock, $SOL_SOCKET, $SO_SNDTIMEO, $tTimeVal) If $iSockError Then _closesocket($iSock) Return SetError(2, _WSAGetLastError(), 0) EndIf EndIf If $iLocPort >= 0 Then $iBind = _bind($iSock, @IPAddress1, $iLocPort) If $iBind Then _closesocket($iSock) Return SetError(3, _WSAGetLastError(), 0) EndIf EndIf If _IsValidIP($sIP) Then $aIP[0] = $sIP Else $aIP = _getaddrinfo($sIP) EndIf $iConnect = _connect($iSock, $aIP[0], $iRemPort) If $iConnect Then _closesocket($iSock) Return SetError(4, _WSAGetLastError(), 0) EndIf Return $iSock EndFunc ;==>_TCPConnectEx Func _IsValidIP($sIP) Local $aIP = StringSplit($sIP, ".") If $aIP[0] <> 4 Then Return SetError(1, 0, 0) For $x = 1 To $aIP[0] If $aIP[$x] < 0 Or $aIP[$x] > 255 Then Return SetError(2, 0, 0) Next Return 1 EndFunc ;==>_IsValidIP TCPConnectTimeout & socket UDF.rar1 point
-
A UDF for manipulating Windows Image Files (.wim) without ImageX.exe This UDF allows you to use the Windows Imaging API directly (wimgapi.dll) so you don't have to use a command line program such as ImageX. Benefits are wimgapi.dll is shipped with windows 7 so users don't have to download the 1gb+ AIK to manage wim files. The UDF also allows you to utilize callback functions so you can show detailed progress info to your users. wimfltr.sys/wimmount.sys required for mount/unmount only. working with both 32 and 64 bit builds. its pretty well documented but you should still read the MS Imaging API documentation and be familiar how wimgapi.dll works to get the most out of this UDF. functions marked with an (*) are only available with newer versions of wimgapi.dll Functions Included: _WIM_ApplyImage _WIM_CaptureImage _WIM_CloseHandle _WIM_CreateFile _WIM_DeleteImage _WIM_DeleteImageMounts * _WIM_ExportImage _WIM_ExtractImagePath * _WIM_GetImageAttributes _WIM_GetImageCount _WIM_GetImageInformation _WIM_LoadImage _WIM_MountImage _WIM_RegisterLogFile * _WIM_RegisterMessageCallback _WIM_RemountImage * _WIM_SetBootImage _WIM_SetImageInformation _WIM_SetReferenceFile _WIM_SetTemporaryPath _WIM_Shutdown _WIM_Startup _WIM_UnMountImage _WIM_UnRegisterLogFile * _WIM_UnregisterMessageCallback have fun! Homes32 Sample Usage #include <Wimgapi.au3> ; functions for WIM Global $swimfile, $hWim, $hImage, $filepath, $Percent, $rTime, $pCallBack Global $gsWimDLL = @SystemDir & "wimgapi.dll" ; path to wimgapi.dll $ProgramName = "WIM Demo" ; Fire up wimgapi.dll $aResult = _WIM_Startup() If @error = 2 Then MsgBox(16, $ProgramName, "Error loading library: " & "(" & $aResult & "," & @error & ", " & $gsWimDLL & ")" & @CRLF & @CRLF & "The file could not be found.") Exit (2) ElseIf @error = 1 Then MsgBox(16, $ProgramName, "Error loading library: " & "(" & $aResult & "," & @error & ", " & $gsWimDLL & ")" & @CRLF & @CRLF & "Wrong DLL. Make sure you are using the right arch (x86/x64)") Exit (254) EndIf ; your code here ; ex. ; Capture("C:toolz", "c:test.wim", "My Test IMG", "Test Desc", 1) ; Cleanup() ; Apply ;----------------------------- Func Apply($sWimFile, $iImageIndex, $sTarget) ProgressOn('Apply', '', '', -1, -1, 19) ; Register callbacks so we get progress information for the capture process. ; WARNING: This does not work very well with Apply do to the way autoit handles callbacks. ; See the following post for more info: ; http://www.autoitscript.com/forum/topic/127075-wimgapi-udf/page__view__findpost__p__917049 $pCallBack = DllCallbackRegister('CallBack', 'int', 'dword;WPARAM;LPARAM;dword') _WIM_RegisterMessageCallback(0, DllCallbackGetPtr($pCallBack), 0) ; load .wim file with read access $hWim = _WIM_CreateFile($sWimFile, $WIM_GENERIC_READ, $WIM_OPEN_EXISTING, 0, 0, 0) If $hWim = 0 Then MsgBox(48, $ProgramName, "Error: Failed to load image. (" & $hWim & "," & @error & "," & @extended & ")") Cleanup() Exit (252) EndIf ; set our temp path $aResult = _WIM_SetTemporaryPath($hWim, $sTarget) ; load the image index $hImage = _WIM_LoadImage($hWim, $iImageIndex) ; Apply the image $aResult = _WIM_ApplyImage($hImage, $sTarget) If $aResult = 0 Then MsgBox(48, $ProgramName, "Error: Failed to apply image. Make sure your path exists! (" & $aResult & "," & @error & "," & @extended & ")") Cleanup() ProgressOff() EndFunc ; Mount ;----------------------------- Func Mount($sMountPath, $sWimFile, $iImageIndex, $RW) $aResult = _WIM_MountImage($sMountPath, $sWimFile, $iImageIndex, $RW) If $aResult = 0 Then MsgBox(48, $ProgramName, "Mount Error: (" & $aResult & "," & @error & "," & @extended & ")") Cleanup() Exit (253) ; mount error EndIf Cleanup() EndFunc ; UnMount ;----------------------------- Func UnMount($sMountPath, $iCommit) $aResult = _WIM_UnMountImage($sMountPath, 0, 0, $iCommit) If $aResult = 0 Then MsgBox(48, $ProgramName, "UnMount Error: (" & $aResult & "," & @error & "," & @extended & ")") Cleanup() Exit (254) ; Unmount error EndIf Cleanup() EndFunc ; GetInfo ;----------------------------- Func GetInfo($sWimFile) ; load .wim file with read access $hWim = _WIM_CreateFile($sWimFile, $WIM_GENERIC_READ, $WIM_OPEN_EXISTING, 0, 0, 0) If $hWim = 0 Then MsgBox(48, $ProgramName, "Error: Failed to load image. (" & $hWim & "," & @error & "," & @extended & ")") Cleanup() Exit (252) EndIf ; set our temp path $aResult = _WIM_SetTemporaryPath($hWim, @TempDir) ; read wim attributes $aWimAttribs = _WIM_GetImageAttributes($hWim) ; read info from the image $aXML = _WIM_GetImageInformation($hWim) ; Cleanup any open handles Cleanup() ; make our output pretty Switch $aWimAttribs[4] Case $WIM_COMPRESS_NONE $aWimAttribs[4] = "NONE" Case $WIM_COMPRESS_XPRESS $aWimAttribs[4] = "XPRESS" Case $WIM_COMPRESS_LZX $aWimAttribs[4] = "LZX" EndSwitch Local $outFile = @ScriptDir & "wiminfo.txt" If FileExists($outFile) Then FileDelete($outFile) FileWrite($outFile, @CRLF & $ProgramName & @CRLF & @CRLF & @CRLF & @CRLF & _ "WIM Information:" & @CRLF & _ "----------------" & @CRLF & _ "Wim Path: : " & $aWimAttribs[1] & @CRLF & _ "GUID : " & $aWimAttribs[2] & @CRLF & _ "Image Count: " & $aWimAttribs[3] & @CRLF & _ "Compression: " & $aWimAttribs[4] & @CRLF & _ "Part Number: " & $aWimAttribs[5] & "/" & $aWimAttribs[6] & @CRLF & _ "Boot Index : " & $aWimAttribs[7] & @CRLF & _ "Attributes : " & $aWimAttribs[8] & @CRLF & @CRLF & @CRLF & _ "Available Image Choices:" & @CRLF & _ "------------------------" & @CRLF & _ $aXML[1]) EndFunc ;==>GetInfo ; Extract ;----------------------------- Func Extract($sWimFile, $iImageIndex, $sFilePath, $sExtractTo) ; load .wim file with read access $hWim = _WIM_CreateFile($sWimFile, $WIM_GENERIC_READ, $WIM_OPEN_EXISTING, 0, 0, 0) If $hWim = 0 Then MsgBox(48, $ProgramName, "Error: Failed to load image. (" & $hWim & "," & @error & "," & @extended & ")") Cleanup() Exit (252) EndIf ; set our temp path $aResult = _WIM_SetTemporaryPath($hWim, @TempDir) ; load the image index $hImage = _WIM_LoadImage($hWim, $iImageIndex) ; extract the file $aResult = _WIM_ExtractImagePath($hImage, $sFilePath, $sExtractTo) If $aResult = 0 Then MsgBox(48, $ProgramName, "Error: Failed to extract from image. Make sure your path exists! (" & $aResult & "," & @error & "," & @extended & ")") Cleanup() EndFunc ; Capture ;----------------------------- Func Capture($Path, $sWimFile, $sImageName, $sImageDesc, $Compress) ProgressOn('Capture', '', '', -1, -1, 19) ; Register callbacks so we get progress information for the capture process. $pCallBack = DllCallbackRegister('CallBack', 'int', 'dword;WPARAM;LPARAM;dword') _WIM_RegisterMessageCallback(0, DllCallbackGetPtr($pCallBack), 0) ; first we need to create a blank .wim file with write access and our compression options $hWim = _WIM_CreateFile($sWimFile, $WIM_GENERIC_WRITE, $WIM_CREATE_ALWAYS, 0, $Compress, 0) If $hWim = 0 Then MsgBox(48, $ProgramName, "Error: Failed to create image. (" & $hWim & "," & @error & "," & @extended & ")") Cleanup() Exit (252) ; image create failed EndIf ; set our temp path $aResult = _WIM_SetTemporaryPath($hWim, @TempDir) ; start the image capture!!! $hImage = _WIM_CaptureImage($hWim, $Path, 0) If $hImage = 0 Then MsgBox(48, $ProgramName, "Error: Failed to capture image. (" & $hImage & "," & @error & "," & @extended & ")") Cleanup() Exit (251) ; image capture failed EndIf ; add our name and description to the XML data - ChrW(65279) is the BOM $sXML = ChrW(65279) & "<IMAGE><NAME>" & $sImageName & "</NAME><DESCRIPTION>" & $sImageDesc & "</DESCRIPTION></IMAGE>" _WIM_SetImageInformation($hImage, $sXML) _WIM_SetBootImage($hWim, 1) Cleanup() ; free resources ProgressOff() EndFunc ;==>Capture ; ================================================================================================================== ; Function: CallBack ; Description: Very Basic Sample Callback function for capture progress ; Usage: CallBack($msgId, $param1, $param2, $b) ; Author: Homes32 ; ================================================================================================================== Func CallBack($msgId, $param1, $param2, $unused) Switch $msgId Case $WIM_MSG_PROGRESS ; get progress % and time remaining $Percent = $param1 If $param2 = 0 Then $rTime = "" Else $rTime = StringFormat('Remaining: %i sec.', $param2 / 1000) EndIf Case $WIM_MSG_PROCESS ; get the file name being processed $Struct = DllStructCreate("ushort[1024]", $param1) $sFilePath = "" $i = 1 While 1 $Tmp = DllStructGetData($Struct, 1, $i) If $Tmp = 0 Then ExitLoop $sFilePath &= ChrW($Tmp) $i += 1 WEnd EndSwitch ProgressSet($Percent, StringFormat('%3i%% completed. %snn %s', $Percent, $rTime, $filePath), 'Capture ' & $sWimFile) Return $WIM_MSG_SUCCESS EndFunc ;==>CallBack Func Cleanup() ; Cleanup any open handles If $hImage Then _WIM_CloseHandle($hImage) If $hWim Then _WIM_CloseHandle($hWim) If $pCallBack Then ; Cleanup our callbacks $aResult = _WIM_UnregisterMessageCallback(0, DllCallbackGetPtr($pCallBack)) DllCallbackFree($pCallBack) EndIf _WIM_Shutdown() ; shutdown wimgapi.dll EndFunc ;==>Cleanup History v1 3-30-2011 * 1st release v2 4-4-2011 * cleaned up the documention * added the following functions _WIM_DeleteImage _WIM_DeleteImageMounts _WIM_ExportImage _WIM_RemountImage _WIM_SetReferenceFile v3 9-19-2011 * Fixed Access Violation crash in _WIM_GetImageInformation Previous Downloads: 312 WimgapiUDF.zip1 point
-
The picture shows Rubik's Cube in the middle of a rotation, wherein the layer is rotated 90 degrees. New version for AutoIt 3.3.10 The scripts were flawed. Fixed in this update. 08-01-2013: First post In the Cubes menu there are six cubes from 2*2*2 to 7*7*7: Pocket Cube, Rubik's Cube, Rubik's Revenge, Professor's Cube, V-Cube 6 and V-Cube 7. See http://en.wikipedia.org/wiki/Rubik's_Cube. The Scramble menu scrambles the cube. In the input field in the statusbar you can set the number of scramble steps. The Solve menu automatically solves the cube. In this version it just plays back the undo log. The Build menu shows how the cubes are created. It also shows how the rotation of a layer is simulated. The Scramble, Solve and Build menus puts the program into a Scramble, Solve and Build mode. To leave the Scramble and Solve modes click the menu once more. To leave the Build mode uncheck the menu. The program mode or state appears in the statusbar. See the Help menu for more information about the menus. Rotating a layer in the cube Click an edge of the layer with the left mouse button and hold the button downMove the mouse in the direction you want to rotate the layerRelease the left mouse buttonThe rotating layer in the picture has probably been clicked somewhere on the blue edge. You can't rotate a layer in Scramble, Solve and Build modes. The mouse buttons can be switched in the Options. Rotating the entire cube Click in the window with the right mouse button and hold the button downMove the mouse in the direction you want the cube to rotateRelease the right mouse buttonThe description of the mouse rotations can be found in the Help menu. Using the keyboard Use the arrow keys or <A,a>, <W,w>, <S,s>, <Z,z> to rotate the cube. Use <Home> or <H,h> to place the cube in the start position. Use <Page Up> or <I,i> and <Page Down> or <O,o> to zoom in and out. Use Num 1-6 or 1-6 to show the 6 sides of the cube. The program Inspiration for the program is from this site: http://rubiksim.sourceforge.net/. The graphics is generated with old style OpenGL 1.1. Some OpenGL globals and functions are copied from this thread http://www.autoitscript.com/forum/index.php?showtopic=83581 by trancexx. Especially globals and functions for creating an OpenGL window and a rendering context. Zipfile The zipfile contains a number of files: RubiksCube.au3 - GUI and main loop, run this fileMenuFncs.au3 - implements the menu systemMenuWins.au3 - creates menu system windowsKeyboard.au3 - code for shortcut keysOGLconsts.au3 - OpenGL constantsOGLfuncs.au3 - OpenGL functionsCubes.au3 - creates the cubesTurnLayer.au3 - rotate a layerRotateCube.au3 - rotate the cubeScramble.au3 - scramble functionSolveCube.au3 - solve functionsBuild.au3 - build functionsUtilities.au3 - calculations(The files are edited with Notepad++ with a tabwidth of 2. This doesn't match the default settings in Scite.) 21-01-2013: Update #1 Fixed some errors in the Build menu. Added a log to see the colors of all sides at one time. See picture in post #5. RubiksCube3.3.10.7z Testet on XP 32 bit and Win 7 32/64 bit. Previous versions for AutoIt 3.3.81 point
-
Process CPU Usage Trackers As yet another alternative to the Performance Counters UDF, I've created this UDF to allow easy tracking of one or more processes's CPU usage. While this has obviously been done before, I haven't seen it done the way I've created it. Basically, just as the Performance Counters had Process Counter objects, so this too has Process Usage trackers. They are relatively simple to use, and require very little interaction other than invoking the functions. To create a new tracker object, call one of these: _ProcessUsageTracker_Create() ; Single process tracker _ProcessesUsageTracker_Create() ; Multiple processes tracker The multiple-process tracker requires addition of processes, which can be done one of 2 ways: _ProcessesUsageTracker_Add() ; add a single process _ProcessesUsageTracker_AddMultiple() ; multiple processes in a ProcessList-style array After the usage tracker object has been created, stats can be collected via one of two calls: _ProcessUsageTracker_GetUsage() ; single process - returns a percentage _ProcessesUsageTracker_GetUsage() ; multiple Processes - returns an array of %'s Basically the main loop of the program can be filled with 'GetUsage' calls without juggling anything around. If a process dies out, an @error code will be returned in the single-process version. The multiple-process tracker version however lets you retain dead processes in the list although their process handles will be closed. These can be alternatively cleared up on each call to 'GetUsage' (setting $bRemoveDead to True), or you can opt to clean them up with the following call: _ProcessesUsageTracker_RemoveDead() ; Removes any dead processes from the tracker object Finally, to destroy the trackers and close handles, just call the appropriate function: _ProcessUsageTracker_Destroy() _ProcessesUsageTracker_Destroy() That's about it. More info is in the headers. Here's an example of a single process cpu usage tracker: ; ======================================================================================================== ; <Process_CPUUsageExample.au3> ; ; Example usage of <Process_CPUUsage.au3> ; ; Author: Ascend4nt ; ======================================================================================================== #include "Process_CPUUsage.au3" ; -------------------- HOTKEY FUNCTION & VARIABLE -------------------- Global $bHotKeyPressed=False Func _EscPressed() $bHotKeyPressed=True EndFunc ; -------------------- MAIN PROGRAM CODE -------------------- HotKeySet("{Esc}", "_EscPressed") Local $hSplash, $sSplashText Local $sProcess, $aProcUsage, $fUsage ; Regular Process: ;~ $sProcess = "firefox.exe" ;~ $sProcess = "sp2004.exe" ; Stress Prime 2004 ; Protected Process (opens a different way): ;~ $sProcess = "audiodg.exe" ; Processes Requiring elevated privilege (will fail even with limited access rights): ;~ $sProcess = "CTAudSvc.exe" $sProcess = InputBox("Enter Process Name", "Process Name:", "", "", 320, 140) If @error Or $sProcess = "" Then Exit $aProcUsage = _ProcessUsageTracker_Create($sProcess) If @error Then Exit ConsoleWrite("Error calling _ProcessUsageTracker_Create(): " & @error & ", @extended = " & @extended & @CRLF) Sleep(250) $hSplash=SplashTextOn("Process CPU Usage Information", "", 360, 20 + 60, Default, Default, 16, Default, 12) ; Start loop Do $sSplashText="" $fUsage = _ProcessUsageTracker_GetUsage($aProcUsage) If @error Then ConsoleWrite("Error from _ProcessUsageTracker_GetUsage(): " & @error & ", @extended = " &@extended & @CRLF) ExitLoop EndIf $sSplashText &= "'"&$sProcess&"' CPU usage: " & $fUsage & " %" & @CRLF $sSplashText &= @CRLF & "[Esc] exits" ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText) Sleep(500) Until $bHotKeyPressed _ProcessUsageTracker_Destroy($aProcUsage) _ Multiple processes example, which is best used with something like 'chrome' which spawns a number of processes with the same name: ; ======================================================================================================== ; <Processes_CPUUsageExample.au3> ; ; Example usage of <Processes_CPUUsage.au3> ; ; Author: Ascend4nt ; ======================================================================================================== #include "Processes_CPUUsage.au3" ; -------------------- HOTKEY FUNCTION & VARIABLE -------------------- Global $bHotKeyPressed=False Func _EscPressed() $bHotKeyPressed=True EndFunc ; -------------------- MAIN PROGRAM CODE -------------------- HotKeySet("{Esc}", "_EscPressed") Local $hSplash, $sSplashText Local $sProcess, $aProcList, $aProcUsage, $aPercents, $nPercents ; Regular Process: ;~ $sProcess = "firefox.exe" ;~ $sProcess = "sp2004.exe" ; Stress Prime 2004 ; Protected Process (opens a different way): ;~ $sProcess = "audiodg.exe" ; Processes Requiring elevated privilege (will fail even with limited access rights): ;~ $sProcess = "CTAudSvc.exe" $sProcess = InputBox("Enter Process Name", "Process Name:", "", "", 320, 140) If @error Or $sProcess = "" Then Exit $aProcUsage = _ProcessesUsageTracker_Create() _ProcessesUsageTracker_Add($aProcUsage, "sp2004.exe") _ProcessesUsageTracker_Add($aProcUsage, "CPUStabTest.exe") $aProcList = ProcessList("chrome.exe") _ProcessesUsageTracker_AddMultiple($aProcUsage, $aProcList) _ProcessesUsageTracker_Add($aProcUsage, $sProcess) _ProcessesUsageTracker_Add($aProcUsage, "audiodg.exe") Sleep(250) $hSplash=SplashTextOn("Process CPU Usage Information", "", 380, 24 + 15*2 + $aProcUsage[0][0]*15, Default, Default, 16+4, "Lucida Console", 11) ; Start loop Do ; DEBUG: Interrupt to allow multiple process termination ;MsgBox(0, "Next usage", "Next usage time..") $sSplashText="" $aPercents = _ProcessesUsageTracker_GetUsage($aProcUsage, True) ; True = Remove dead $nPercents = @extended If @error Then ConsoleWrite("Error from _ProcessesUsageTracker_GetUsage(): " & @error & ", @extended = " &@extended & @CRLF) ExitLoop EndIf For $i = 0 To $nPercents - 1 $sSplashText &= "'"&$aProcUsage[$i+1][0]&"' [PID #"&$aProcUsage[$i+1][1]&"] CPU usage: " & $aPercents[$i] & " %" & @CRLF Next $sSplashText &= @CRLF & "[Esc] exits" ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText) Sleep(500) Until $bHotKeyPressed _ProcessesUsageTracker_Destroy($aProcUsage) ProcessCPUUsage.zip1 point
-
Code is designed only for horizontal sliders. I've to modify the code to create also vertical sliders which will take some time. Br, UEZ1 point
-
hi guys, check out this little udf. it's not much, but at least it's not just sapi. ;speech udf ;uses either sapi or google speech. ;function ;name: _SpeechGet ;description: generates speech and outputs it to the speakers. ;usage: _SpeechGet($Text, $Engine) ;$Text = the text to speak. ;$Engine = the speech engine to use, 0 = microsoft speech API 5x, 1 = Google translation API. 0 is default. ;returns 0 if no errors, 1 for errors. Func _SpeechGet($Text, $Mode = "0") if $Text = "" then Return 1 if $Mode > 1 or $Mode < 0 then Return 1 if $Mode = "0" then ;create speech object Local $Voice = ObjCreate("Sapi.SpVoice") if not IsObj($Voice) then Return 1 EndIf if $Mode = "0" then ;speak the text $Voice.Speak($Text) Return 0 else ;use the google translation api to get the speech InetGet("http://translate.google.com/translate_tts?q=" & $Text, @TempDir & "\tempspeech.mp3", 1) ;play the downloaded speech SoundPlay(@TempDir & "\tempspeech.mp3", 1) ;delete the temporary file FileDelete(@TempDir & "\tempspeech.mp3") Return 0 EndIf EndFunc let me know if you enjoy it, or if you know of any other web based speech services i could add support for.1 point
-
AutoIt Snippets
somdcomputerguy reacted to FireFox for a topic
Are you trying to reach Proxima Centauri ?1 point -
AutoMathEdit This is a very simple language written in AutoIt. AutoMathEdit only handles numeric operations and lacks the fexibility and functionality of other programming languages. it's still a language nonetheless! See this post: There are currently no keywords or loops, but the intended purpose of AutoMathEdit is to replace the calculator for quick tasks. The standard windows calculator does not keep tabs on every number you type. This is one advantage of using AutoMathEdit instead of using a standard calculator. This is the first scripting language I have ever written and it was certainly an education. I know I'm only scratching the surface with this, but everyone has to start soimewhere. I have gained much respect for the dev team after this endeavour. Dealing with so many complicated commands must be a nightmare. AutoMathEdit is meant to be used exclusivey within an Edit control. The function Echo behaves like the AutoIt function ConsoleWrite. This is an alpha release and there are still several bugs need ironing out. AutoMathEdit.au3 #include-once #include <Math.au3> #include <Array.au3> ; #INDEX# ======================================================================================================================= ; Title .........: AutoMathEdit Version 0.0.0.6 (Alpha) ; AutoIt Version : 3.3.8.1 ; Language ......: English ; Description ...: Simple (maths only) scripting language based on AutoIt ; Notes .........: AutoMathEdit makes use of AutoIt syntax and standard maths functions. ; The library is not yet complete and this release is for evaluation purposes. ;+ ; Supported AutoIt functions:- Abs ACos ASin ATan BitAND BitNOT BitOR BitRotate ; BitShift BitXOR Cos Ceiling Dec Exp Floor Hex Log Mod Random Round Sin Sqrt ;+ ; Supported UDF functions:- _ATan2 _Combinations _Degree Echo _Factorial _Max _Min ; _Radian _Permutations ;+ ; Supported variable types:- integers floats binary ;+ ; Supported operators:- + - * / ^ = += -= *= /= ;+ ; Constants:- ; $MATH_E .... (Napiers Constant) ; $MATH_PHI .. (Golden Ratio) ; $MATH_PI ... (Pi) ; $MATH_PSI .. (Reciprocal Fibonacci Constant) ;+ ; Supported syntax:- ; 1. End of line comments (semicolon) ; 2. Line continuation (underscore) ;+ ; General Comments: ; UDF functions are included automatically. ; All variables are declared automatically. ; The use of $ (dollar sign) for variable names is optional. ; The function Echo returns the value of an expression. ; Echo(expression) ;= value ;+ ; Thanks to the following devs and members who's examples have been a great inspiration: ; Jon, Manadar, Mat, Valik, trancexx, UEZ (list is not complete) ;+ ; Author(s) .....: Nick Wilkinson (czardas) ; =============================================================================================================================== ; #CURRENT# ===================================================================================================================== ;_Combinations ;_Execute ;_Factorial ;_Permutations ; =============================================================================================================================== ; #INTERNAL_USE_ONLY#============================================================================================================ ;__AssignSplit ;__ErrorMsg ;__GetBreakPoint ;__GetNewStr ;__GetSubArr ;__IsConst ;__IsFunc ;__IsReserved ;__Return ;__StripOutStrings ; =============================================================================================================================== ; #FUNCTION# ==================================================================================================================== ; Name...........: _Execute ; Description ...: Runs AutoMathEdit ; Syntax.........: _Execute($_sScript_) ; Parameters ....: $_sScript_ .... The string to parse. ; Return values .: Success ....... Parses AutoMathEdit and returns the new code string. ; Failure ....... Parses AutoMathEdit up to the fail point and sets @error ; |@error = 1 ... Illegal characters ; |@error = 2 ... Invalid Syntax ; |@error = 3 ... Function not recognised ; |@error = 4 ... Unexpected Termination ; |@error = 5 ... Unterminated String ; |@error = 6 ... Failed to reassign mathematical constant ; |@error = 7 ... Missing Parentheses ; |@error = 8 ... Unassigned Variable ; Author ........: czardas ; Modified.......: ; Remarks .......: _Execute also handles calls to the Echo() function which evaluates an expression. ; The value returned by the function Echo appears as a comment in the returned code. ; Related .......: None ; Link ..........: ; Example .......: Yes ; =============================================================================================================================== Func _Execute($_sScript_) If Not StringLen($_sScript_) Then Return SetError(4, 0, $_sScript_) Local Const $MATH_E = 2.71828182845904523536028747135266249 ; Napiers Constant Local Const $MATH_PHI = 1.61803398874989484820458683436563811772 ; Golden Ratio Local Const $MATH_PI = 3.14159265358979323846264338328 ; Pi Local Const $MATH_PSI = 3.359885666243177553172011302918927179688905133731 ; Reciprocal Fibonacci constant Local $_aRawData_ = StringSplit(StringStripCR($_sScript_), @LF) $_sScript_ = StringRegExpReplace($_sScript_, "(;.*)", "") ; Remove comments Local $_subStr_ ; Substitute string for $ and to avoid conflicts with reserved variables or constants __GetNewStr($_sScript_, $_subStr_) Local $_aTemp_, $_error_, $_sFail_ = "" ; To store the string which could not be parsed $_aTemp_ = __GetSubArr($_sScript_, $_subStr_, $_sFail_) ; Returns an array of substitute patterns $_error_ = @error Local $_aScriptArr_, $foo, $_sRawCode_ = $_sScript_ ; Keep original code intact $_sScript_ = StringReplace($_sScript_, "$MATH", ";") ; To avoid corrupting constant variable names $_sScript_ = StringReplace($_sScript_, "$", $_subStr_) ; To avoid conflicts with duplicate variable names $_sScript_ = StringReplace($_sScript_, ";", "$MATH") ; Replace the correct math constant names If $_error_ = 0 Then For $foo = 1 To $_aTemp_[0][0] $_sScript_ = StringRegExpReplace($_sScript_, "(?i)(b" & $_aTemp_[$foo][0] & "b)", $_aTemp_[$foo][1]) Next Else If StringLen($_sFail_) Then $_aScriptArr_ = StringSplit(StringStripCR($_sScript_), @LF) ; Split to lines of raw code For $foo = 0 To UBound($_aScriptArr_) -1 If StringInStr($_aScriptArr_[$foo], $_sFail_) Then $_sFail_ = "Line " & $foo & @LF & $_sFail_ ExitLoop EndIf Next MsgBox(16, "Error", __ErrorMsg($_error_) & @LF & $_sFail_) Return SetError($_error_, 0, __Return($_aRawData_)) ; Unable to parse - Errors vary EndIf EndIf Local $bar ; Variable integer $_aScriptArr_ = StringSplit(StringStripCR($_sScript_), @LF) ; Split to lines of raw code For $foo = 1 To $_aScriptArr_[0] $bar = $foo While StringRegExp($_aScriptArr_[$foo], "(s_s*z)") ; Check for line continuation underscore NOT CHECKED If $bar < $_aScriptArr_[0] Then If StringLen($_aScriptArr_[$bar +1]) Then $_aScriptArr_[$foo] = StringRegExpReplace($_aScriptArr_[$foo], "(s_s*z)", " " & $_aScriptArr_[$bar +1]) $_aScriptArr_[$bar +1] = "" $bar += 1 Else MsgBox(16, "Error", "Line " & $bar & @LF & __ErrorMsg(5) & @LF & $_aRawData_[$bar]) Return SetError(5, 0, __Return($_aRawData_)) ; Unterminated String EndIf ElseIf StringRegExp($_aScriptArr_[$foo], "(s_s*z)") Then MsgBox(16, "Error", "Line " & $_aScriptArr_[0] & @LF & __ErrorMsg(5)) Return SetError(5, 0, __Return($_aRawData_)) ; Unterminated String EndIf WEnd $foo = $bar Next For $foo = 1 To $_aScriptArr_[0] ; Parse each line sequence $_aScriptArr_[$foo] = StringStripWS($_aScriptArr_[$foo], 3) If Not StringLen($_aScriptArr_[$foo]) Then ContinueLoop If StringInStr($_aScriptArr_[$foo], "=") Then $_aAssign_ = __AssignSplit($_aScriptArr_[$foo]) $_error_ = @error If $_error_ = 0 Then If StringLeft($_aAssign_[1], 1) = "$" Then $_aAssign_[1] = StringTrimLeft($_aAssign_[1], 1) Else MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo]) Return SetError(2, 0, __Return($_aRawData_)) EndIf If __IsConst($_aAssign_[1]) Then MsgBox(16, "Error", __ErrorMsg(6) & @LF & "Line " & $foo & @LF & "$" & $_aAssign_[1] & " =") Return SetError(6, 0, __Return($_aRawData_)) EndIf $_aAssign_[2] = Execute($_aAssign_[2]) $_error_ = @error If StringLen($_aAssign_[2]) = 0 Or ($_aAssign_[2] <> 0 And $_error_ <> 0 And Not IsNumber(Number($_aAssign_[2])) Or $_aAssign_[2] = False) Then MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aAssign_[1] & " =") Return SetError(2, 0, __Return($_aRawData_)) EndIf If $_aAssign_[0] = 2 Then Assign($_aAssign_[1], $_aAssign_[2]) ElseIf IsDeclared($_aAssign_[1]) Then $_nValue_ = Execute("$" & $_aAssign_[1]) Switch $_aAssign_[0] Case "+" Assign($_aAssign_[1], $_nValue_ + $_aAssign_[2]) Case "-" Assign($_aAssign_[1], $_nValue_ - $_aAssign_[2]) Case "*" Assign($_aAssign_[1], $_nValue_ * $_aAssign_[2]) Case "/" Assign($_aAssign_[1], $_nValue_ / $_aAssign_[2]) EndSwitch Else MsgBox(16, "Error", __ErrorMsg(8) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo]) Return SetError(8, 0, __Return($_aRawData_)) EndIf Else $bar = __GetBreakPoint($_sRawCode_, $foo, "=", 2) MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $bar & @LF & "=") Return SetError(2, 0, __Return($_aRawData_)) EndIf ; Echo is an internal command which writes the value of an expression. ElseIf StringLeft($_aScriptArr_[$foo], 4) = "Echo" Then $_aScriptArr_[$foo] = StringStripWS(StringTrimLeft($_aScriptArr_[$foo], 4), 3) If StringLeft($_aScriptArr_[$foo], 1) <> "(" Then MsgBox(16, "Error", __ErrorMsg(7) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo]) Return SetError(7, 0, __Return($_aRawData_)) ; Missing Parentheses EndIf $bar = __GetBreakPoint($_sRawCode_, $foo) If StringRight($_aScriptArr_[$foo], 1) <> ")" Then MsgBox(16, "Error", __ErrorMsg(7) & @LF & "Line " & $bar & @LF & $_aRawData_[$bar]) Return SetError(7, 0, __Return($_aRawData_)) ; Missing Parentheses EndIf $_aScriptArr_[$foo] = StringTrimLeft(StringTrimRight($_aScriptArr_[$foo], 1), 1) $_temp_ = Execute($_aScriptArr_[$foo]) $_error_ = @error If StringLen($_temp_) = 0 Or ($_temp_ <> 0 And $_error_ <> 0 And (Not IsNumber(Number($_temp_)) Or $_temp_ = False)) Then $_aTemp_ = StringRegExp($_aScriptArr_[$foo], "x24w+", 3) If Not @error Then For $bar = 0 To UBound($_aTemp_) -1 $_temp_ = StringTrimLeft($_aTemp_[$bar], 1) If Not IsDeclared($_temp_) Then $_subLen_ = StringLen($_subStr_) If StringLeft($_temp_, $_subLen_ +1) = "k" & $_subStr_ Then ; Or StringLeft($_temp_, $_subLen_ +1) = "n" & $_subStr_ ; may need to add this $_temp_ = StringTrimLeft($_temp_, $_subLen_ +1) ElseIf StringLeft($_temp_, $_subLen_) = $_subStr_ Then $_temp_ = StringTrimLeft($_temp_, $_subLen_) EndIf $bar = __GetBreakPoint($_sRawCode_, $foo, $_temp_) MsgBox(16, "Error", __ErrorMsg(8) & @LF & "Line " & $bar & @LF & $_aRawData_[$bar]) Return SetError(8, 0, __Return($_aRawData_)) EndIf Next EndIf MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo]) Return SetError(2, 0, __Return($_aRawData_)) EndIf $_aRawData_[$bar] = StringStripWS(StringRegExpReplace($_aRawData_[$bar], "(;.*)", ""), 2) & " ;= " & $_temp_ Else ; No assignments or Echo function - just an expression. What's that all about? $_temp_ = Execute($_aScriptArr_[$foo]) $_error_ = @error If StringLen($_temp_) = 0 Or ($_temp_ <> 0 And $_error_ <> 0 And Not IsNumber(Number($_temp_)) Or $_temp_ = False) Then MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo]) Return SetError(2, 0, __Return($_aRawData_)) EndIf EndIf Next Return __Return($_aRawData_) EndFunc ;==> _Execute ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __GetNewStr ; Description ...: Searches for a nonconflicting substitution string to replace the dollar sign. ; Syntax.........: __GetNewStr($sTestStr, ByRef $sNewString) ; Parameters ....: $sTestStr - AutoMathEdit ; : $sNewString - substitution string ; Return values .: [ByRef] $sNewString ; Author ........: czardas ; Modified.......: ; Remarks .......: Avoids conflicts by placing underscore in the second character position. ; Related .......: __GetSubArr ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __GetNewStr($sTestStr, ByRef $sNewString) ; Find a nonconflicting replacement for $ (dollar sign) Local $aChar[37] = ["_","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] ; Move outside function If StringLen($sNewString) < 2 Then $sNewString = $aChar[Random(0, 36, 1)] & "_" If Not StringInStr($sTestStr, $sNewString) Then Return For $i = 0 To 36 If Not StringInStr($sTestStr, $sNewString & $aChar[$i]) Then $sNewString &= $aChar[$i] Return EndIf Next $sNewString &= $aChar[Random(0, 36, 1)] __GetNewStr($sTestStr, $sNewString) EndFunc ;==> __GetNewStr ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __GetSubArr ; Description ...: Searches for a nonconflicting substitution string to replace the dollar sign. ; Syntax.........: __GetNewStr($sTestStr, ByRef $sNewString) ; Parameters ....: $sTestStr - AutoMathEdit ; : $subStr - substitution string ; : $sFail - Unexpected string which caused the function to fail ; ; Return values .: Success - An array of variable name substitutions ; Failure - Sets @error and returns [ByRef] $sFail ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: __GetNewStr ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __GetSubArr($sTestStr, $subStr, ByRef $sFail) __StripOutStrings($sTestStr) ; Remove quotes Local $aRegExp = StringRegExp($sTestStr, "[^,w=-^*+()x24s.x22'/]", 3) If Not @error Then ; Encountered an illegal character $sFail = $aRegExp[0] Return SetError(1) ; Illegal character EndIf $aRegExp = StringRegExp($sTestStr, "([w|x24]x24)|(x24[^w])", 3) If Not @error Then ; Dollar is in the wrong place $sFail = $aRegExp[0] Return SetError(2) ; Invalid Syntax EndIf $aRegExp = StringRegExp($sTestStr, "($?w+s*(?)", 3) ; Gets functions and variables If IsArray($aRegExp) Then For $i = 0 To UBound($aRegExp) -1 $aRegExp[$i] = StringLower(StringStripWS($aRegExp[$i], 3)) ; Account for case insensitivity Next $aRegExp = _ArrayUnique($aRegExp) ; Get rid of duplicated substitution strings Local $aSubArr[UBound($aRegExp) +1][2] $aSubArr[0][0] = 0 For $i = 0 To UBound($aRegExp) -1 $aRegExp[$i] = StringStripWS($aRegExp[$i], 2) Select Case StringRight($aRegExp[$i], 1) = "(" If StringLeft($aRegExp[$i], 1) = "$" Then ; Functions do not begin with $ $sFail = $aRegExp[$i] Return SetError(2) ; Invalid Syntax ElseIf Not (__IsFunc(StringRegExpReplace($aRegExp[$i], "s*(", "")) Or StringStripWS($aRegExp[$i], 8) = "_(") Then $sFail = $aRegExp[$i] Return SetError(3) ; Function not recognised EndIf Case StringLeft($aRegExp[$i], 1) = "$" If __IsReserved(StringTrimLeft($aRegExp[$i], 1)) Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = StringReplace($aRegExp[$i], "$", "$r" & $subStr) ElseIf Not __IsConst(StringTrimLeft($aRegExp[$i], 1)) Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = StringReplace($aRegExp[$i], "$", "$o" & $subStr) EndIf Case StringLeft($aRegExp[$i], 2) = "0x" If Not StringIsXDigit(StringTrimLeft($aRegExp[$i], 2)) Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = "$x" & $subStr & $aRegExp[$i] EndIf Case Not (StringIsInt($aRegExp[$i]) Or StringIsFloat($aRegExp[$i]) Or __IsFunc($aRegExp[$i])) If __IsReserved($aRegExp[$i]) Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = "$r" & $subStr & $aRegExp[$i] ElseIf __IsConst($aRegExp[$i]) Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = "$k" & $subStr & $aRegExp[$i] ElseIf StringIsDigit(StringLeft($aRegExp[$i], 1)) Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = "$d" & $subStr & $aRegExp[$i] ElseIf $aRegExp[$i] <> "_" Then $aSubArr[0][0] += 1 $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i] $aSubArr[$aSubArr[0][0] ][1] = "$w" & $subStr & $aRegExp[$i] EndIf EndSelect Next ReDim $aSubArr[$aSubArr[0][0] +1][2] For $i = 0 To $aSubArr[0][0] $aSubArr[$i][0] = StringReplace($aSubArr[$i][0], "$", $subStr) Next Return $aSubArr ; No errors have occured. Else Return SetError(4) ; Unexpected Termination EndIf EndFunc ;==> __GetSubArr ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __StripOutStrings ; Description ...: Removes all strings wrapped in quotes from the code. ; Syntax.........: __StripOutStrings(ByRef $sCodeStr) ; Parameters ....: $sCodeStr - The string to alter. ; Return values .: [ByRef] the string after removing all strings wrapped in quotes ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: None ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __StripOutStrings(ByRef $sCodeStr) Local $foo, $bar, $iStart, $iEnd, $aQuot While 1 $foo = StringInStr($sCodeStr, '"') ; Double quote $bar = StringInStr($sCodeStr, "'") ; Single quote If $foo = 0 And $bar = 0 Then ExitLoop If $foo > $bar And $bar > 0 Then $iStart = $bar $sQuot = "'" Else $iStart = $foo $sQuot = '"' EndIf $iEnd = StringInStr($sCodeStr, $sQuot, 0, 2) If $iEnd = 0 Then ; Error Code??? $sCodeStr = StringLeft($sCodeStr, $iStart -1) Else $sCodeStr = StringLeft($sCodeStr, $iStart -1) & " " & StringRight($sCodeStr, StringLen($sCodeStr) - $iEnd) EndIf WEnd EndFunc ;==> __StripOutStrings ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __IsConst ; Description ...: Checks to see if the string is the name of a constant. ; Syntax.........: __IsFunc($sTestStr) ; Parameters ....: $sTestStr - Variable name to test ; Return values .: Returns True or False ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: __IsFunc , __IsReserved ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __IsConst($sTestStr) $sTestStr = "|" & $sTestStr & "|" If StringInStr("|MATH_E|MATH_PHI|MATH_PI|MATH_PSI|", $sTestStr) Then Return True Else Return False EndIf EndFunc ;==> __IsConst ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __IsFunc ; Description ...: Checks to see if the string is the name of a function. ; Syntax.........: __IsFunc($sTestStr) ; Parameters ....: $sTestStr - Name to test ; Return values .: Returns True or False ; Author ........: czardas ; Modified.......: ; Remarks .......: Only recognises AutoMathEdit functions ; Related .......: __IsConst , __IsReserved ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __IsFunc($sTestStr) $sTestStr = "|" & $sTestStr & "|" If StringInStr("|_ATan2|_Combinations|_Degree|_Factorial|_Max|_Min|_Permutations|_Radian|Abs|ACos|ASin|ATan|BitAND|BitNOT|BitOR|BitRotate|BitShift|BitXOR|Ceiling|Cos|Dec|Echo|Exp|Floor|Hex|Log|Mod|Random|Round|Sin|Sqrt|Tan|", $sTestStr) Then Return True Else Return False EndIf EndFunc ;==> __IsFunc ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __IsReserved ; Description ...: Checks to see if the variable name is already being used. ; Syntax.........: __IsReserved($sTestStr) ; Parameters ....: $sTestStr - Variable name to test ; Return values .: Returns True or False ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: __IsConst , __IsFunc ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __IsReserved($sTestStr) $sTestStr = "|" & $sTestStr & "|" If StringInStr("|_subStr_|_in|no_|_error_|_sFail_|_sRawCode_|_aAssign_|_nValue_|_sScript_|_temp_|_aTemp_|_subLen_|_aScriptArr_|_aRawData_|", $sTestStr) Then Return True Else Return False EndIf EndFunc ;==> __IsReserved ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __AssignSplit ; Description ...: Splits an assignment command to var = expression ; Syntax.........: __AssignSplit($sAssignStr) ; Parameters ....: $sAssignStr - Line of code containing an assignment operator ; Return values .: An array where:- ; | element 0 = type of assignment = += -= *= /= ; | element 1 = variable name ; | element 2 = expression ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: None ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __AssignSplit($sAssignStr) Local $aAssignArr = StringSplit($sAssignStr, "=") ; Split string => variable equals expression If $aAssignArr[0] > 2 Then Return SetError(2, 0, 0) ; Only one assignment allowed per line Switch StringRight($aAssignArr[1], 1) Case "+","-","*","/" ; Get type of assignment $aAssignArr[0] = StringRight($aAssignArr[1], 1) ; += or -= or *= or /= $aAssignArr[1] = StringTrimRight($aAssignArr[1], 1) Case Else If StringRegExp($aAssignArr[1], "([+-*/][s]+z)") Then Return SetError(2) EndSwitch $aAssignArr[1] = StringStripWS($aAssignArr[1], 3) Return $aAssignArr EndFunc ;==> __AssignSplit ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __GetBreakPoint ; Description ...: Determines the exact line where a break in operations occurs - an error or a closing bracket for Echo ; Syntax.........: __GetBreakPoint($scriptStr, $iPosition [, $sErrorStr = False [, $iOccurence = 1 ]] ) ; Parameters ....: $scriptStr - AutoMathEdit ; : $iPosition - Line to start the search ; : $sErrorStr - Unexpected string which caused the function to fail ; : $iOccurence - The occurence of the error string to find. ; Return values .: The line number from the original script where the break in operations occured. ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: None ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __GetBreakPoint($scriptStr, $iPosition, $sErrorStr = False, $iOccurence = 1) Local $aScriptArr = StringSplit(StringStripCR($scriptStr), @LF), $iCount = 0 Switch $sErrorStr Case "=" For $i = $iPosition To $aScriptArr[0] If StringRegExp($aScriptArr[$i], "(s_s*z)") Then While StringInStr($aScriptArr[$i], $sErrorStr, 0, 1) $aScriptArr[$i] = StringReplace($aScriptArr[$i], $sErrorStr, "", 1) $iCount += 1 If $iCount = $iOccurence Then Return $i WEnd Else Return $i EndIf Next Case False While StringRegExp($aScriptArr[$iPosition], "(s_s*z)") $iPosition += 1 If $iPosition > $aScriptArr[0] Or $aScriptArr[$iPosition -1] = "" Then Return SetError (5, 0, $iPosition) ; Unterminated string WEnd Return $iPosition Case Else For $iPosition = $iPosition To $aScriptArr[0] If StringRegExp($aScriptArr[$iPosition], "(x24" & $sErrorStr &"[^w])") Or StringRegExp($aScriptArr[$iPosition], "([^w]" & $sErrorStr &"[^w])") Then Return $iPosition Next EndSwitch EndFunc ;==> __GetBreakPoint ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __ErrorMsg ; Description ...: Returns the details of an error encountered while parsing the script. ; Syntax.........: __ErrorMsg($vError) ; Parameters ....: $vError - Error code 1 - 8 ; Return values .: $vError - Details of the type of error encountered. ; Author ........: czardas ; Modified.......: ; Remarks .......: ; Related .......: None ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __ErrorMsg($vError) Switch $vError Case 1 $vError = "Illegal characters" Case 2 $vError = "Invalid Syntax" Case 3 $vError = "Function not recognised" Case 4 $vError = "Unexpected Termination" Case 5 $vError = "Unterminated String" Case 6 $vError = "Failed to reassign mathematical constant" Case 7 $vError = "Missing Parentheses" Case 8 $vError = "Unassigned Variable" EndSwitch Return $vError EndFunc ;==> __ErrorMsg ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name...........: __Return ; Description ...: Same as _ArrayToString, but with parameters already set ; Syntax.........: __Return($aRawData) ; Parameters ....: $aRawData - an array with the original script plus added comments. ; Return values .: Original script plus comments. ; Author ........: czardas ; Modified.......: ; Remarks .......: This function only exists to simplify reading the code for _Execute. ; Related .......: None ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func __Return($aRawData) Return _ArrayToString($aRawData, @CRLF, 1) EndFunc ;==> __Return ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #region ;... External library not yet complete Func _Permutations($n, $k) If Not IsInt($n) Or Not IsInt($k) Then Return SetError(1) If $k > $n Then Return 0 Return _Factorial($n)/(_Factorial($n -$k)) EndFunc ;==> _Permutations Func _Combinations($n, $k) If Not IsInt($n) Or $n < 1 Or Not IsInt($k) Or $k < 1 Then Return SetError(1) If $k > $n Then Return 0 Return _Factorial($n)/(_Factorial($k)*_Factorial($n -$k)) EndFunc ;==> _Combinations Func _Factorial($n) ; From UEZ If Not IsInt($n) Or $n < 1 Then Return SetError(1) Local $iRet = 1 For $i = 1 to $n $iRet *= $i Next Return $iRet EndFunc #endregion Test Edit Control #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> #include <GuiEdit.au3> #include <WinAPI.au3> #include <AutoMathEdit.au3> _MathEditorTest() Func _MathEditorTest() Local $hGUI = GUICreate("AutoMathScript Edit Control Test", 600, 400, Default, Default, BitOR($WS_OVERLAPPEDWINDOW, $WS_EX_COMPOSITED)) Local $hFileMenu = GUICtrlCreateMenu("File") Local $hExit = GUICtrlCreateMenuItem("Exit", $hFileMenu), _ $hTools = GUICtrlCreateMenu("Tools") Local $hExecute = GUICtrlCreateMenuItem("Execute" & @TAB & "F5", $hTools), _ $iyOffset = _WinAPI_GetSystemMetrics(55) ; SM_CYMENUSIZE Local $hEdit1 = GUICtrlCreateEdit("", 0, 0, 600, 400 - $iyOffset, BitOr($GUI_SS_DEFAULT_EDIT, $ES_NOHIDESEL)), _ $hF5 = GUICtrlCreateDummy(), _ $hTab = GUICtrlCreateDummy(), _ $hSelectAll = GUICtrlCreateDummy(), _ $AccelKeys[3][2] = [[ @TAB, $hTab],["^a", $hSelectAll],["{F5}", $hF5]] GUICtrlSetFont($hEdit1, 12, 400, 1, "Lucida Console") GUISetAccelerators($AccelKeys) GUISetState() While 1 $msg = GUIGetMsg() Switch $msg Case $GUI_EVENT_CLOSE, $hExit ExitLoop Case $hExecute, $hF5 $sRet = _Execute(_GetSelectedText($hEdit1)) _GUICtrlEdit_ReplaceSel($hEdit1, $sRet) Case $hTab _TAB($hEdit1) Case $hSelectAll _SelectAll($hEdit1) EndSwitch WEnd EndFunc ;==> _MathEditorTest Func _GetSelectedText($hEdit) Local $aPos = _GUICtrlEdit_GetSel($hEdit) If $aPos[0] = $aPos[1] Then Return SetError(1, 0, "") ; Nothing selected $sRet = StringMid(_GUICtrlEdit_GetText($hEdit), $aPos[0] +1, $aPos[1] - $aPos[0]) Return $sRet EndFunc ;==> _GetSelectedText Func _TAB($hEdit) Local $sSelText = _GetSelectedText($hEdit) If Not @error Then Local $aLines = StringSplit($sSelText, @CRLF, 1) If $aLines[0] > 1 Then For $i = 1 To $aLines[0] $aLines[$i] = @TAB & $aLines[$i] Next _GUICtrlEdit_ReplaceSel($hEdit, _ArrayToString($aLines, @CRLF, 1)) Return EndIf EndIf _GUICtrlEdit_ReplaceSel($hEdit, @TAB) EndFunc ;==> _TAB Func _SelectAll($hEdit) _GUICtrlEdit_SetSel($hEdit, 0, -1) EndFunc ;==> _SelectAll See next post for features, history and AutoMathEdit examples.1 point
-
Hello, Just a quick and dirty example using nslookup command: #include <Constants.au3> Local $hostname="autoitscript.com" ;just a hostname example using autoitscript.com Local $DNSserver="8.8.8.8" ;just an example using Google DNS server (if you want to use default server just remove the ip: Local $DNSserver="" $GETNORMAL=_NormalLookup($hostname,$DNSserver) If @error Then MsgBox(0,"","Error trying to get ip for " & $hostname) Exit Else MsgBox(0,"","Normal Lookup for hostname " & $hostname & " is " & $GETNORMAL) EndIf $GETREVERSE=_ReverseLookup($GETNORMAL,$DNSserver) If @error Then MsgBox(0,"","Error trying to get reverse lookup for " & $hostname) Exit Else MsgBox(0,"","Reverse Lookup for ip " & $GETNORMAL & " is " & $GETREVERSE) EndIf Func _ReverseLookup($fip="127.0.0.1",$fDNSserver="") Local $Consigue=Run(@ComSpec & " /c " & 'nslookup -type=PTR ' & $fip & ' ' & $fDNSserver, "", @SW_HIDE,$STDERR_CHILD + $STDOUT_CHILD) Local $line While 1 $line &= StdoutRead($Consigue) If @error Then ExitLoop WEnd Local $array=StringRegExp($line,".*name\ =\ (.+)?",3) If @error Then SetError(1) Else Return StringStripWS(StringStripCR($array[0]),8) EndIf EndFunc Func _NormalLookup($fhostname="localhost",$fDNSserver="") Local $Consigue=Run(@ComSpec & " /c " & 'nslookup -type=A ' & $fhostname & ' ' & $fDNSserver, "", @SW_HIDE,$STDERR_CHILD + $STDOUT_CHILD) Local $line While 1 $line &= StdoutRead($Consigue) If @error Then ExitLoop WEnd Local $array=StringRegExp($line,"(?s)Name:.*Address:\ (.+)",3) If @error Then SetError(1) Else Return StringStripWS(StringStripCR($array[0]),8) EndIf EndFunc Keep in mind what I said, it is quick and really dirty, it will fail if the hostname has more than one ip, etc. so I recommend to take a look to already implemented functions TCPNameToIP and _TCPIpToName (check the examples in AutoIT help). Edit: To add example using TCP functions: #include <Inet.au3> Local $hostname=@ComputerName TCPStartup() $tcpnametoip=TCPNameToIP($hostname) $tcpiptoname=_TCPIpToName($tcpnametoip) MsgBox(64,"Reverse Lookup", "Hostname " & $hostname & " resolves to " & $tcpnametoip & @CRLF & _ "IP " & $tcpnametoip & " reverses to " & $tcpiptoname) Cheers,1 point
-
1 point
-
Here, let me then: #include <WinApi.au3> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; AddHookApi("user32.dll", "MessageBoxW", "Intercept_MessageBoxW", "int", "hwnd;wstr;wstr;uint") Func Intercept_MessageBoxW($hWnd, $sText, $sTitle, $iType) Local $aCall = DllCall("user32.dll", "int", "MessageBoxW", _ "hwnd", $hWnd, _ "wstr", $sText, _ "wstr", StringReplace($sTitle, "AutoIt", @ScriptName), _ "uint", $iType) If @error Or Not $aCall[0] Then Return 0 Return $aCall[0] EndFunc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Let's try it ; Usual message box MsgBox(0, 'Test', 'Some text') ; Cause error that would say some AutoIt shit happened, but now it wouldn't say "AutoIt" DllStructCreate("byte[123456789097]") ; The End ; The magic is down below Func AddHookApi($sModuleName, $vFunctionName, $vNewFunction, $sRet = "", $sParams = "") Local Static $pImportDirectory, $hInstance Local Const $IMAGE_DIRECTORY_ENTRY_IMPORT = 1 If Not $pImportDirectory Then $hInstance = _WinAPI_GetModuleHandle(0) $pImportDirectory = ImageDirectoryEntryToData($hInstance, $IMAGE_DIRECTORY_ENTRY_IMPORT) If @error Then Return SetError(1, 0, 0) EndIf Local $iIsInt = IsInt($vFunctionName) Local $iRestore = Not IsString($vNewFunction) Local $tIMAGE_IMPORT_MODULE_DIRECTORY Local $pDirectoryOffset = $pImportDirectory Local $tModuleName Local $iInitialOffset, $iInitialOffset2 Local $iOffset2 Local $tBufferOffset2, $iBufferOffset2 Local $tBuffer, $tFunctionOffset, $pOld, $fMatch, $pModuleName, $pFuncName Local Const $PAGE_READWRITE = 0x04 While 1 $tIMAGE_IMPORT_MODULE_DIRECTORY = DllStructCreate("dword RVAOriginalFirstThunk;" & _ "dword TimeDateStamp;" & _ "dword ForwarderChain;" & _ "dword RVAModuleName;" & _ "dword RVAFirstThunk", _ $pDirectoryOffset) If Not DllStructGetData($tIMAGE_IMPORT_MODULE_DIRECTORY, "RVAFirstThunk") Then ExitLoop $pModuleName = $hInstance + DllStructGetData($tIMAGE_IMPORT_MODULE_DIRECTORY, "RVAModuleName") $tModuleName = DllStructCreate("char Name[" & _WinAPI_StringLenA($pModuleName) & "]", $pModuleName) If DllStructGetData($tModuleName, "Name") = $sModuleName Then ; function from this module $iInitialOffset = $hInstance + DllStructGetData($tIMAGE_IMPORT_MODULE_DIRECTORY, "RVAFirstThunk") $iInitialOffset2 = $hInstance + DllStructGetData($tIMAGE_IMPORT_MODULE_DIRECTORY, "RVAOriginalFirstThunk") If $iInitialOffset2 = $hInstance Then $iInitialOffset2 = $iInitialOffset $iOffset2 = 0 While 1 $tBufferOffset2 = DllStructCreate("dword_ptr", $iInitialOffset2 + $iOffset2) $iBufferOffset2 = DllStructGetData($tBufferOffset2, 1) If Not $iBufferOffset2 Then ExitLoop If $iIsInt Then If BitAND($iBufferOffset2, 0xFFFFFF) = $vFunctionName Then $fMatch = True; wanted function Else $pFuncName = $hInstance + $iBufferOffset2 + 2 ; 2 is size od "word", see line below... $tBuffer = DllStructCreate("word Ordinal; char Name[" & _WinAPI_StringLenA($pFuncName) & "]", $hInstance + $iBufferOffset2) If DllStructGetData($tBuffer, "Name") == $vFunctionName Then $fMatch = True; wanted function EndIf If $fMatch Then $tFunctionOffset = DllStructCreate("ptr", $iInitialOffset + $iOffset2) VirtualProtect(DllStructGetPtr($tFunctionOffset), DllStructGetSize($tFunctionOffset), $PAGE_READWRITE) If @error Then Return SetError(3, 0, 0) $pOld = DllStructGetData($tFunctionOffset, 1) If $iRestore Then DllStructSetData($tFunctionOffset, 1, $vNewFunction) Else DllStructSetData($tFunctionOffset, 1, DllCallbackGetPtr(DllCallbackRegister($vNewFunction, $sRet, $sParams))) EndIf Return $pOld EndIf $iOffset2 += DllStructGetSize($tBufferOffset2) WEnd ExitLoop EndIf $pDirectoryOffset += 20 ; size of $tIMAGE_IMPORT_MODULE_DIRECTORY WEnd Return SetError(4, 0, 0) EndFunc Func VirtualProtect($pAddress, $iSize, $iProtection) Local $aCall = DllCall("kernel32.dll", "bool", "VirtualProtect", "ptr", $pAddress, "dword_ptr", $iSize, "dword", $iProtection, "dword*", 0) If @error Or Not $aCall[0] Then Return SetError(1, 0, 0) Return 1 EndFunc Func ImageDirectoryEntryToData($hInstance, $iDirectoryEntry) ; Get pointer to data Local $pPointer = $hInstance ; Start processing passed binary data. 'Reading' PE format follows. Local $tIMAGE_DOS_HEADER = DllStructCreate("char Magic[2];" & _ "word BytesOnLastPage;" & _ "word Pages;" & _ "word Relocations;" & _ "word SizeofHeader;" & _ "word MinimumExtra;" & _ "word MaximumExtra;" & _ "word SS;" & _ "word SP;" & _ "word Checksum;" & _ "word IP;" & _ "word CS;" & _ "word Relocation;" & _ "word Overlay;" & _ "char Reserved[8];" & _ "word OEMIdentifier;" & _ "word OEMInformation;" & _ "char Reserved2[20];" & _ "dword AddressOfNewExeHeader", _ $pPointer) Local $sMagic = DllStructGetData($tIMAGE_DOS_HEADER, "Magic") ; Check if it's valid format If Not ($sMagic == "MZ") Then Return SetError(1, 0, 0) ; MS-DOS header missing. Btw 'MZ' are the initials of Mark Zbikowski in case you didn't know. ; Move pointer $pPointer += DllStructGetData($tIMAGE_DOS_HEADER, "AddressOfNewExeHeader") ; move to PE file header ; In place of IMAGE_NT_SIGNATURE structure Local $tIMAGE_NT_SIGNATURE = DllStructCreate("dword Signature", $pPointer) ; Check signature If DllStructGetData($tIMAGE_NT_SIGNATURE, "Signature") <> 17744 Then ; IMAGE_NT_SIGNATURE Return SetError(2, 0, 0) ; wrong signature. For PE image should be "PE\0\0" or 17744 dword. EndIf ; Move pointer $pPointer += 4 ; size of $tIMAGE_NT_SIGNATURE structure ; In place of IMAGE_FILE_HEADER structure ; Move pointer $pPointer += 20 ; size of $tIMAGE_FILE_HEADER structure ; Determine the type Local $tMagic = DllStructCreate("word Magic;", $pPointer) Local $iMagic = DllStructGetData($tMagic, 1) Local $tIMAGE_OPTIONAL_HEADER If $iMagic = 267 Then ; x86 version ; Move pointer $pPointer += 96 ; size of $tIMAGE_OPTIONAL_HEADER ElseIf $iMagic = 523 Then ; x64 version ; Move pointer $pPointer += 112 ; size of $tIMAGE_OPTIONAL_HEADER Else Return SetError(3, 0, 0) ; unsupported module type EndIf ; Validate input by checking available number of structures that are in the module Local Const $IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16 ; predefined value that PE modules always use (AutoIt certainly) If $iDirectoryEntry > $IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1 Then Return SetError(4, 0, 0) ; invalid input ; Calculate the offset to wanted entry (every entry is 8 bytes) $pPointer += 8 * $iDirectoryEntry ; At place of correst directory entry Local $tIMAGE_DIRECTORY_ENTRY = DllStructCreate("dword VirtualAddress; dword Size", $pPointer) ; Collect data Local $pAddress = DllStructGetData($tIMAGE_DIRECTORY_ENTRY, "VirtualAddress") If $pAddress = 0 Then Return SetError(5, 0, 0) ; invalid input ; $pAddress is RVA, add it to base address Return $hInstance + $pAddress EndFuncedit: because this is better than before.1 point