Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 06/25/2023 in all areas

  1. Automate the change of the (current) user account picture was a script that I was missing, but I was sure to find an easy command line, like a simple powershell. It was not the case, I found only methods to change it in Active Directory environments, and my goal was to change the account picture also in freshly installed win 10/11 non domain OSes, and it works also in domain machines. The focus is to take care of every aspect of the process. The code: #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Icon=Icone\angryRabbit.ico #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** ;UAP ;User Account Picture ;()NSC 2023 ;notes ; only way to access 64-bit node in a 32-bit compiled script is using HKLM64 ;Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AccountPicture\Users ;main inspiration ;https://social.msdn.microsoft.com/Forums/sqlserver/en-US/3f50b25a-4c47-4bc8-959e-1108419288a7/how-to-set-specific-users-account-picture-from-cmd?forum=scripting ;PSexec to use as System '-s' switch ;https://learn.microsoft.com/it-it/sysinternals/downloads/psexec ;image processing ;https://imagemagick.org/index.php ;https://imagemagick.org/script/command-line-processing.php ;needed VCredist ;https://learn.microsoft.com/it-it/cpp/windows/latest-supported-vc-redist?view=msvc-170 ;https://aka.ms/vs/17/release/vc_redist.x64.exe ;permissions SETACL ;https://helgeklein.com/setacl/ ;https://www.autoitscript.com/forum/topic/162656-change-registry-key-permissions/?do=findComment&comment=1182956 ;interesting but not used (AD related) ;https://woshub.com/how-to-set-windows-user-account-picture-from-active-directory/ #RequireAdmin #include <Security.au3> #include <Array.au3> #include <File.au3> #include <String.au3> #include <_Gollog.au3> $mygui = "UAP - NSC 2023" gollog_ini($mygui, 600, 300, 200, 200, "0x050980", "0xf2dcc3", "consolas") ;f2dcc3 Global $tempfolder = "c:\temp", $ver = "V.1.0" Global $onlyexe4conversion = "magick.exe", $exe4conversion = $tempfolder & "\" & $onlyexe4conversion Global $onlyexe4regperm = "setacl.exe", $exe4regperm = $tempfolder & "\" & $onlyexe4regperm Global $onlyexe4PsExec = "psexec64.exe", $exe4PsExec = $tempfolder & "\" & $onlyexe4PsExec Global $vcredist = $tempfolder & "\" & "VC_redist.x64.exe" Global $registrypath = "hklm64\SOFTWARE\Microsoft\Windows\CurrentVersion\AccountPicture\Users\" Global $registrypath4SETACL = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AccountPicture\Users\" Global $aSizes[11] = ["32x32", "40x40", "48x48", "64x64", "96x96", "192x192", "208x208", "240x240", "424x424", "448x448", "1080x1080"] Gollog("START UAP " & $ver) Global $sConsoleUser = _GetConsoleUser() Gollog("Console User: " & $sConsoleUser & @CRLF) Global $aUserProfile = _GetProfile($sConsoleUser) Gollog("Console User Path: " & $aUserProfile[1][1] & @CRLF) Global $folder4accountPictures = $aUserProfile[1][1] & "\" & "UAP" ;_ArrayDisplay($aUserProfile, "current USER") Global $aexpprof = _StringExplode($aUserProfile[1][2], "\") Global $CUreg = $aexpprof[UBound($aexpprof) - 1] Gollog("current user SID: " & $CUreg & @CRLF) ;TEST all users Gollog("enumerating all users:") Global $allUserProfiles = _GetProfile() For $i = 1 To UBound($allUserProfiles) - 1 Gollog($allUserProfiles[$i][0] & " " & $allUserProfiles[$i][2]) Next ;_ArrayDisplay($allUserProfiles, "all USERS") createFolder4userPictures() TempCreate() SetRegPermissions() VcRedist() GenPicS() Gollog("END UAP") Func GenPicS() ;image prepare Gollog("picking image for avatar") Local $sourceimg = FileOpenDialog("Select Image for your User Profile", @UserProfileDir & "\" & "downloads", "Images (*.png;*.jpg;*.jpeg;*.gif;*.bmp)", 1) Local $sDrive = "", $sDir = "", $sFileName = "", $sExtension = "" Local $aPathSplit = _PathSplit($sourceimg, $sDrive, $sDir, $sFileName, $sExtension) ;registry prepare If RegDelete($registrypath & $CUreg) Then Gollog("regdelete ok " & @CRLF) Gollog($registrypath & $CUreg & @CRLF) Else Gollog("regdelete error " & @error & @CRLF) Gollog($registrypath & $CUreg & @CRLF) EndIf If RegWrite($registrypath & $CUreg) Then Gollog("regwrite root ok " & @CRLF) Else Gollog("regwrite root error " & @error & @CRLF) EndIf For $i = 0 To UBound($aSizes) - 1 ;image conversion ShellExecuteWait($exe4conversion, $sourceimg & " -resize " & $aSizes[$i] & " " & $folder4accountPictures & "\" & $sFileName & "_" & $aSizes[$i] & $sExtension) ;registry write Local $apartsize = _StringExplode($aSizes[$i], "x") If RegWrite($registrypath & $CUreg, "Image" & $apartsize[0], "REG_SZ", $folder4accountPictures & "\" & $sFileName & "_" & $aSizes[$i] & $sExtension) Then Gollog("regewrite image ok " & $aSizes[$i] & @CRLF) Gollog($registrypath & $CUreg & " Image" & $apartsize[0] & " REG_SZ " & $folder4accountPictures & "\" & $sFileName & "_" & $aSizes[$i] & $sExtension) Else Gollog("regwrite image error " & @error & @CRLF) Gollog($registrypath & $CUreg & " Image" & $apartsize[0] & " REG_SZ " & $folder4accountPictures & "\" & $sFileName & "_" & $aSizes[$i] & $sExtension) EndIf Next EndFunc ;==>GenPicS Func VcRedist() Gollog("installing Microsoft Visual C++ Redistributable ") ShellExecuteWait($vcredist, "/install /passive /norestart") EndFunc ;==>VcRedist Func SetRegPermissions() Gollog("creating file to set registry permissions") ;writing bat file Local $batfile = $tempfolder & "\" & "UAPsetacl.bat" If FileExists($batfile) Then FileDelete($batfile) gollog("deleted old " & $batfile) EndIf Local $hFileOpen = FileOpen($batfile, $FO_APPEND) If $hFileOpen = -1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred whilst writing the UAPsetacl.bat file", 3) GOLLOG("An error occurred whilst writing the UAPsetacl.bat file") Exit EndIf FileWriteLine($hFileOpen, 'c:\temp\setacl.exe -on "' & $registrypath4SETACL & $CUreg & '" -ot reg -actn ace -ace "n:Administrators;p:full"') FileClose($hFileOpen) Gollog("set registry permissions") ;launch permission set on registry ShellExecuteWait($exe4PsExec, " -s -accepteula " & $batfile) EndFunc ;==>SetRegPermissions Func TempCreate() Gollog("deploying necessary temp files") If Not FileExists($tempfolder) Then DirCreate($tempfolder) FileInstall("C:\nsc_TEST\resources\imagemagick\magick.exe", $exe4conversion, 1) FileInstall("C:\nsc_TEST\resources\SetACL\64 bit\setacl.exe", $exe4regperm, 1) FileInstall("C:\NSC_test\resources\PSExec\PsExec64.exe", $exe4PsExec, 1) FileInstall("C:\nsc_TEST\resources\VCredist\VC_redist.x64.exe", $vcredist, 1) EndFunc ;==>TempCreate ;Create folder for user pictures - cleaning pre existing Func createFolder4userPictures() Gollog("creating folder for new avatar pictures") If FileExists($folder4accountPictures & "\") Then DirRemove($folder4accountPictures, 1) EndIf DirCreate($folder4accountPictures) EndFunc ;==>createFolder4userPictures ;Use WMI query to get user logged onto console Func _GetConsoleUser() Local $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!//.") Local $colUsers, $objUser Local $strAccount $colUsers = $objWMIService.InstancesOf("Win32_ComputerSystem") For $objUser In $colUsers $strAccount = $objUser.UserName Next If $strAccount <> "" Then Return $strAccount Else Return (1) EndIf EndFunc ;==>_GetConsoleUser ; #FUNCTION# ==================================================================================================================================== ; Name...........: _GetProfile ; Description ...: Determine each user's Profile folder, the user's SID and if the profile is loaded to the registry ; Syntax.........: _GetProfile([$sAccount, $sComputer]) ; Parameters ....: $sAccount - User account name, defaults to all users ; $sComputer - Computer name, the local computer is default ; Requirement(s).: Service 'RemoteRegistry' running on the target computer ; When the target computer is the local computer, the 'RemoteRegistry' service isn't required ; Return values .: An array containing the path to each user's profile folder, the user's SID ; The array returned is two-dimensional and is made up as follows: ; $array[0][0] = Number of profiles ; $array[1][0] = 1st user name ; $array[1][1] = Path to 1st user profile ; $array[1][2] = 1st user registry hive ; $array[1][3] = 1 if 1st user profile is loaded to the registry, 0 if not ; $array[2][0] = 2nd user name ; $array[2][1] = Path to 2nd user profile ; $array[2][2] = 2nd user registry hive ; $array[2][3] = 1 if 2nd user profile is loaded to the registry, 0 if not ; ... ; $array[n][0] = nth user name ; $array[n][1] = Path to nth user profile ; $array[n][2] = nth user registry hive ; $array[n][3] = 1 if nth user profile is loaded to the registry, 0 if not ; Author ........: engine ; Modified.......: AdamUL ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; _GetProfile("Default User") to get Default User's profile data on the local computer ; =============================================================================================================================================== Func _GetProfile($sAccount = "", $sComputer = @ComputerName) Local $avArray[1][4], $sDefaultUser, $sEnv Local Const $sProfileListKey = "\\" & $sComputer & "\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" Local Const $sRootKey = "\\" & $sComputer & "\HKEY_USERS\" Local Const $sDefaultUser1 = RegRead($sProfileListKey, "DefaultUserProfile") Local Const $iDefaultUser1Error = @error Local Const $sDefaultUser2 = RegRead($sProfileListKey, "Default") Local Const $iDefaultUser2Error = @error If $iDefaultUser1Error And $iDefaultUser2Error Then $avArray[0][0] = 0 Return $avArray EndIf If $iDefaultUser1Error Then $sDefaultUser = "Default" Else $sDefaultUser = $sDefaultUser1 EndIf If $sAccount = "" Or $sAccount = $sDefaultUser Then Local $iInstance, $sSID While 1 $iInstance += 1 $sSID = RegEnumKey($sProfileListKey, $iInstance) If @error Then ExitLoop If StringLen($sSID) > 8 Then ProfileAdd($avArray, $sSID, $sProfileListKey, $sRootKey) WEnd Local $u = UBound($avArray), $iSum For $k = 1 To $u - 1 $iSum += $avArray[$k][3] Next ReDim $avArray[$u + 1][4] $avArray[$u][0] = $sDefaultUser $avArray[$u][1] = RegRead($sProfileListKey, "ProfilesDirectory") & "\" & $sDefaultUser If $iSum = 0 Then $avArray[$u][2] = "\\" & $sComputer & "\HKEY_CURRENT_USER" $avArray[$u][3] = 1 Else Local $avDomain, $iN = 998, $sDSID, $avDU $avDomain = _Security__LookupAccountName($sComputer, $sComputer) Do $iN += 1 $sDSID = $avDomain[0] & "-" & $iN $avDU = _Security__LookupAccountSid($sDSID, $sComputer) Until $avDU = 0 $avArray[$u][2] = $sRootKey & $sDSID $avArray[$u][3] = 0 EndIf If $sAccount = $sDefaultUser Then Local $avNew[2][4] = [["", "", "", ""], [$avArray[$u][0], $avArray[$u][1], $avArray[$u][2], $avArray[$u][3]]] $avArray = $avNew EndIf Else Local $avSID = _Security__LookupAccountName($sAccount, $sComputer) If $avSID = 0 Then $avArray[0][0] = 0 Return $avArray Else ProfileAdd($avArray, $avSID[0], $sProfileListKey, $sRootKey) EndIf EndIf $avArray[0][0] = UBound($avArray) - 1 For $j = 1 To $avArray[0][0] $sEnv = StringRegExp($avArray[$j][1], "\x25\S{1,128}\x25", 1) If Not @error Then $avArray[$j][1] = StringReplace($avArray[$j][1], $sEnv[0], EnvGet(StringReplace($sEnv[0], "%", ""))) Next Return $avArray EndFunc ;==>_GetProfile ; #INTERNAL_USE_ONLY#============================================================================================================================ ; Name...........: ProfileAdd ; Description ...: Add profile data to an array that will be returned by _GetProfile function ; Syntax.........: ProfileAdd($avArray, $sSID, $sProfileListKey, $sRootKey) ; Parameters ....: $avArray - Array ; $sSID - Account SID ; $sProfileListKey - Constant defined inside _GetProfile function ; $sRootKey - Constant defined inside _GetProfile function ; Requirement(s).: ; Return values .: ; Author ........: engine ; Modified.......: AdamUL ; Remarks .......: For internal use only ; Related .......: ; Link ..........; ; Example .......; ; =============================================================================================================================================== Func ProfileAdd(ByRef $avArray, $sSID, Const $sProfileListKey, Const $sRootKey) Local $sPath, $i Local $asSplit = Split_sKey("\" & $sProfileListKey) Local $avUser = _Security__LookupAccountSid($sSID, $asSplit[0]) If Not @error And $avUser <> 0 Then If $avUser[2] = 1 Then $sPath = RegRead($sProfileListKey & "\" & $sSID, "ProfileImagePath") If Not @error Then $i = UBound($avArray) ReDim $avArray[$i + 1][4] $avArray[$i][0] = $avUser[0] $avArray[$i][1] = $sPath $avArray[$i][2] = $sRootKey & $sSID RegEnumKey($sRootKey & $sSID, 1) If @error Then $avArray[$i][3] = 0 Else $avArray[$i][3] = 1 EndIf EndIf EndIf EndIf EndFunc ;==>ProfileAdd ; #INTERNAL_USE_ONLY#============================================================================================================================ ; Name...........: Split_sKey ; Description ...: Splits $sKey between computername, username and keyname ; Syntax.........: Split_sKey($sKey) ; Parameters ....: $sKey - Reg function main key ; Requirement(s).: ; Return values .: ; Author ........: engine ; Modified.......: ; Remarks .......: For internal use only ; Related .......: ; Link ..........; ; Example .......; ; =============================================================================================================================================== Func Split_sKey($sKey) Local $asArray[3] If StringInStr($sKey, "\\\") = 1 Then Local $asComputer = StringRegExp($sKey, "\\\\\\[^\\]*\\", 1) If Not @error Then $asArray[0] = StringTrimRight(StringTrimLeft($asComputer[0], 3), 1) $sKey = StringReplace($sKey, $asComputer[0], "\", 1) If Not StringInStr($sKey, "\\") = 1 Then $sKey = StringTrimLeft($sKey, 1) EndIf EndIf If $asArray[0] = "" Then $asArray[0] = @ComputerName If StringInStr($sKey, "\\") = 1 And Not StringInStr($sKey, "\\\") = 1 Then Local $asUser = StringRegExp($sKey, "\\\\[^\\]*\\", 1) If Not @error Then $asArray[1] = StringTrimRight(StringTrimLeft($asUser[0], 2), 1) $sKey = StringReplace($sKey, $asUser[0], "", 1) EndIf EndIf If Not (StringInStr($sKey, "\") = 1 Or StringInStr($sKey, "\", 0, -1) = StringLen($sKey) Or StringInStr($sKey, "\\")) Then $asArray[2] = $sKey EndIf Return $asArray EndFunc ;==>Split_sKey 3+1 external executables are needed, look at notes at the top of che code. The _gollog udf is here. The abstract is this : it determines the current user SID it gives control to the admin user to the right registry entries, because they are changeable only by "system" account") it creates the needed pictures and write down to the registry the correct keys. Research on these topics was made in this thread.
    1 point
  2. Jos

    Ternary line for GUI loop?

    Hardly anybody actually reads the whole page ever.... Only a few open it.
    1 point
  3. MattyD

    Midi UDF

    Hi folks, Quick announcement about the band-aid release for 1.6. V1.6.1: Script breaking: - A streaming device handle must be explicitly be requested with _midi_OpenOutput for sequence playback. (new parameter- req. for experimental functions) Non-script breaking: - Output devices are no longer opened as streaming devices by default. (reverted behaviour which fixes a multitude of functions) - Fixed cases where _midi_GetOutputName & _midi_GetInputName were returning False instead of a blank string on failure.
    1 point
  4. Luigi

    AutoUpdate

    Greetings... Yes... I know... Have a lot fo autoupdate's scripts... But I made one with two special options, not writed yet... self-update (ok) self install from any location (ok) run only in work folder (ok) check self version from repository (not ready) update all dependents files and check md5 file and/or version (not ready) work with remote drive (mount/unmount) (not ready) Tips... Create a folder: C:\Repository Save the scripts in folder C:\Repository Compile app.au3 Run from C:\Repository Close app.exe Copy to another folder... Run app.exe Recompile app.exe again... Re-run app.exe again... The script always run from C:\ProgramData\Luigi\app.exe... with the last version... AutoUpdate.au3 app.au3
    1 point
  5. This is a continuation of Custom drawn TreeViews and ListViews. However, only with respect to listviews. The crucial difference between the new and the old code is that the new code is a complete UDF and therefore much easier to use. Because the UDF is about colors and fonts in listview items and subitems, it's only for listviews in Details or Report view. Main features The UDF supports the following main features. Colors and fonts: 1 Single items/subitems Back colors Fore colors Fonts and styles 2 Colors/fonts for entire columns 3 Alternating colors (entire listview) Alternating colors for rows, columns or both Both default and alternating color can be set Number of rows/columns between color change can be set 4 Custom default colors/font instead of standard default colors/font Custom default back and fore colors can be set for Normal listview items (instead of white and black) Selected listview items (instead of dark blue and white) Unfocused selected items (instead of button face and black) 5 Colors for selected listview items Back and fore colors for selected items when listview has focus Back and fore colors for selected items when listview has not focus Features 1, 2 and 3 cannot be mixed together. 4 and 5 can be mixed with the previous features. 5 extends the functionality of the previous features by adding colors to selected items. 5 cannot be used alone. Listviews: Multiple listviews Native and non-native listviews Native and non-native listview items The UDF can be used with existing listviews WM_NOTIFY message handlers: WM_NOTIFY message handlers can be used completely as usual The UDF can be used with existing WM_NOTIFY message handlers Colors and fonts for single listview items/subitems are stored in an array. The index in this array for a given listview item is stored in ItemParam. Except for this usage of ItemParam nothing in the UDF assumes that listviews or items/subitems are created in a certain way, or that any WM_NOTIFY handlers exists or are designed in a certain way. It should be easy to use the UDF with existing listviews with or without a WM_NOTIFY message handler or other message handlers. WM_NOTIFY message handlers Colors and fonts in listviews are implemented through custom draw notifications in the form of WM_NOTIFY messages. A WM_NOTIFY message handler is needed to implement colors/fonts. If a listview is included in a GUI and a little more than just very basic functionality is wanted, another WM_NOTIFY handler is soon needed to implement this functionality. To register a WM_NOTIFY handler you use the function GUIRegisterMsg. This function can register only one message handler at a time for the same message type. The result of code like this is that only WM_NOTIFY2 message handler is working: GUIRegisterMsg( $WM_NOTIFY, "WM_NOTIFY1" ) ; Register WM_NOTIFY1 GUIRegisterMsg( $WM_NOTIFY, "WM_NOTIFY2" ) ; Register WM_NOTIFY2 (unregisters WM_NOTIFY1) This makes it difficult to implement colors/fonts in a UDF, if you at the same time want to implement advanced functionality in your own code. A solution is to register the WM_NOTIFY message handler, that takes care of custom draw notifications, in a different way. This can be done by a technique called subclassing, which is implemented through the four functions SetWindowSubclass, GetWindowSubclass, RemoveWindowSubclass and DefSubclassProc (coded in WinAPIShellEx.au3). Subclassing Subclassing a window (or control) means to create a message handler for the window, that will receive messages to the window before the original message handler for the window. This section is information on the implementation of a WM_NOTIFY message handler through subclassing: The UDF The UDF is implemented in UDFs\ListViewColorsFonts.au3. This is a list of the most important functions copied from the UDF (around line 200): ; Initiating and exiting ; ---------------------- ; ListViewColorsFonts_Init ; ListViewColorsFonts_Exit ; ; Set colors/fonts for items/subitems ; ----------------------------------- ; ListViewColorsFonts_SetItemColors ; ListViewColorsFonts_SetItemFonts ; ListViewColorsFonts_SetItemColorsFonts ; ; Set colors/fonts for entire listview ; ------------------------------------ ; ListViewColorsFonts_SetColumnColorsFonts ; ListViewColorsFonts_SetAlternatingColors ; ListViewColorsFonts_SetDefaultColorsFonts ; ; Maintenance functions ; --------------------- ; ListViewColorsFonts_Redraw Some of the functions in the complete list in the file are not coded in this version. To use the UDF you first calls ListViewColorsFonts_Init which stores information about the listview and the parent window, and creates the subclass that takes care of the actual drawing of the colors and fonts. Then you call one or more of the ListViewColorsFonts_Set-functions to define the colors and fonts. Depending on the functions you might also need to call ListViewColorsFonts_Redraw. And that's all. Finally you can call ListViewColorsFonts_Exit to remove the subclass before the script exits. If you don't call ListViewColorsFonts_Exit it's called automatically by the UDF. This is the syntax for ListViewColorsFonts_Init and the information about $fColorsFonts flag also copied from ListViewColorsFonts.au3: ; ListViewColorsFonts_Init( $idListView, $fColorsFonts = 7, $iAddRows = 100, $bNative = False ) ; $idListView - Listview control ID or handle ; $fColorsFonts - Specifies options for usage of colors and fonts in the listview. Add required options together. ; 1: Back colors for items/subitems ; Can not be specified separately in this version ; 2: Fore colors for items/subitems ; Can not be specified separately in this version ; 4: Fonts and styles for items/subitems ; Can not be specified separately in this version ; 7: Back and fore colors, fonts and styles ; Flags 1/2/4 are combined in flag 7 in this version ; ; 8: Colors/fonts for entire columns ; ; 16: Alternating row colors (for entire listview) ; 32: Alternating column colors (for entire listview) ; ; 64: Custom default colors and font (for entire listview) ; Custom default back and fore colors can be set for ; - Normal listview items (instead of white and black) ; - Selected listview items (instead of dark blue and white) ; - Unfocused selected listview items (instead of button face and black) ; ; 128: Colors for selected items when listview has focus ; 256: Colors for selected items when listview has not focus The limitations with respect to flags 1, 2 and 4 in this version is only a matter of optimizations. It has nothing to do with features. Drawing of selected items is largely controlled by Windows. A lot of extra code is needed to implement custom colors for selected items through flags 128 and 256. For $fColorsFonts flag is further noted that: ; - Flags 1/2/4 can be combined in a total of seven different ways ; - Flags 1/2/4 (items/subitems), flag 8 (columns) and flags 16/32 (listview) cannot be combined ; - Flag 64 is used to replace the standard default colors/font by custom default colors/font ; Flag 64 can be used alone or in combination with flags 1-32 ; Custom default colors/font must be set before all other colors/fonts ; Flag 64 leads to some restrictions on the features for items/subitems (flags 1/2/4) ; - Flags 128/256 extends the functionality of flags 1-64 by adding colors to selected items ; Flags 128/256 cannot be used alone An array $aListViewColorsFontsInfo is used to store information about the listview, the parent window and the usage of colors/fonts in the listview. For flags 1/2/4 about single items/subitems another array $aListViewColorsFonts is used to store the colors and fonts for the items and subitems. The number of columns in this array depends on whether the flags 128/256 are set or not. The first 160 lines in the UDF contains information about these arrays. For flags 1/2/4 ItemParam field in the listview is used to store the zero based row index in $aListViewColorsFonts for a given listview item. For native listview items created with GUICtrlCreateListViewItem the existing value of ItemParam (control ID) is used as index in an intermediate array $aListViewColorsFonts_Index, and $aListViewColorsFonts_Index holds the index in $aListViewColorsFonts stored as index+1. For non-native listview items the index in $aListViewColorsFonts is stored in ItemParam as -index-20. For non-native listview items an existing value of ItemParam is overwritten. The best way to add colors and fonts to listviews is to put each listview in its own child window. The child window should not contain any other controls, and it should have the same size as the listview. However, this is not a requirement. See the UDF for documentation of the other functions. The implementation of the functions starts in line 230 and onwards. The UDF also contains a group of internal functions. Among other the subclass callback functions to draw the colors and fonts in response to NM_CUSTOMDRAW notifications from the listview. So far the UDF contains seven callback functions which starts around line 2100 and runs over the next 1300 lines nearly to the bottom of the file. The code This section is about some code details related partly to the subclass callback functions and partly to drawing of selected items. Subclass callback functions: Drawing of selected items: In the current version of the UDF the callback function that is implemented to draw single items/subitems ($fColorsFonts = 1/2/4) is the function that can handle all features ($fColorsFonts = 1+2+4 = 7). If only a part of the features is needed, it's possible to create smaller and faster functions, which only implements this part of the features. These functions (six functions in total) are postponed to next version. Features A few comments on the features. The main features in terms of colors and fonts are (a repeat of the list in top of post): 1 Single items/subitems 2 Colors/fonts for entire columns 3 Alternating colors (entire listview) 4 Custom default colors/font instead of standard default colors/font 5 Colors for selected listview items 1, 2 and 3 are features for different kind of elements in the listview and cannot be mixed together. 4 can be used either as an independent feature or mixed with 1, 2 or 3. 5 cannot be used as an independent feature but can only be used together with 1, 2, 3 or 4. 5 extends the functionality of these features by adding colors to selected items. When features 1, 4 and 5 are mixed together, it may look as shown in the following illustrations (screen dumps of examples 3.1 and 4.1 in folder \Examples\5) Selected items\). The first illustration shows how it looks when colors for single items/subitems are mixed with colors for selected items: In the upper picture rows 3-6 are provided with back and fore colors. All subitems in row 3 and 4. Only a few subitems in row 5 and 6. The rows are normal (unselected) rows. In the middle picture rows 2-7 are selected and the listview has focus. Rows 3-6 are also provided with back and fore colors for selected items. In the lower picture rows 2-7 are selected but the listview has not focus. Rows 3-6 are also provided with back and fore colors for selected but unfocused items. In the second illustration the standard default colors are replace with custom default colors. The standard default back and fore colors are: Normal (unselected) items: White and black Selected items in focused listview: Dark blue and white Selected items in unfocused listview: Button face and black These custom default colors are used in the illustration: Normal (unselected) items: Light green and brown Selected items in focused listview: Shiny green (chartreuse) and black Selected items in unfocused listview: Dark green and black Examples Two folders with examples is included in the zip below. The first folder is named Examples and contains examples about the usage of the functions in the UDF. The second folder is named UDF topics and contains examples related to the implementation of the UDF. It's about the use of the subclassing technique as a substitute for a WM_NOTIFY message handler. Particularly about the message flow and performance issues. These examples are addressed in next section. The Examples folder contains these subfolders and files: 0) UDF examples\ - The small examples from the documentation of the functions in the UDF 1) Items-subitems\ - Colors and fonts for single items/subitems 2) Entire columns\ - Colors and fonts for entire columns 3) Alternating colors\ - Alternating row/column colors in an entire listview 4) Custom defaults\ - Replace standard default colors/font with custom defaults 5) Selected items\ - Colors for selected items when listview has focus and has not focus 6) Help file examples\ - Shows how to add colors to a few examples from AutoIt Help file 7) Original examples\ - An implementation of the examples in the old thread with this UDF Listview templates\ - A collection of listview templates ready to add colors/fonts Features demo.au3 - A brief demonstration of all features No colors or fonts.au3 - Reference example All examples runs on Windows XP and later without any performance issues. Folder 1 - 5 demonstrates the five main color/font features listed in top of post. In most of the subfolders you can find a _Readme.txt file with a brief description of the examples. Multiple selections is enabled in most listviews. A few examples will not pass an Au3Check. In particular the examples in subfolder 1 and 2 and the examples in UDF topics folder (see next section) were used to test the subclassing technique as a substitute for a WM_NOTIFY message handler. More information about some of the examples: Examples\0) UDF examples\0) ListViewColorsFonts_Init\Example 1.au3: #include <GUIConstantsEx.au3> #include "..\..\..\UDFs\ListViewColorsFonts.au3" #include "..\..\..\UDFs\GuiListViewEx.au3" Opt( "MustDeclareVars", 1 ) Example() Func Example() ; Create GUI Local $hGui = GUICreate( "ListViewColorsFonts_Init\Example 1", 420, 200, -1, -1, $GUI_SS_DEFAULT_GUI-$WS_MINIMIZEBOX ) ; Create ListView Local $idListView = GUICtrlCreateListView( "", 10, 10, 400, 180, $GUI_SS_DEFAULT_LISTVIEW-$LVS_SINGLESEL, $WS_EX_CLIENTEDGE ) _GUICtrlListView_SetExtendedListViewStyle( $idListView, $LVS_EX_DOUBLEBUFFER+$LVS_EX_FULLROWSELECT ) Local $hListView = GUICtrlGetHandle( $idListView ) ; Reduces flicker ; Add columns to ListView _GUICtrlListView_AddColumn( $idListView, "Column 1", 94 ) _GUICtrlListView_AddColumn( $idListView, "Column 2", 94 ) _GUICtrlListView_AddColumn( $idListView, "Column 3", 94 ) _GUICtrlListView_AddColumn( $idListView, "Column 4", 94 ) ; Fill ListView Local $iItems = 100 For $i = 0 To $iItems - 1 GUICtrlCreateListViewItem( $i & "/Column 1|" & $i & "/Column 2|" & $i & "/Column 3|" & $i & "/Column 4", $idListView ) Next ; Perform initializations to add colors/fonts to single items/subitems ListViewColorsFonts_Init( $idListView, 7 ) ; $fColorsFonts = 7, ( $iAddRows = 100, $bNative = False ) ; Set a green back color for an entire item and a yellow back color for a single cell ListViewColorsFonts_SetItemColors( $idListView, 3, -1, 0xCCFFCC ) ; Green back color for entire item ListViewColorsFonts_SetItemColors( $idListView, 3, 2, 0xFFFFCC ) ; Yellow back color for cell 2 in item ; Force an update of local variables in drawing function ListViewColorsFonts_Redraw( $idListView ) ; 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 ) ; Show GUI GUISetState( @SW_SHOW ) ; Message loop While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch WEnd ; Delete color/font info for listview ListViewColorsFonts_Exit( $idListView ) GUIDelete() EndFunc UDF topics The examples in UDF topics folder is about the use of subclassing as a substitute for a WM_NOTIFY message handler. Particularly about the message flow and performance issues. These examples illustrates some of the issues, that was discussed in the Subclassing section above, with code. The UDF topics folder contains these subfolders: 1) Subclassing\ - Creating listviews in GUI or child windows? 2) Performance\ - How many listviews can you create in GUI? More information about the examples: Next version In The code section above is already mentioned a number of subclass callback functions which are postponed to next version. The purpose of these additional functions is merely to optimize the code in terms of speed. A number of ListViewColorsFonts_Get-functions to complement the corresponding ListViewColorsFonts_Set-functions are also deferred to next version. For single items/subitems ($fColorsFonts = 1/2/4) colors and fonts are stored in $aListViewColorsFonts array which again is stored in $aListViewColorsFontsInfo. The three functions ListViewColorsFonts_SetItemColors / SetItemFonts / SetItemColorsFonts are used to update $aListViewColorsFonts item by item or subitem by subitem. It would be much faster to update $aListViewColorsFonts directly. Two functions are needed to get a copy of the array from $aListViewColorsFontsInfo and store the array again after the updates. And there is also a need for a couple of examples to illustrate the technique. Examples to dynamically update colors and fonts are missing in this version. Perhaps there is also a need for a few functions to support dynamically updates. For non-native listviews created with _GUICtrlListView_Create it's not uncommon to use ItemParam to store a user defined value. If index in $aListViewColorsFonts is stored in ItemParam, it's no longer possible to use ItemParam for such purposes. A couple of functions to give the user an opportunity to still be able to store a user defined value would be nice. Several global variables are defined in this version. They will be removed in the next version except for a few variables which probably will need to be global in performance terms. If there will be reported any issues or problems in this version, they of course also need to be addressed. The next version should be ready in 2-3 months, and it should also be the final version. Zip file The zip is structured in this way Examples\ UDF topics\ UDFs\ ListViewColorsFonts.au3 GuiImageListEx.au3 GuiListViewEx.au3 NamedColors.au3 OtherColors.au3 NamedColors.au3 contains global constants of named colors copied from .NET Framework Colors Class. You need AutoIt 3.3.10 or later. Tested on Windows 7 32/64 bit and Windows XP 32 bit. Comments are welcome. Let me know if there are any issues. (Set tab width = 2 in SciTE to line up comments by column.) ListViewColorsFonts.7z
    1 point
  6. Melba23

    ListView select subitems.

    newniman, The problem was that you had not correctly set the position of the ListView within the GUI - see line #55 of this amended script: #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <File.au3> #include <GuiListView.au3> Global $hGUI, $hListview, $aHit[2] = [-1, -1] ; $aHit contains row & col of marked cell Local $PIPEFILE = "edit-zoom_step_av_value.csv" Local $aRetArray _FileReadToArray($PIPEFILE, $aRetArray, $FRTA_NOCOUNT);, "|") ; As the delimiters are already "!" why bother to split the lines? <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< $hGUI = GUICreate("Mark Cell in Listview", 1040, 590) Local $cListview = GUICtrlCreateListView("Zoom Step|F3.4|F4.0|F4.5|F5.0|F5.6|F6.3|F7.1|F8.0", 24, 100, 472, 300, $LVS_REPORT, BitOR($LVS_EX_GRIDLINES, $LVS_EX_FULLROWSELECT)) $hListview = GUICtrlGetHandle($cListview) GUICtrlSetFont($cListview, 8, 800, 0, "MS Sans Serif") For $x = 0 To UBound($aRetArray, $UBOUND_ROWS) - 1 ; As the "|" are already in place, this is much easier to write! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< GUICtrlCreateListViewItem($aRetArray[$x], $cListview) Next Local $cButton = GUICtrlCreateButton("Value?", 150, 430, 70, 20) GUISetState(@SW_SHOW) GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY"); good tutorial @ https://www.autoitscript.com/wiki/Tutorial_GUIRegisterMsg While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $cButton MsgBox(0, "Info", "Cell selected: " & _GUICtrlListView_GetItemText($hListview, $aHit[0], $aHit[1]) & @CR, 0, $hGUI) ;MsgBox(0, "Info", "zoom_step selected: " & $aHit[0] & " --> Aperture column selected: " & $aHit[1], 0, $hGUI) EndSwitch WEnd Func WM_NOTIFY($hWnd, $iMsg, $wParam, $lParam) #forceref $hWnd, $iMsg, $wParam ; Used by au3check to tell it not to report on "variable not used" when using the parameter "-w 5" - Correct <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Local $tNMHDR, $hWndFrom, $iCode $tNMHDR = DllStructCreate($tagNMHDR, $lParam) $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom")) $iCode = DllStructGetData($tNMHDR, "Code") Switch $hWndFrom Case $hListview Switch $iCode Case $LVN_ITEMCHANGED Local $tNMLISTVIEW, $iItem, $aInfo $tNMLISTVIEW = DllStructCreate($tagNMLISTVIEW, $lParam) $iItem = DllStructGetData($tNMLISTVIEW, "Item") _GUICtrlListView_SetItemSelected($hListview, $iItem, False) Local $aInfo = GUIGetCursorInfo($hGUI) If $aInfo[2] Then $aInfo = _GUICtrlListView_SubItemHitTest($hListview, $aInfo[0] - 24, $aInfo[1] - 100) ; Upper left position of ListView within GUI - so must match actual position If $aInfo[0] > -1 And $aInfo[1] > -1 And $aInfo[0] = $iItem Then If $aHit[0] > -1 Then _GUICtrlListView_RedrawItems($hListview, $aHit[0], $aHit[0]) If $aHit[0] <> $aInfo[0] Or $aHit[1] <> $aInfo[1] Then $aHit[0] = $aInfo[0] ; Row $aHit[1] = $aInfo[1] ; Col Else $aHit[0] = -1 ; Row $aHit[1] = -1 ; Col EndIf _GUICtrlListView_RedrawItems($hListview, $iItem, $iItem) EndIf EndIf Case $NM_CUSTOMDRAW Local $tNMLVCUSTOMDRAW = DllStructCreate($tagNMLVCUSTOMDRAW, $lParam) Local $dwDrawStage = DllStructGetData($tNMLVCUSTOMDRAW, "dwDrawStage") Switch $dwDrawStage ; Holds a value that specifies the drawing stage Case $CDDS_PREPAINT ; Before the paint cycle begins Return $CDRF_NOTIFYITEMDRAW ; Notify the parent window of any ITEM-related drawing operations Case $CDDS_ITEMPREPAINT ; Before painting an item Return $CDRF_NOTIFYSUBITEMDRAW ; Notify the parent window of any SUBITEM-related drawing operations Case BitOR($CDDS_ITEMPREPAINT, $CDDS_SUBITEM) ; Before painting a subitem Local $dwItemSpec = DllStructGetData($tNMLVCUSTOMDRAW, "dwItemSpec") ; Item index Local $iSubItem = DllStructGetData($tNMLVCUSTOMDRAW, "iSubItem") ; Subitem index Local $uItemState = DllStructGetData($tNMLVCUSTOMDRAW, "uItemState") ; Item state If $dwItemSpec = $aHit[0] Then ; Marked row Switch $iSubItem Case $aHit[1] ; Marked column DllStructSetData($tNMLVCUSTOMDRAW, "ClrText", 0xFFFFFF) ; Forecolor white DllStructSetData($tNMLVCUSTOMDRAW, "clrTextBk", 0xCC6600) ; Backcolor dark blue, BGR Case Else ; Other columns DllStructSetData($tNMLVCUSTOMDRAW, "ClrText", 0x000000) ; Forecolor black DllStructSetData($tNMLVCUSTOMDRAW, "ClrTextBk", 0xFFFFFF) ; Backcolor white EndSwitch Else ; Other rows DllStructSetData($tNMLVCUSTOMDRAW, "ClrText", 0x000000) DllStructSetData($tNMLVCUSTOMDRAW, "ClrTextBk", 0xFFFFFF) EndIf Return $CDRF_NEWFONT ; $CDRF_NEWFONT must be returned after changing font or colors EndSwitch EndSwitch EndSwitch Return $GUI_RUNDEFMSG EndFunc ;==>WM_NOTIFY I also removed most of the include files (which were not all necessary) and cleaned up the _FileReadToArray code which makes creating the ListView items much easier. M23
    1 point
  7. Oh, all right then, a guy can be wrong already! #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <GuiRichEdit.au3> Global $sText = "", $hGui, $hRichEdit For $n = 2 To 100 $sText &= $n & " - This is a single long line intended to cause a hoizontal scroll bar to appear in my RichEdit control." & @CRLF Next $hGui = GUICreate("Example (" & StringTrimRight(@ScriptName, 4) & ")", 320, 350, -1, -1) $hRichEdit = _GUICtrlRichEdit_Create($hGui, $sText, 10, 10, 300, 220, BitOR($ES_MULTILINE, $WS_VSCROLL, $WS_HSCROLL)) _GUICtrlRichEdit_SetEventMask($hRichEdit, BitOR($ENM_SCROLL, $ENM_SCROLLEVENTS)) GUISetState(@SW_SHOW) GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY") While True Switch GUIGetMsg() Case $GUI_EVENT_CLOSE _GUICtrlRichEdit_Destroy($hRichEdit) Exit EndSwitch WEnd Func WM_NOTIFY($hWnd, $iMsg, $iWparam, $iLparam) ; $tagEN_MSGFILTER = hwnd hWndFrom;uint_ptr IDFrom;INT Code;uint msg;wparam wParam;lparam lParam #forceref $iMsg, $iWparam Local $hWndFrom, $iCode, $tNMHDR, $tMsgFilter, $hMenu $tNMHDR = DllStructCreate($tagNMHDR, $iLparam) $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom")) $iCode = DllStructGetData($tNMHDR, "Code") Switch $hWndFrom Case $hRichEdit Select Case $iCode = $EN_MSGFILTER $tMsgFilter = DllStructCreate($tagEN_MSGFILTER, $iLparam) $aPos = _GUICtrlRichEdit_GetScrollPos($hRichEdit) Switch DllStructGetData($tMsgFilter, "msg") Case 276 ConsoleWrite("Debug: Horz Scroll: x = " & $aPos[0] & "; y = " & $aPos[1] & @LF) Case 277 ConsoleWrite("Debug: Vert Scroll: x = " & $aPos[0] & "; y = " & $aPos[1] & @LF) EndSwitch EndSelect EndSwitch Return $GUI_RUNDEFMSG EndFunc ;==>WM_NOTIFY
    1 point
×
×
  • Create New...