4

I have a ListView control and I want to add a checkbox in upper left corner of ListView.

The solution for adding the CheckBox control that I'm using is this:

Me.ListViewCustom1.Controls.Add(CheckBoxControl);
Me.CheckBoxControl.Location = new Point(3, 5);

The issue I'm having is on ListView scroll. The checkbox appears all smeared up. I've been scavaging the web for a solution and I really can't find something that would solve this issue.

This is how the controls appears:

Image(Sorry for random data)

I hereby asking for help in this complicated situation.

TaW
  • 53,122
  • 8
  • 69
  • 111
  • [How to add a Checkbox to a ListView column header?](https://stackoverflow.com/a/35790015/3110834) – Reza Aghaei Jan 22 '21 at 22:48
  • I actually saw that post. The idea with adding a dedicated column for the checkbox is clever but I would like to solve the issue without the new column. Do you think it's possible? – Pavlo Zakharuk Jan 22 '21 at 22:50
  • [See here](https://stackoverflow.com/questions/1851620/handling-scroll-event-on-listview-in-c-sharp) on capturing the scroll event ; then maybe a refresh will help.. – TaW Jan 22 '21 at 23:00
  • I've had problems with this solution aswell. Because the position I set doesn't follow the "column". The checkbox, after refresh, appears in position not relative to first column :/ – Pavlo Zakharuk Jan 22 '21 at 23:09

1 Answers1

2

Assuming you don't want the option that I used in the linked post, the other way that you can approach this is adding the CheckBox to the header of the ListView.

Using SendMessageYou can send LVM_GETHEADER message to the listview control and get the handle of the header, then SetParent will help you to set the header as parent of checkbox:

const int LVM_GETHEADER = 0x1000 + 31;
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
private void Form1_Load(object sender, EventArgs e)
{
    var header = SendMessage(listView1.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
    var checkBox = new CheckBox()
    {
        AutoSize = true,
        Text = "",
        Location = new Point(3, 5)
    };
    this.listView1.Controls.Add(checkBox);
    SetParent(checkBox.Handle, header);
}

And this is what you get:

enter image description here

Obviously I've added a few extra spaces before text of the column header to make room for the check box.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398