Search code examples
c#winformstreeview

Autosize witdth of treeview after collapse


I'm looking for a way to set the width of a treeview to either it's max, or to the size of the longest treenode in it, whenever a node is being collapsed or opened.

I've tried using the clientsize, but that doesn't seem to work. Is there a different way to check which node is the longest and set the TreeView.Width to that size?


Solution

  • After some more searching on the net I found this way:

    private const int GWL_STYLE = -16;
    private const int WS_VSCROLL = 0x00200000;
    private const int WS_HSCROLL = 0x00100000;
    
    
    [DllImport("user32.dll", ExactSpelling = false, CharSet = CharSet.Auto)]
    private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
    

    and:

    //tree = instance of a treeview
    tree.AfterExpand += (s, ea) =>
    {
        int style = GetWindowLong(tree.Handle, GWL_STYLE);
        while ((style & WS_HSCROLL) != 0)
        {
            tree.Width++;
            style = GetWindowLong(tree.Handle, GWL_STYLE);
        }
    };
    

    Ofcourse you can use this on a button aswell!