Jump to content

ListView how to change color of selected unfocused listview element / row ?


Go to solution Solved by donnyh13,

Recommended Posts

Posted
11 minutes ago, WildByDesign said:

I am curious about this as well. In particular, are there any performance differences between constantly creating/deleting brushes in comparison to the non-brush solution?

Exactly this is what I'm curios too. You just worded it in a better way.

Thanks 

11 minutes ago, WildByDesign said:

I've learned a lot from this thread already. :)

Good for you :)

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted
1 hour ago, mLipok said:

@UEZ I also have a question about @Nine example and my modification .
Nine uses 

_WinAPI_DeleteObject($hBrush)

which was fired each time LV was re-drawn

My questions are about using 

_WinAPI_DeleteObject($hBrush)

in a such kind of multiple usage "like a loop"

Question 1:
Should we delete Brush each time or they can be static ? (which I did in my modification to Nine example)

Question 2:
Are there any advantages or disadvantages of using Brush in comparition to yours "non Brush solution" - of coruse in such scenario (using Brush in WM_NOTIFY especially with big ListView) 

Thank you very much in advance
mLipok

 

1) As a general rule, when you open a resource, you should release it again to avoid a memory leak. For example, if you constantly call _WinAPI_CreateSolidBrush(), you’re reserving memory without freeing it up. Eventually, the memory will run out.
Yes, every call to _WinAPI_CreateSolidBrush() / _WinAPI_DeleteObject() takes processing time, which may become noticeable if there are a large number of calls. I don’t think this plays a major role for “normal” applications.

2) At first glance, it appears that no brush is being used, but I assume that Windows creates a brush internally and then deletes it to prevent a memory leak.

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Posted
3 hours ago, UEZ said:

Yes, every call to _WinAPI_CreateSolidBrush() / _WinAPI_DeleteObject() takes processing time, which may become noticeable if there are a large number of calls. I don’t think this plays a major role for “normal” applications.

On big 4K screen with huge numbers of rows in the listview it can be noticeable.

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

  • 2 weeks later...
Posted (edited)
On 4/22/2026 at 11:44 AM, mLipok said:

My finall modification:

;~ https://www.autoitscript.com/forum/topic/213651-listview-how-to-change-color-of-selected-unfocused-listview-element-row/#findComment-1551804

;Coded by UEZ build 2020-04-21
#include <ColorConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiListView.au3>
#include <StructureConstants.au3>
#include <WinAPISys.au3>
#include <WindowsConstants.au3>

Opt("MustDeclareVars", True)

Example1()
Example2()

Func Example1()
    Local $hGUI = GUICreate("Listview Example1", 300, 300)
    Local $idListview = GUICtrlCreateListView("Col1|Col2|Col3  ", 10, 10, 200, 150)
    GUICtrlCreateListViewItem("item2|col22|col23", $idListview)
    GUICtrlCreateListViewItem("item1|col12|col13", $idListview)
    GUICtrlCreateListViewItem("item3|col32|col33", $idListview)
    Local $idButton = GUICtrlCreateButton("Test", 75, 170, 70, 20)
    GUISetState()

    While True
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                GUIDelete($hGUI)
                ExitLoop
            Case $idButton
                _GUICtrlListView_GetSelectedIndices($idListview)
                GUICtrlSetState($idListview, $GUI_FOCUS)
        EndSwitch
    WEnd
EndFunc   ;==>Example1

Func Example2()
    Local $hGUI = GUICreate("Listview Custom Draw Example2", 300, 300)

    Local $idListview = GUICtrlCreateListView("Col1|Col2|Col3", 10, 10, 200, 150, BitOR($LVS_SHOWSELALWAYS, $LVS_REPORT))
    _GUICtrlListView_SetExtendedListViewStyle($idListview, BitOR($LVS_EX_FULLROWSELECT, $LVS_EX_DOUBLEBUFFER))

    GUICtrlCreateListViewItem("item2|col22|col23", $idListview)
    GUICtrlCreateListViewItem("item1|col12|col13", $idListview)
    GUICtrlCreateListViewItem("item3|col32|col33", $idListview)
    GUICtrlCreateListViewItem("item4||col33", $idListview)

    Local $idButton = GUICtrlCreateButton("Test", 75, 170, 70, 20)

    GUISetState(@SW_SHOW)
    GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")

    While True
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                GUIDelete($hGUI)
                ExitLoop
            Case $idButton
                ConsoleWrite("Button clicked." & @CRLF)
        EndSwitch
    WEnd
EndFunc   ;==>Example2

Func WM_NOTIFY($hWnd, $iMsg, $wParam, $lParam)
    #forceref $hWnd, $iMsg, $wParam

    Local $tNMHDR = DllStructCreate($tagNMHDR, $lParam) ; $tagNMHDR is defined in #include <StructureConstants.au3>
    Local $iCode = $tNMHDR.Code
    Local $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))

    If _WinAPI_GetClassName($hWndFrom)= "SysListView32" Then
        Local $tNMLVCUSTOMDRAW = DllStructCreate($tagNMLVCUSTOMDRAW, $lParam) ; $tagNMLVCUSTOMDRAW is defined in #include <StructureConstants.au3> ; https://learn.microsoft.com/en-us/windows/win32/api/commctrl/ns-commctrl-nmlvcustomdraw
        Local $dwItemSpec = $tNMLVCUSTOMDRAW.dwItemSpec
        Local $dwDrawStage = $tNMLVCUSTOMDRAW.dwDrawStage
        Local $uItemState = $tNMLVCUSTOMDRAW.uItemState
        Local $tItem = DllStructCreate($tagNMLVCUSTOMDRAW, $lParam)
        Local $dwItemType = $tItem.dwItemType

        If $dwItemType = $LVCDI_ITEM Then
            Switch $iCode
                Case $NM_CUSTOMDRAW
                    Switch $dwDrawStage
                        Case $CDDS_PREPAINT
                            Return $CDRF_NOTIFYITEMDRAW

                        Case $CDDS_ITEMPREPAINT
                            If _GUICtrlListView_GetItemSelected($hWndFrom, $dwItemSpec) Then
                                ;remove SELECTED-State and draw system colors
                                $tNMLVCUSTOMDRAW.uItemState = BitAND($uItemState, BitNOT($CDIS_SELECTED), BitNOT($CDIS_FOCUS))
;~                              $tNMLVCUSTOMDRAW.clrTextBk = _WinAPI_GetSysColor($COLOR_HIGHLIGHT) ; for _WinAPI_GetSysColor() "system" color should be used - $COLOR_HIGHLIGHT is defined in WindowsSysColorConstants.au3
;~                              $tNMLVCUSTOMDRAW.clrText = _WinAPI_GetSysColor($COLOR_HIGHLIGHTTEXT) ; for _WinAPI_GetSysColor() "system" color should be used - $COLOR_HIGHLIGHTTEXT is defined in WindowsSysColorConstants.au3
                                $tNMLVCUSTOMDRAW.clrTextBk = $COLOR_BLACK ; direct color - defined in ColorConstants.au3 or given by hand 0x000000
                                $tNMLVCUSTOMDRAW.clrText = $COLOR_WHITE ; direct color - defined in ColorConstants.au3 or given by hand 0xFFFFFF
                                Return $CDRF_NEWFONT
                            EndIf
                    EndSwitch
            EndSwitch
        EndIf
    EndIf
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

 

 

@UEZ yours example is using  Return $CDRF_NEWFONT


Other uses Return $CDRF_SKIPDEFAULT  

The problem that I have with your examples is that I would like to combine them with autonumbering by putting $dwItemSpec to first column .
And adding Grid lines.
As so far I used this snippet:

If $dwDrawStage = $CDDS_PREPAINT Then Return $CDRF_NOTIFYITEMDRAW
            If $dwDrawStage = $CDDS_ITEMPREPAINT Then Return $CDRF_NOTIFYSUBITEMDRAW
            Local $bIsSelected = _GUICtrlListView_GetItemState($tItem.hWndFrom, $tItem.dwItemSpec, $LVIS_SELECTED)
            If $bIsSelected Then
                _WinAPI_SelectObject($hDC, $hBrushItem_Selected)
            Else
                _WinAPI_SelectObject($hDC, $hBrushItem_Unselected)
            EndIf

            _WinAPI_SelectObject($hDC, $hPenItem_Borders)
            If $tItem.dwItemSpec > 0 Then $tRect.top -= 1
            $tRect.bottom += 1
            _WinAPI_Rectangle($hDC, $tRect)

            _WinAPI_SetTextColor($hDC, $bIsSelected ? $clrWhite : $clrBlack)
            _WinAPI_SetBkMode($hDC, $TRANSPARENT)

            $tRect.Left += 5
            $tRect.Top += 2
            If $tItem.iSubitem = $LV_COL__IDX_for_user Then
                _WinAPI_SetTextColor($hDC, $clrGroup2)
                _WinAPI_DrawText($hDC, $dwItemSpec, $tRect, BitOR($DT_CENTER, $DT_INTERNAL, $DT_WORDBREAK))
            Else
                _WinAPI_DrawText($hDC, _GUICtrlListView_GetItemText($tItem.hWndFrom, $tItem.dwItemSpec, $tItem.iSubitem), $tRect, BitOR($DT_LEFT, $DT_INTERNAL, $DT_WORDBREAK))
            EndIf
            Return $CDRF_SKIPDEFAULT

but this impact CPU usage on my i5 8gen laptop - about 4% constant CPU usage instead 0.2% in your solution (without text changing and without gridlines ) .

So my question is do you have idea how to draw gridlines and change text together wiht yours quick/fast solution:

 

                        Case $CDDS_ITEMPREPAINT
                            If _GUICtrlListView_GetItemSelected($hWndFrom, $dwItemSpec) Then
                                ;remove SELECTED-State and draw system colors
                                $tNMLVCUSTOMDRAW.uItemState = BitAND($uItemState, BitNOT($CDIS_SELECTED), BitNOT($CDIS_FOCUS))
;~                              $tNMLVCUSTOMDRAW.clrTextBk = _WinAPI_GetSysColor($COLOR_HIGHLIGHT) ; for _WinAPI_GetSysColor() "system" color should be used - $COLOR_HIGHLIGHT is defined in WindowsSysColorConstants.au3
;~                              $tNMLVCUSTOMDRAW.clrText = _WinAPI_GetSysColor($COLOR_HIGHLIGHTTEXT) ; for _WinAPI_GetSysColor() "system" color should be used - $COLOR_HIGHLIGHTTEXT is defined in WindowsSysColorConstants.au3
                                $tNMLVCUSTOMDRAW.clrTextBk = $COLOR_BLACK ; direct color - defined in ColorConstants.au3 or given by hand 0x000000
                                $tNMLVCUSTOMDRAW.clrText = $COLOR_WHITE ; direct color - defined in ColorConstants.au3 or given by hand 0xFFFFFF
                                Return $CDRF_NEWFONT
                            EndIf

 

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...