Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent immediate firing of MouseUp event in Winforms Listview when the mouse is still down?

Basically if you have a standard Listview that has multi-selection turned on, the mouse up and down events work fine.

But if you turn off multi-selection and click and hold your mouse button on the Listview, it immediately fires down and then up event while the mouse button is still down.

Is there a way to prevent this? I only want the mouse up event to trigger when I release the mouse button.

like image 668
Joan Venge Avatar asked Oct 21 '25 02:10

Joan Venge


1 Answers

ListView mouse event processing in WndProc is a bit complicated. This is what I could do by overriding OnMouseUp and WndProc to stop raisng the unnecessary MouseUp:

using System.Collections.Specialized;
using System.Reflection;
using System.Windows.Forms;
public class MyListView : ListView
{
    const int WM_LBUTTONUP = 0x0202, WM_RBUTTONUP = 0x0205, WM_MBUTTONUP = 0x0208;
    const int LISTVIEWSTATE_mouseUpFired = 0x00080000;
    FieldInfo listViewStateField;
    public MyListView()
    {
        listViewStateField = (typeof(ListView)).GetField("listViewState",
               BindingFlags.NonPublic | BindingFlags.Instance);
    }
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_LBUTTONUP || m.Msg == WM_MBUTTONUP || m.Msg == WM_RBUTTONUP) {
            var value = (BitVector32)listViewStateField.GetValue(this);
            value[LISTVIEWSTATE_mouseUpFired] = true;
            listViewStateField.SetValue(this, value);
            var x = (m.LParam.ToInt32() & 0xffff);
            var y = (m.LParam.ToInt32() >> 16) & 0xffff;
            var e = new MouseEventArgs(
                m.Msg == WM_LBUTTONUP ? MouseButtons.Left :
                m.Msg == WM_MBUTTONUP ? MouseButtons.Middle :
                MouseButtons.Right, 1, x, y, 0);
            OnMouseUp(e);
        }
        base.WndProc(ref m);
    }
    protected override void OnMouseUp(MouseEventArgs e)
    {
        if (Control.MouseButtons == MouseButtons.None)
            base.OnMouseUp(e);
    }
}
like image 124
Reza Aghaei Avatar answered Oct 23 '25 17:10

Reza Aghaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!