Sending a LVM_APPROXIMATEVIEWRECT
message to Control, you can get back an approximate measure that includes the Header's height and the size of all the Items.
Setting the ClientSize
of the Control to this measure, should allow to resize the ListView, to show all Items in their full extent.
You can specify a number of Items to include (wParam
) and a preferred size (lParam
), or set both lParam
and wParam
to -1
: in this case, all Items are included and the size is auto-detected.
Note that the height may include the horizontal Scrollbar height: a margin may be visible at the bottom.
If that's not desirable, remove SystemInformation.HorizontalScrollBarHeight
from the overall height.
Or do the same thing to limit the extent of the Control to a specific measure, if the number of Items in the ListView suggests it.
► As noted in comments, if the ListView is docked to the Form, setting its ClientSize doesn't have any visible effect.
In this case, you need to also resize the Form, adding the difference between the old Size of the ListView and its new calculated size.
Assuming the ListView is named listView1
:
Size oldSize = listView1.ClientSize;
int hScrollBarHeight = SystemInformation.HorizontalScrollBarHeight
// Both wParam and lParam set to -1: include all Items and full size
int approxSize = NativeMethods.SendMessage(
listView1.Handle, NativeMethods.LVM_APPROXIMATEVIEWRECT, -1, (-1 << 16 | -1));
int approxHeight = approxSize >> 16;
int approxWidth = approxSize & 0xFFFF;
Size newSize = new Size(approxWidth, approxHeight - hScrollBarHeight);
// If needed, resize the Form (here, grow and shrink) to adapt to the new size
// Checking the Dock property state is a possible example, apply whatever logic fits
if (listView1.Dock != DockStyle.None) {
this.Height += newSize.Height - oldSize.Height;
this.Width += newSize.Width - oldSize.Width;
}
listView1.ClientSize = newSize;
internal class NativeMethods
{
internal const int LVM_FIRST = 0x1000;
internal const int LVM_APPROXIMATEVIEWRECT = LVM_FIRST + 0x40;
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, int lParam);
}