Click here to Skip to main content
15,884,099 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Collapsible ListView

Rate me:
Please Sign up or sign in to vote.
4.73/5 (6 votes)
24 Oct 2018MIT 9.4K   6   3
Collapsible ListView

Introduction

This is a short tip for a collapsible ListView.

Background

For some reasons, I had to create a Windows Form application and I needed to have a ListView control on it. Then I decided to make its groups collapsible and I found that although there are several pieces around the web, no one had put them into a class that a DEV can just put to use with no hooks and tricks around.

Using the Code

Without any further ado, here is the code. Just add it to your project and replace your existing ListView control references with this and all should work as before with collapsible groups.

C#
public class CollapsibleListView : ListView
{
    private const int LVGF_STATE = 0x00000004;
    private const int LVGS_COLLAPSIBLE = 0x00000008;
    private const int LVM_FIRST = 0x1000;
    private const int LVM_SETGROUPINFO = (LVM_FIRST + 147);
    private const int LVM_INSERTGROUP = (LVM_FIRST + 145);
    private const int WM_LBUTTONUP = 0x0202;

    /// <summary>
    /// Intercepts <see cref="ListView.WndProc(ref Message)"/> calls
    /// </summary>
    /// <param name="message">Message</param>
    protected override void WndProc(ref Message message)
    {
        switch (message.Msg)
        {
            case WM_LBUTTONUP:
                base.DefWndProc(ref message);
                break;
            case LVM_INSERTGROUP:
                base.WndProc(ref message);
                var group = Marshal.PtrToStructure<LvGroup>(message.LParam);
                SetGroupCollapsible(group.iGroupId);
                return;
        }

        base.WndProc(ref message);
    }

    /// <summary>
    /// Sends the specified message to a window or windows.
    /// <seealso cref="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendmessage"/>
    /// </summary>
    /// <param name="handle">A handle to the window 
    /// whose window procedure will receive the message.</param>
    /// <param name="message">The message to be sent.</param>
    /// <param name="wParam">Additional message-specific information.</param>
    /// <param name="lParam">Additional message-specific information.</param>
    /// <returns>The return value specifies the result of the message processing; 
    /// it depends on the message sent.</returns>
    [DllImport("user32.dll")]
    private static extern int SendMessage(IntPtr handle, int message, int wParam, IntPtr lParam);

    /// <summary>
    /// Represents native version of the <see cref="ListViewGroup"/> class
    /// <seealso cref="https://docs.microsoft.com/en-us/windows/desktop/api/commctrl/ns-commctrl-taglvgroup"/>
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    private struct LvGroup
    {
        public int cbSize;
        public int mask;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string pszHeader;
        public int cchHeader;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string pszFooter;
        public int cchFooter;
        public int iGroupId;
        public int stateMask;
        public int state;
        public int uAlign;
    }

    /// <summary>
    /// Updates a <see cref="ListViewGroup"/> item's state within current instance as collapsible
    /// </summary>
    /// <param name="groupItemIndex">Group item index</param>
    private void SetGroupCollapsible(int groupItemIndex)
    {
        LvGroup group = new LvGroup();
        group.cbSize = Marshal.SizeOf(group);
        group.state = LVGS_COLLAPSIBLE;
        group.mask = LVGF_STATE;
        group.iGroupId = groupItemIndex;

        IntPtr ip = IntPtr.Zero;
        try
        {
            ip = Marshal.AllocHGlobal(group.cbSize);
            Marshal.StructureToPtr(group, ip, false);
            SendMessage(Handle, LVM_SETGROUPINFO, groupItemIndex, ip);
        }
        finally
        {
            if (ip != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(ip);
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Architect
United States United States
I got my BS in Software Engineering from Iran, worked there for 4.5 years mainly in industrial automation field. Then I moved to Australia. In Australia, I had a great chance to work at some big companies. Since 2009 I have been living in the States. I received my MS in Information Systems from Illinois State University. Currently, I am a Senior Software Development Engineer.

Comments and Discussions

 
QuestionMoving the collapse button Pin
Lewis Cho5-Nov-23 22:12
Lewis Cho5-Nov-23 22:12 
QuestionModification for earlier Framework Versions Pin
chrisbray25-Oct-18 3:55
chrisbray25-Oct-18 3:55 
AnswerRe: Modification for earlier Framework Versions Pin
Tecfield26-Oct-18 2:31
Tecfield26-Oct-18 2:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.