且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

窗口形式的树视图中的 AutoResize 属性

更新时间:2023-10-19 18:04:04

您可以发送

I want to resize treeview based on treenodes. When it expand i want to show all item but when it collapse i want to show just root node and decrease height of treeview. I just tried is any property similar to auto resize but it was not found. If anybody help me on this problem it will be great.

You can send TVM_GETNEXTITEM message to TreeView, passing TVGN_LASTVISIBLE as wParam to get the handle of last node of the treeview.

Then you can call the internal NodeFromHandle method to get the node from handle. Then you can use Bound property of the node to find its bound. Top + Height of the last item, determines required height of TreeView:

const int TVM_GETNEXTITEM = 0x1100 + 10;
const int TVGN_LASTVISIBLE = 0x000A;
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);

void AdjustTreeViewHeight(TreeView treeView)
{
    treeView.Scrollable = false;
    var nodeHandle = SendMessage(treeView.Handle, TVM_GETNEXTITEM, 
        TVGN_LASTVISIBLE, IntPtr.Zero);
    var node = treeView.GetType().GetMethod("NodeFromHandle",
        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
        .Invoke(treeView, new object[] { nodeHandle }) as TreeNode;
    var r = node.Bounds;
    treeView.Height = r.Top + r.Height + 4;
}

Cal above method after adding/removing nodes, also in AfterCollapse and AfterExpand: