Toggle ListView Selection Bar and Headers

This article first appeared in Visual Developer Magazine
(Note: This is my unedited original and may differ slightly from the published version.)
By Matt Hart

Visual Basic’s ListView control normally shows only button style headers in lvwReport View style. Clickable headers imply sorting, but you’ll often want a ListView control without sorting. Fortunately, it’s easy to toggle the headers from flat to button style. The header is actually a separate object, and you must retrieve its handle before changing the style.

Changing the width of the selection bar is easier. An extended style bit is toggled using the SendMessage API function.

Private Declare Function GetWindowLong Lib "user32" Alias _
    "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias _
    "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias _
    "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _
    ByVal wParam As Long, lParam As Any) As Long

Private Const GWL_STYLE = (-16)
Private Const LVM_FIRST = &H1000
Private Const LVM_GETHEADER = (LVM_FIRST + 31)
Private Const HDS_BUTTONS = 2
Private Const LVM_SETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 54)
Private Const LVM_GETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 55)
Private Const LVS_EX_FULLROWSELECT = &H20

Call ToggleHeaders(ListView1.hwnd)
Call ToggleSelect(ListView1.hwnd)

Sub ToggleHeaders(lhWnd As Long)
    Dim hHeader As Long, lStyle As Long
    hHeader = SendMessage(lhWnd, LVM_GETHEADER, 0, ByVal 0&)
    lStyle = GetWindowLong(hHeader, GWL_STYLE)
    SetWindowLong hHeader, GWL_STYLE, lStyle Xor HDS_BUTTONS
End Sub

Sub ToggleSelect(lhWnd As Long)
    Dim lStyle As Long
    lStyle = SendMessage(lhWnd, LVM_GETEXTENDEDLISTVIEWSTYLE, _
                         0, ByVal 0)
    lStyle = lStyle Xor LVS_EX_FULLROWSELECT
    SendMessage lhWnd, LVM_SETEXTENDEDLISTVIEWSTYLE, _
                0, ByVal lStyle
End Sub

Back to Articles
Copyright © 2000 by Matt E. Hart, All Rights Reserved Worldwide.
Nothing on this web site may be reproduced, in any form, without express written consent.