Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 12/04/2015 in all areas

  1. LockFile allows you to lock a file to the current process. This is useful if you want to interact with a specific file but wish to avoid the accidental deletion by another process or worse still a user. Examples have been provided and any advice for improvements is much appreciated. UDF: #include-once ; #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 ; #INDEX# ======================================================================================================================= ; Title .........: Lock_File ; AutoIt Version : v3.3.10.0 or higher ; Language ......: English ; Description ...: Lock a file to the current process only. Any attempts to interact with the file by another process will fail ; Note ..........: ; Author(s) .....: guinness ; Remarks .......: The locked file handle must be closed with the Lock_Unlock() function after use ; =============================================================================================================================== ; #INCLUDES# ========================================================================================================= #include <WinAPI.au3> ; #GLOBAL VARIABLES# ================================================================================================= ; None ; #CURRENT# ===================================================================================================================== ; Lock_Erase: Erase the contents of a locked file ; Lock_File: Lock a file to the current process only ; Lock_Read: Read data from a locked file ; Lock_Reduce: Reduce the locked file by a certain percentage ; Lock_Write: Write data to a locked file ; Lock_Unlock: Unlock a file so other processes can interact with it ; =============================================================================================================================== ; #INTERNAL_USE_ONLY#============================================================================================================ ; None ; =============================================================================================================================== ; #FUNCTION# ==================================================================================================================== ; Name ..........: Lock_Erase ; Description ...: Erase the contents of a locked file ; Syntax ........: Lock_Erase($hFile) ; Parameters ....: $hFile - Handle returned by Lock_File() ; Return values .: Success - True ; Failure - False, use _WinAPI_GetLastError() to get additional details ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func Lock_Erase($hFile) _WinAPI_SetFilePointer($hFile, $FILE_BEGIN) Return _WinAPI_SetEndOfFile($hFile) EndFunc ;==>Lock_Erase ; #FUNCTION# ==================================================================================================================== ; Name ..........: Lock_File ; Description ...: Lock a file to the current process only ; Syntax ........: Lock_File($sFilePath[, $bCreateNotExist = False]) ; Parameters ....: $sFilePath - Filepath of the file to lock ; $bCreateNotExist - [optional] Create the file if it doesn't exist (True) or don't create (False). Default is False ; Return values .: Success - Handle of the locked file ; Failure - Zero and sets @error to non-zero. Call _WinAPI_GetLastError() to get extended error information ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func Lock_File($sFilePath, $bCreateNotExist = False) Return _WinAPI_CreateFile($sFilePath, BitOR($CREATE_ALWAYS, (IsBool($bCreateNotExist) And $bCreateNotExist ? $CREATE_NEW : 0)), BitOR($FILE_SHARE_WRITE, $FILE_SHARE_DELETE), 0, 0, 0) ; Creation = 2, Access = 2 + 4, Sharing = 0, Attributes = 0, Security = 0 EndFunc ;==>Lock_File ; #FUNCTION# ==================================================================================================================== ; Name ..........: Lock_Read ; Description ...: Read data from a locked file ; Syntax ........: Lock_Read($hFile) ; Parameters ....: $hFile - Handle returned by Lock_File() ; $iBinaryFlag - [optional] Flag value to pass to BinaryToString(). Default is $SB_UTF8. See BinaryToString() documentation for more details ; Return values .: Success - Data read from the file ; Failure - Empty string and sets @error to non-zero ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func Lock_Read($hFile, $iBinaryFlag = $SB_UTF8) Local $iFileSize = _WinAPI_GetFileSizeEx($hFile) + 1, _ $sText = '' Local $tBuffer = DllStructCreate('byte buffer[' & $iFileSize & ']') _WinAPI_SetFilePointer($hFile, $FILE_BEGIN) _WinAPI_ReadFile($hFile, DllStructGetPtr($tBuffer), $iFileSize, $sText) Return SetError(@error, 0, BinaryToString(DllStructGetData($tBuffer, 'buffer'), $iBinaryFlag)) EndFunc ;==>Lock_Read ; #FUNCTION# ==================================================================================================================== ; Name ..........: Lock_Reduce ; Description ...: Reduce the locked file by a certain percentage ; Syntax ........: Lock_Reduce($hFile, $iPercentage) ; Parameters ....: $hFile - Handle returned by Lock_File() ; $iPercentage - A percentage value to reduce the file by ; Return values .: Success - True ; Failure - False. Use _WinAPI_GetLastError() to get additional details ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func Lock_Reduce($hFile, $iPercentage) If Not IsInt($iPercentage) Then $iPercentage = Int($iPercentage) If $iPercentage > 0 And $iPercentage < 100 Then Local $iFileSize = _WinAPI_GetFileSizeEx($hFile) * ($iPercentage / 100) _WinAPI_SetFilePointer($hFile, $iFileSize) Return _WinAPI_SetEndOfFile($hFile) EndIf Return Lock_Erase($hFile) EndFunc ;==>Lock_Reduce ; #FUNCTION# ==================================================================================================================== ; Name ..........: Lock_Write ; Description ...: Write data to a locked file ; Syntax ........: Lock_Write($hFile, $sText) ; Parameters ....: $hFile - Handle returned by Lock_File() ; $sText - Data to be written to the locked file ; Return values .: Success - Number of bytes written to the file ; Failure - 0 and sets @error to non-zero ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func Lock_Write($hFile, $sText) Local $iFileSize = _WinAPI_GetFileSizeEx($hFile), _ $iLength = StringLen($sText) Local $tBuffer = DllStructCreate('byte buffer[' & $iLength & ']') DllStructSetData($tBuffer, 'buffer', $sText) _WinAPI_SetFilePointer($hFile, $iFileSize) Local $iWritten = 0 _WinAPI_WriteFile($hFile, DllStructGetPtr($tBuffer), $iLength, $iWritten) Return SetError(@error, @extended, $iWritten) ; Number of bytes written EndFunc ;==>Lock_Write ; #FUNCTION# ==================================================================================================================== ; Name ..........: Lock_Unlock ; Description ...: Unlock a file so other applications can interact with it ; Syntax ........: Lock_Unlock($hFile) ; Parameters ....: $hFile - Handle returned by Lock_File() ; Return values .: Success - True ; Failure - False ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func Lock_Unlock($hFile) Return _WinAPI_CloseHandle($hFile) EndFunc ;==>Lock_Unlock Example 1: (with LockFile) #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> ; Include the LockFile.au3 UDF #include 'LockFile.au3' ; LockFile by guinness Example_1() Func Example_1() ; Path of the locked file Local Const $sFilePath = _WinAPI_GetTempFileName(@TempDir) ; Lock the file to this process and create it if not already done so Local $hLock = Lock_File($sFilePath, True) ; Erase the contents of the locked file Lock_Erase($hLock) ; Write random data to the locked file For $i = 1 To 5 Lock_Write($hLock, RandomText(10) & @CRLF) Next ; Read the locked file Local $sRead = Lock_Read($hLock) ; Display the contents of the locked file that was just read MsgBox($MB_SYSTEMMODAL, '', $sRead) ; Display the current file size of the locked file. For example 60 bytes MsgBox($MB_SYSTEMMODAL, '', ByteSuffix(_WinAPI_GetFileSizeEx($hLock))) ; Reduce the file size by 50% Lock_Reduce($hLock, 50) ; Display the reduced size. This will be 50% less than before. For example 30 bytes MsgBox($MB_SYSTEMMODAL, '', ByteSuffix(_WinAPI_GetFileSizeEx($hLock))) ; Delete the locked file. As this is locked the deletion will fail MsgBox($MB_SYSTEMMODAL, '', 'Delete the locked file: ' & _ @CRLF & _ @CRLF & _ FileDelete($sFilePath) & ' (this will return 0, as the file is currently locked).') ; Unlock the locked file Lock_Unlock($hLock) ; Delete the file as it is now unlocked MsgBox($MB_SYSTEMMODAL, '', 'Delete the locked file: ' & _ @CRLF & _ @CRLF & _ FileDelete($sFilePath) & ' (this will return 1, as the file is unlocked).') EndFunc ;==>Example_1 ; Convert a boolean datatype to an integer representation Func BooleanToInteger($bValue) Return $bValue ? 1 : 0 EndFunc ;==>BooleanToInteger ; Append the largest byte suffix to a value Func ByteSuffix($iBytes, $iRound = 2) ; By Spiff59 Local Const $aArray = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'] Local $iIndex = 0 While $iBytes > 1023 And $iIndex < UBound($aArray) $iIndex += 1 $iBytes /= 1024 WEnd Return Round($iBytes, Int($iRound)) & $aArray[$iIndex] EndFunc ;==>ByteSuffix ; Generate random text Func RandomText($iLength) Local $iRandom = 0, _ $sData = '' For $i = 1 To $iLength $iRandom = Random(55, 116, 1) $sData &= Chr($iRandom + 6 * BooleanToInteger($iRandom > 90) - 7 * BooleanToInteger($iRandom < 65)) Next Return $sData EndFunc ;==>RandomText Example 2: (without LockFile) #include <MsgBoxConstants.au3> #include <StringConstants.au3> #include <WinAPIFiles.au3> ; Traditional approach to reading and writing to a file. Due to the nature of AutoIt, the file isn't locked, thus allowing other processes to interact with the file Example_2() Func Example_2() ; Path of the locked file Local $sFilePath = _WinAPI_GetTempFileName(@TempDir) ; Lock the file to this process and create it if not already done so This is writing mode Local $hLock = FileOpen($sFilePath, $FO_OVERWRITE) ; Erase the contents of the locked file FileWrite($hLock, '') ; Write random data to the locked file For $i = 1 To 5 FileWrite($hLock, RandomText(10) & @CRLF) Next ; Close the file handle and create another handle to read the file contents FileClose($hLock) $hLock = FileOpen($sFilePath, $FO_READ) ; Read the locked file Local $sRead = FileRead($hLock) ; Display the contents of the locked file that was just read MsgBox($MB_SYSTEMMODAL, '', $sRead) ; Delete the locked file. As this is not locked by AutoIt the file will be deleted MsgBox($MB_SYSTEMMODAL, '', 'Delete the locked file: ' & _ @CRLF & _ @CRLF & _ FileDelete($sFilePath) & ' (this will return 1, as the file is''t locked by AutoIt due to safety measures in place).') ; Unlock the locked file (though not really locked) FileClose($hLock) EndFunc ;==>Example_2 ; Convert a boolean datatype to an integer representation Func BooleanToInteger($bValue) Return $bValue ? 1 : 0 EndFunc ;==>BooleanToInteger ; Generate random text Func RandomText($iLength) Local $iRandom = 0, _ $sData = '' For $i = 1 To $iLength $iRandom = Random(55, 116, 1) $sData &= Chr($iRandom + 6 * BooleanToInteger($iRandom > 90) - 7 * BooleanToInteger($iRandom < 65)) Next Return $sData EndFunc ;==>RandomText All of the above has been included in a ZIP file. Previous download: 866+ LockFile.zip
    1 point
  2. This is a very simple sample about checking printer status and set its online/offline status.may help those who in need of this issue. $StrComputer="." $obj=ObjGet("winmgmts:\\"&$StrComputer&"\root\CIMV2") $colitems=$obj.ExecQuery("Select * from Win32_Printer") For $objitem In $colitems If $objitem.Caption=="SHARP AR-1808S" Then $a=Int($objitem.Attributes / 1024) If Mod($a, 2)=0 Then MsgBox(0,0,"Printer is online",8) ElseIf Mod($a, 2)=1 Then MsgBox(0,0,"Printer is offline,press 'OK'button To make the printer online ",8) ;core code $objitem.WorkOffline = False $objitem.Put_ ;~~~~~~~~~~~~~~~~~~~~~~ MsgBox(0,'','Printer is online now.') Else MsgBox(0,0,"unknown status",8) EndIf EndIf next
    1 point
  3. Hi! If you liked my TCPServer UDF, you'll also like this one. Following the same principles, this TCPClient UDF helps you on handling multiple connections to different servers, and set actions depending on two events: OnReceive and OnDisconnect. It is also multi server (you can connect to many servers at once) and you can also bind a Console-based executable to the socket (similar to -e parameter in NetCat). This feature is useful if you want to use some Console UDF to create a TCP application and don't want to deal with the TCP* functions. Also, it runs on background just firing events, it won't pause your script while waiting/receiving data, so you can do anything else (close and open connections, allow the user to click buttons or just wait on an infinite loop) that your callbacks will be called once the event is fired It is also very easy to use. See this examples: Example #1: Connecting to a basic server By running this (as soon as you open a basic server with Netcat) you will receive a message box telling you when the server closes the connection (the socket ID and his IP address are passed as parameter to your callback function) and also when the server sends something over the TCP socket (the data sent is passed as parameter). #cs Download netcat at https://eternallybored.org/misc/netcat/ Execute this script Run in CMD: nc -vv -l -p 8081 #ce #include "TCPClient.au3" ; First we set the callback functions for the two events (none of them is mandatory) _TCPClient_OnDisconnect("disconnect") _TCPClient_OnReceive("received") ; And a parameter _TCPClient_DebugMode(True) ; Finally we connect to the server at port 8081 at any interface _TCPClient_Connect('127.0.0.1', 8081) Func disconnect($iSocket, $sIP) MsgBox(0, "Server disconnected", "Server " & $sIP & " disconnected from socket " & $iSocket) EndFunc ;==>disconnect Func received($iSocket, $sIP, $sData, $sPar) MsgBox(0, "Data received from " & $sIP, $sData & @CRLF & "Parameter: " & $sPar) _TCPClient_Send($iSocket, "You wrote: " & $sData) _TCPClient_SetParam($iSocket, 'will write again') EndFunc ;==>received While 1 Sleep(100) WEndExample #2: Requesting a page from a HTTP server In this example, we run this code and it will get the response from a HTTP server. Of course, as we are requesting google.com index, it may just show a redirect page to a local (with country top-level domain) Google page or with some stuff on the URL. #include "TCPClient.au3" _TCPClient_OnReceive("received") _TCPClient_DebugMode(True) $iSocket = _TCPClient_Connect(TCPNameToIP('google.com'), 80) If @error Then Exit _TCPClient_Send($iSocket, "GET / HTTP/1.0" & @CRLF & @CRLF) Func received($iSocket, $sIP, $sData, $sParam) MsgBox(0, "Data received", $sData) _TCPClient_Disconnect($iSocket) EndFunc ;==>received While 1 Sleep(100) WEndExample #3: Command prompt bound to the socket after password requesting By running this example, we will be asked for a password, which is 123456 as we set on the script. If the password is correct, we will see the Command Prompt live-updated (try running a ping to some server, for example). #include "TCPClient.au3" #cs To test this example, execute a netcat server, running this commands: nc -vv -l -p 31337 #ce Global $Password = "123456" _TCPClient_OnReceive("receive") _TCPClient_OnDisconnect("disconnect") _TCPClient_DebugMode() Func receive($iSocket, $sIP, $sData, $mPar) If $mPar = "login" Then If $sData = $Password Then ; right password, let's change the parameter _TCPClient_SetParam($iSocket, "logged") ; and now bind _TCPClient_BindAppToSocket($iSocket, "cmd.exe") Else _TCPClient_Send($iSocket, "Wrong password. Try again: ") EndIf Else If $sData = "exit" Then ; unbinds _TCPClient_UnBindAppToSocket($iSocket) ; says bye _TCPClient_Send($iSocket, "See you") ; closes connection _TCPClient_Disconnect($iSocket) Else ; sends command directly to the process _TCPClient_SendToBound($iSocket, $sData) EndIf EndIf EndFunc Func disconnect($iSocket, $sIP) MsgBox(0, $iSocket, $sIP) EndFunc $iSocket = _TCPClient_Connect('127.0.0.1', '31337') If @error Then MsgBox(0, "", "could not connect. Error: " & @error) Exit EndIf ; Sets parameter to login, so we know what the server is doing _TCPClient_SetParam($iSocket, "login") _TCPClient_Send($iSocket, "Please enter password: ") While True Sleep(100) WEndThe limit is your imagination? Well, maybe. Functions list: _TCPClient_Connect($sSvr, $iPort) _TCPClient_Disconnect($iSocket) _TCPClient_SetParam($iSocket, $sPar) _TCPClient_Send($iSocket, $sData) _TCPClient_Broadcast($sData [, $iExceptSocket = 0 ]) _TCPClient_ListConnections() _TCPClient_BindAppToSocket($iSocket, $sCommand [, $sWorkingDir = @WorkingDir ]) _TCPClient_SendToBound($iSocket, $sData) _TCPClient_UnBindAppToSocket($iSocket) _TCPClient_OnReceive($sCallback) _TCPClient_OnDisconnect($sCallback) _TCPClient_DebugMode([ $bMOde = "toggle" ]) _TCPClient_AutoTrim([ $bMode = "toggle" ]) _TCPClient_SocketToConnID($iSocket) _TCPClient_ConnIDToSocket($iConn) _TCPClient_SocketToIP($iSocket)Help file and more examples included! Latest version: 1.0.0 Download: https://www.autoitscript.com/forum/files/file/377-tcpclient-udf/ Changelog 1.0.0 - First release - 03/12/2015If you can't open the help file, please uncompress it, go to properties and click Unlock. Fork me on Github: http://github.com/jesobreira/tcpclient-udf
    1 point
  4. 4000 lines of code/data is not problem. Whole application with more forms is able to read/write data to/from any desired form.
    1 point
  5. Definitelly look at this: https://www.autoitscript.com/wiki/Managing_Multiple_GUIs
    1 point
  6. The explanations are much more complicated than the code. Here's the code: #include <GUIConstants.au3> #include <WinAPIShellEx.au3> #include <GuiEdit.au3> Opt( "MustDeclareVars", 1 ) Example() Func Example() Local $hGui = GUICreate( "Input (numbers only)", 300, 118 ) Local $idInput = GUICtrlCreateInput( "", 50, 50, 200, 18, $GUI_SS_DEFAULT_INPUT+$ES_NUMBER ) Local $hInput = GUICtrlGetHandle( $idInput ) GUICtrlCreateLabel( "No context menu, no paste, no balloontip", 50, 70, 200, 18 ) ; Register callback function to subclass Input control Local $pInputProc = DllCallbackGetPtr( DllCallbackRegister( "InputProc", "lresult", "hwnd;uint;wparam;lparam;uint_ptr;dword_ptr" ) ) _WinAPI_SetWindowSubclass( $hInput, $pInputProc, 9999, 0 ) ; SubclassId = 9999, $pData = 0 GUISetState() While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd ; Cleanup _WinAPI_RemoveWindowSubclass( $hInput, $pInputProc, 9999 ) GUIDelete( $hGui ) Exit EndFunc ; InputProc callback function Func InputProc( $hWnd, $iMsg, $wParam, $lParam, $iSubclassId, $pData ) Switch $iMsg Case $WM_CONTEXTMENU, $WM_PASTE, $EM_SHOWBALLOONTIP Return 0 EndSwitch ; Call next function in subclass chain Return DllCall( "comctl32.dll", "lresult", "DefSubclassProc", "hwnd", $hWnd, "uint", $iMsg, "wparam", $wParam, "lparam", $lParam )[0] ; _WinAPI_DefSubclassProc EndFunc
    1 point
  7. JohnOne

    ControlClick

    Just realized, It's because the installation app requires admin. You cannot interact with an admin window from a non-admin program, so... #RequireAdmin ...in script solves problem,
    1 point
  8. 1) You can easily catch single clicks in a listbox, but you have to respond to WM_COMMAND messages. See example for _GUICtrlListBox_Create in helpfile and watch the event that's fired for a single click. 2) I think this is possible. Take a look at _WinAPI_TrackMouseEvent.
    1 point
  9. If you want to paste a text every time F4 is pressed, you could do: Global Const $text = "text to paste" HotKeySet("{F4}", "paste") Func paste() Send($text) EndFunc While 1 Sleep(100) WEndNote that this script writes, instead of pasting. If you really want to paste... Global Const $text = "text to paste" HotKeySet("{F4}", "paste") Func paste() ClipPut($text) ; copy to clipboard Send("^v") ; Ctrl + V, see helpfile EndFunc While 1 Sleep(100) WEnd
    1 point
  10. Jefrey

    Socket Error

    Hi! Could you try posting on English language?
    1 point
  11. 1 point
  12. If you just want to write an array to an excel file I have used this and it worked great. You can also do a file write loop and create a .csv If you want to add data to an existing excel file or have a higher level of interaction I would use Waters Excel.UDF
    1 point
  13. Example 2 should fit. It writes an 1D array to Excel. Example 3 uses an 2D array.
    1 point
  14. mLipok, In this version of example 9 code is added to read and save column order in "HdrItemOrder.ini". #include <GUIConstants.au3> #include <GuiListView.au3> #include <WinAPIShellEx.au3> #include "GuiListViewEx.au3" #include "ListViewCustomDraw.au3" Opt( "MustDeclareVars", 1 ) Global $hGui, $idListView, $hListView, $fListViewHasFocus = 0, $hLVfont, $iItems = 1000, $aLines[1][4] Global $hHeader, $fHeaderOrderOfItem0 = 0 ; $fHeaderOrderOfItem0 is used to handle column 0 issue Example() Func Example() ; Create GUI $hGui = GUICreate( "Rearrange columns", 440, 320 ) ; Create ListView $idListView = GUICtrlCreateListView( "", 10, 10, 420, 300, $GUI_SS_DEFAULT_LISTVIEW-$LVS_SINGLESEL, $WS_EX_CLIENTEDGE+$LVS_EX_DOUBLEBUFFER+$LVS_EX_FULLROWSELECT+$LVS_EX_GRIDLINES+$LVS_EX_HEADERDRAGDROP ) $hListView = GUICtrlGetHandle( $idListView ) ; Reduce flicker ; Increase item height $hLVfont = _GUICtrlListView_SetItemHeightByFont( $hListView, 26 ) ; Add columns to ListView _GUICtrlListView_AddColumn( $hListView, "Column 1", 94 ) _GUICtrlListView_AddColumn( $hListView, "Column 2", 94 ) _GUICtrlListView_AddColumn( $hListView, "Column 3", 94 ) _GUICtrlListView_AddColumn( $hListView, "Column 4", 94 ) ; Fill ListView Local $idItem For $i = 0 To $iItems - 1 $idItem = GUICtrlCreateListViewItem( $i & " Column 1|" & $i & " Column 2|" & $i & " Column 3|" & $i & " Column 4", $idListView ) ; $idItem (controlID) is stored in ItemParam in the internal storage allocated for the ListView If Not $i Then ReDim $aLines[$idItem+$iItems][4] ; Second line in ListView items is stored in $aLines array $aLines[$idItem][0] = $i & " Line 2/1" ; $idItem (controlID, stored in ItemParam) is row index in $aLines $aLines[$idItem][1] = $i & " Line 2/2" ; Four item texts are stored in four columns in $aLines array $aLines[$idItem][2] = $i & " Line 2/3" ; If line texts are stored as strings it's easy to test for empty texts $aLines[$idItem][3] = $i & " Line 2/4" Next ; Adjust height of GUI and ListView to fit ten rows Local $iLvHeight = _GUICtrlListView_GetHeightToFitRows( $hListView, 10 ) WinMove( $hGui, "", Default, Default, Default, WinGetPos( $hGui )[3] - WinGetClientSize( $hGui )[1] + $iLvHeight + 20 ) WinMove( $hListView, "", Default, Default, Default, $iLvHeight ) ; Column 0 issue ; Header handle and position $hHeader = _GUICtrlListView_GetHeader( $hListView ) Local $tRect = _WinAPI_GetClientRect( $hListView ) Local $tPos = _GUICtrlHeader_Layout( $hHeader, $tRect ) Local $aHdrPos = WinGetPos( $hHeader ) ; Left/top corner in screen coordinates $aHdrPos[2] = $aHdrPos[0] + DllStructGetData( $tPos, "CX" ) ; Right/bottom corner in screen coordinates $aHdrPos[3] = $aHdrPos[1] + DllStructGetData( $tPos, "CY" ) Local $bMouseClickHeader = False ; Read Header item order Local $aHdrItemOrder0 = [ 4, 0, 1, 2, 3 ], $aHdrItemOrder, $sOrder If FileExists( "HdrItemOrder.ini" ) Then $sOrder = FileReadLine( "HdrItemOrder.ini" ) $aHdrItemOrder = StringSplit( $sOrder, "|", 2 ) ; 2 = $STR_NOCOUNT For $i = 1 To $aHdrItemOrder[0] If $aHdrItemOrder[$i] <> $aHdrItemOrder0[$i] Then ExitLoop Next If $i < $aHdrItemOrder[0] Then _GUICtrlHeader_SetOrderArray( $hHeader, $aHdrItemOrder ) $aHdrItemOrder0 = $aHdrItemOrder EndIf EndIf ; Register WM_NOTIFY message handler ; To handle NM_CUSTOMDRAW notifications ; And to check when ListView receives/loses focus GUIRegisterMsg( $WM_NOTIFY, "WM_NOTIFY" ) ; Register WM_ACTIVATE message handler ; If GUI loses focus selected listview items are drawn with a button face background color. ; To check when GUI receives/loses focus ; When GUI receives focus selected items are redrawn with the dark blue background color. GUIRegisterMsg( $WM_ACTIVATE, "WM_ACTIVATE" ) ; Detection of received focus is faster through the WM_ACTIVATE message than directly ; through the listview. This provides a faster and smoother redraw of selected items. ; Show GUI GUISetState( @SW_SHOW ) ; Message loop While 1 Switch GUIGetMsg() ; Two Case sections to handle column 0 issue Case $GUI_EVENT_PRIMARYDOWN Local $aPos = MouseGetPos() If $aHdrPos[0] <= $aPos[0] And $aPos[0] <= $aHdrPos[2] And _ $aHdrPos[1] <= $aPos[1] And $aPos[1] <= $aHdrPos[3] Then ; Mouse click in header ; Register callback function to subclass ListView Local $pListViewProc = DllCallbackGetPtr( DllCallbackRegister( "ListViewProc", "lresult", "hwnd;uint;wparam;lparam;uint_ptr;dword_ptr" ) ) _WinAPI_SetWindowSubclass( $hListView, $pListViewProc, 9999, 0 ) ; $iSubclassId = 9999, $pData = 0 $bMouseClickHeader = True EndIf Case $GUI_EVENT_PRIMARYUP If $bMouseClickHeader Then ; Remove callback function _WinAPI_RemoveWindowSubclass( $hListView, $pListViewProc, 9999 ) $bMouseClickHeader = False EndIf Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd ; Save Header item order if changed $aHdrItemOrder = _GUICtrlHeader_GetOrderArray( $hHeader ) For $i = 1 To $aHdrItemOrder[0] If $aHdrItemOrder[$i] <> $aHdrItemOrder0[$i] Then ExitLoop Next If $i < $aHdrItemOrder[0] Then $sOrder = $aHdrItemOrder[0] For $i = 1 To $aHdrItemOrder[0] $sOrder &= "|" & $aHdrItemOrder[$i] Next Local $hHdrIni = FileOpen( "HdrItemOrder.ini", 2 ) ; 2 = $FO_OVERWRITE FileWriteLine( $hHdrIni, $sOrder ) FileClose( $hHdrIni ) EndIf ; Cleanup GUIDelete() EndFunc ; ListViewProc callback function to handle column 0 issue Func ListViewProc( $hWnd, $iMsg, $wParam, $lParam, $iSubclassId, $pData ) If $iMsg <> $WM_NOTIFY Then Return DllCall( "comctl32.dll", "lresult", "DefSubclassProc", "hwnd", $hWnd, "uint", $iMsg, "wparam", $wParam, "lparam", $lParam )[0] If HWnd( DllStructGetData( DllStructCreate( $tagNMHDR, $lParam ), "hWndFrom" ) ) <> $hHeader Then Return DllCall( "comctl32.dll", "lresult", "DefSubclassProc", "hwnd", $hWnd, "uint", $iMsg, "wparam", $wParam, "lparam", $lParam )[0] #forceref $iSubclassId, $pData Switch DllStructGetData( DllStructCreate( $tagNMHDR, $lParam ), "Code" ) Case $HDN_ENDDRAG ; A Header item has been dragged with the mouse $fHeaderOrderOfItem0 = -1 ; Recalculate order of Header item with index 0 EndSwitch ; Call next function in subclass chain Return DllCall( "comctl32.dll", "lresult", "DefSubclassProc", "hwnd", $hWnd, "uint", $iMsg, "wparam", $wParam, "lparam", $lParam )[0] EndFunc ; WM_NOTIFY message handler Func WM_NOTIFY( $hWnd, $iMsg, $wParam, $lParam ) #forceref $hWnd, $iMsg, $wParam Local Static $iLvIndex, $iArrayIdx, $iSelected, $tRect = DllStructCreate( $tagRECT ), $pRect = DllStructGetPtr( $tRect ), $hDC Local $tNMHDR = DllStructCreate( $tagNMHDR, $lParam ) Local $hWndFrom = HWnd( DllStructGetData( $tNMHDR, "hWndFrom" ) ) Local $iCode = DllStructGetData( $tNMHDR, "Code" ) Switch $hWndFrom Case $hListView Switch $iCode Case $NM_CUSTOMDRAW Local $tNMLVCustomDraw = DllStructCreate( $tagNMLVCUSTOMDRAW, $lParam ) Local $dwDrawStage = DllStructGetData( $tNMLVCustomDraw, "dwDrawStage" ) Switch $dwDrawStage ; Specifies the drawing stage ; Stage 1 Case $CDDS_PREPAINT ; Before the paint cycle begins If $fHeaderOrderOfItem0 = -1 Then ; Handle column 0 issue ; Calculate order of Header item with index 0 Local $tHdrItem = DllStructCreate( $tagHDITEM ) DllStructSetData( $tHdrItem, "Mask", $HDI_ORDER ) DllCall( "user32.dll", "lresult", "SendMessageW", "hwnd", $hHeader, "uint", $HDM_GETITEMW, "wparam", 0, "struct*", $tHdrItem ) $fHeaderOrderOfItem0 = DllStructGetData( $tHdrItem, "Order" ) EndIf $hDC = DllStructGetData( $tNMLVCustomDraw, "hDC" ) ; Device context _WinAPI_SelectObject( $hDC, $hLVfont ) ; Set original font _WinAPI_SetBkMode( $hDC, $TRANSPARENT ) ; Transparent background Return $CDRF_NOTIFYITEMDRAW+$CDRF_NEWFONT ; Notify the parent window before an item is painted ; Stage 2 Case $CDDS_ITEMPREPAINT ; Before an item is painted $iLvIndex = DllStructGetData( $tNMLVCustomDraw, "dwItemSpec" ) ; Item index $iArrayIdx = DllStructGetData( $tNMLVCustomDraw, "lItemlParam" ) ; Array index $iSelected = GUICtrlSendMsg( $idListView, $LVM_GETITEMSTATE, $iLvIndex, $LVIS_SELECTED ) ; Item state Return $CDRF_NOTIFYSUBITEMDRAW ; Notify the parent window before a subitem is painted ; Stage 3 Case BitOR( $CDDS_ITEMPREPAINT, $CDDS_SUBITEM ) ; Before a subitem is painted: Default painting of checkbox, image, icon Return $CDRF_NOTIFYPOSTPAINT ; Notify the parent window after a subitem is painted ; Stage 4 Case BitOR( $CDDS_ITEMPOSTPAINT, $CDDS_SUBITEM ) ; After a subitem has been painted: Custom painting of text lines Local $iSubItem = DllStructGetData( $tNMLVCustomDraw, "iSubItem" ) ; Subitem index ; Subitem rectangle DllStructSetData( $tRect, "Top", $iSubItem ) DllStructSetData( $tRect, "Left", $iSubItem ? $LVIR_BOUNDS : $LVIR_LABEL ) GUICtrlSendMsg( $idListView, $LVM_GETSUBITEMRECT, $iLvIndex, $pRect ) ; Subitem text color DllCall( "gdi32.dll", "int", "SetTextColor", "handle", $hDC, "int", ( $iSelected And $fListViewHasFocus ) ? 0xFFFFFF : 0x000000 ) ; _WinAPI_SetTextColor ; Custom painting of first text line in subitem If $fHeaderOrderOfItem0 Then ; Handle column 0 issue ; Handle column 0 issue due to column 0 and other columns have different left margins RepaintFirstTextLineCol0( $idListView, $iLvIndex, $iSubItem, $iSelected, $fListViewHasFocus, $hDC, $tRect ) Else RepaintFirstTextLine( $idListView, $iLvIndex, $iSubItem, $iSelected, $fListViewHasFocus, $hDC, $tRect ) EndIf ; Custom painting of second text line in subitem If Not $aLines[$iArrayIdx][$iSubItem] Then Return $CDRF_NEWFONT DllStructSetData( $tRect, "Top", DllStructGetData( $tRect, "Top" ) + 12 ) ; Top margin DllCall( "user32.dll", "int", "DrawTextW", "handle", $hDC, "wstr", $aLines[$iArrayIdx][$iSubItem], "int", -1, "struct*", $tRect, "uint", $DT_WORD_ELLIPSIS ) ; _WinAPI_DrawText Return $CDRF_NEWFONT ; $CDRF_NEWFONT must be returned after changing font or colors EndSwitch Case $NM_KILLFOCUS If $fListViewHasFocus Then GUICtrlSendMsg( $idListView, $LVM_REDRAWITEMS, 0, $iItems - 1 ) $fListViewHasFocus = 0 EndIf Case $NM_SETFOCUS If Not $fListViewHasFocus Then _ GUICtrlSendMsg( $idListView, $LVM_REDRAWITEMS, 0, $iItems - 1 ) $fListViewHasFocus = 2 EndSwitch EndSwitch Return $GUI_RUNDEFMSG EndFunc ; WM_ACTIVATE message handler Func WM_ACTIVATE( $hWnd, $iMsg, $wParam, $lParam ) #forceref $iMsg, $lParam If $hWnd = $hGui Then _ $fListViewHasFocus = BitAND( $wParam, 0xFFFF ) ? 1 : 0 Return $GUI_RUNDEFMSG EndFunc I have obviously forgotten to update my signature for a long time. I will go through the examples and update the signature in the weekend. Thank you. For everybody: Always nice to get feedback. Thank you.
    1 point
  15. For our imaging script, I wrote a function to do just what you are trying to do. The function that I wrote pulls the images off of a server share, and copy them to "backgrounds" directory. This function is part of a much larger script, so you may need to edit them to do what you need. Func _EnableWin7CustomLogonBackground($sUserName, $sPassword, $sServerShare) ;Copies the Logon UI backgrounds from a server share and turn the setting on in the registry. $sUserName = StringStripWS($sUserName, 8) If Not StringInStr($sUserName, "AD\") Then $sUserName = "AD\" & StringStripWS($sUserName, 8) Local Const $sOobeDir = @SystemDir & "\oobe" Local Const $sBackgroundsDir = $sOobeDir & "\info\backgrounds" If Not FileExists($sOobeDir) Then Return SetError(2, 0, 0) DriveMapAdd("", $sServerShare, 0, $sUserName, $sPassword) If @error Then Return SetError(Number("100" & @error), @extended, 0) If Not DirCopy($sServerShare, $sBackgroundsDir, 1) Then Return SetError(2, 0, 0) Local $s64Bit = "" If @OSArch = "X64" Then $s64Bit = "64" ;~ If Not RegWrite("HKEY_LOCAL_MACHINE" & $s64Bit & "\Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background", "OEMBackground", "REG_DWORD", 1) Then Return SetError(4, @error, 0) ;Use Logon UI Reg Key. If Not RegWrite("HKEY_LOCAL_MACHINE" & $s64Bit & "\Software\Policies\Microsoft\Windows\System", "UseOEMBackground", "REG_DWORD", 1) Then Return SetError(4, @error, 0) ;Use Policy Reg Key. Return 1 EndFunc ;==>_EnableWin7CustomLogonBackground Hopefully this is helpful. Adam
    1 point
  16. _ChooseColor in <Misc.au3> is based on ChooseColor function in comdlg32.dll. ChooseColor is depending on a CHOOSECOLOR structure. The Flags and lpfnHook fields in this structure can be used to create a hook function for the ChooseColor window. This hook function can be used to simulate a modeless ChooseColor window. There are two interesting features of a hook funtion. It allows you to receive windows messages even if the ChooseColor dialog is a modal window. And it makes it possible to determine which messages are to be forwarded to the ChooseColor dialog, and which are not to be forwarded. The hook function receives Windows messages before the ChooseColor dialog. If the hook function returns 0, the messages are forwarded to the ChooseColor dialog. If the hook function returns 1 (not 0), the messages are not forwarded to the ChooseColor dialog. Messages that are not forwarded to ChooseColor should be processed by the hook function. When the OK button in ChooseColor dialog is clicked, this click is handled by the hook function and not forwarded to the ChooseColor dialog. This means, that the ChooseColor window does not close. In the hook function the selected color is calculated and send to the AutoIt window with _SendMessage. In the zip below the main AutoIt GUI, ChooseColor.au3, contains a button. When you click this button another script, ModelessCC.au3, is started with ShellExecute. ModelessCC.au3 opens the ChooseColor dialog. There is no message loop in ModelessCC.au3. But because ChooseColor is modal, ModelessCC.au3 will not exit until ChooseColor is closed. The hook function is also running in ModelessCC.au3. The hook function is running even if ChooseColor is modal. The function catches the OK button clicks in ChooseColor and sends the color to the main AutoIt GUI with _SendMessage. The hook function and ChooseColorEx is coded in MiscEx.au3. The main AutoIt GUI contains 12 labels. Click a label, select a color in the ChooseColor dialog, click the OK button, and the background color of the label will be set to the selected color. You can select colors for all 12 labels without closing the ChooseColor dialog. Tested with AutoIt 3.3.10 on Windows 7 64 bit and Windows XP 32 bit. ModelessChooseColor.7z
    1 point
  17. I'm still curious how psexec works (if it's not by this same procedure). I wish Sysinternals would release source for their apps. So much to learn...
    1 point
×
×
  • Create New...