Search code examples
c#winformslistview

How to keep the Selected property true when clicked a not exist row in ListView?


My ListView have to keep the Selected property true unless Light and Time value changed. (Because the ListView should remain in this state and Enabled should change to false.)

enter image description here

When I click outside ListView, the Selected property stays true. But, when I click a 'not exist' row of ListView, the Selected property doesn't stay true.

enter image description here

To solve this problem, I wrote a code in ListView_Click event, but ListView_Click event only occurs about rows with values.

What shoud I do?


Solution

  • One way to suppress suppress the click behavior under those conditions is to make a custom ListViewEx class that overrides WndProc and performs a HitTest when the mouse is clicked. (You'll have to go to the designer file and swap out the ListView references of course.)

    class ListViewEx : ListView
    {
        const int WM_LBUTTONDOWN = 0x0201;
        protected override void WndProc(ref Message m)
        {
            if(m.Msg == WM_LBUTTONDOWN)
            {
                if (suppressClick())
                {
                    m.Result = (IntPtr)1;
                    return;
                }
            }
            base.WndProc(ref m);
        }
        private bool suppressClick()
        {
            var hitTest = HitTest(PointToClient(MousePosition));
            if ((hitTest.Item == null) || string.IsNullOrEmpty(hitTest.Item.Text))
            {
                return true;
            }
            return false;
        }
    }
    

    test result