2

There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around?

2 Answers2

11

I know this post is fairly old, however, if you never found the best option, I've got a blog post that may help, it involves utilizing LVM_SETICONSPACING.

According to my blog,

Initially, you'll need to add:

using System.Runtime.InteropServices;

Next, you'll need to import the DLL, so that you can utilize SendMessage, to modify the ListView parameters.

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

Once that is complete, create the following two functions:

public int MakeLong(short lowPart, short highPart)
{
    return (int)(((ushort)lowPart) | (uint)(highPart << 16));
}

public void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding) 
{     
    const int LVM_FIRST = 0x1000;     
    const int LVM_SETICONSPACING = LVM_FIRST + 53;     
    SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding));      
} 

Then to use the function, just pass in your ListView, and set the values. In the example, 64 pixels is the image width, and 32 pixels is my horizontal spacing/padding, 100 pixels is the image height, and 16 pixels is my vertical spacing/padding, and both parameters require a minimum of 4 pixels.

ListViewItem_SetSpacing(this.listView1, 64 + 32, 100 + 16);
Quinn Johns
  • 376
  • 4
  • 16
  • 1
    Please post relevant content from the blog post in your answer. – Jon B Oct 25 '12 at 16:13
  • 1
    `LVM_SETICONSPACING` only applies to ListViews in Icon view. Any way to do an equivalent thing when in Details view to change the row padding (not the row height, which as @Joel Lucsy says can be done with an imagelist)? – Nick Shaw May 29 '14 at 10:39
  • Where does the value `53` come from in `const int LVM_SETICONSPACING = LVM_FIRST + 53;`? Shouldn't that be a constant with a comment describing its purpose and meaning? – rory.ap May 19 '20 at 14:04
  • The reason I ask is I'm dealing with different DPIs and trying to calculate layouts based on ratio. I don't know if 53 has something to do with pixels in which case it would be different at DPI != 100%. – rory.ap May 19 '20 at 14:06
5

A workaround is to use an ImageList that is as tall as you want the items to be. Just fill a blank image with the background color. You can even make the image 1 wide so as to not take much space horizontally.

Joel Lucsy
  • 8,520
  • 1
  • 29
  • 35