Joan Venge
Joan Venge

Reputation: 331330

Can I detect if a user right clicked on a ListView column header in Winforms?

I don't mean the inside of the listview items but the column header that allows you to resize the column.

Upvotes: 4

Views: 3015

Answers (2)

Jaroslav Lobačevski
Jaroslav Lobačevski

Reputation: 131

The OnMouseEnter/Leave solution shows the context menu sometimes even not on the header. Here is better solution ListView ContextMenuStrip for column headers

Upvotes: 0

L.B
L.B

Reputation: 116168

A simple UserControl overriding ListView's OnMouseEnter OnMouseLeave & WndProc

public partial class MyListView : ListView
{
    public MyListView()
    {
    }

    public delegate void ColumnContextMenuHandler(object sender, ColumnHeader columnHeader);
    public event ColumnContextMenuHandler ColumnContextMenuClicked = null;

    bool _OnItemsArea = false;
    protected override void OnMouseEnter(EventArgs e)
    {
        base.OnMouseEnter(e);
        _OnItemsArea = true;
    }

    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        _OnItemsArea = false;
    }

    const int WM_CONTEXTMENU = 0x007B;

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_CONTEXTMENU)
        {
            if (!_OnItemsArea)
            {
                Point p = base.PointToClient(MousePosition);
                int totalWidth = 0;
                foreach (ColumnHeader column in base.Columns)
                {
                    totalWidth += column.Width;
                    if (p.X < totalWidth)
                    {
                        if (ColumnContextMenuClicked != null) ColumnContextMenuClicked(this, column);
                        break;
                    }
                }
            }
        }
        base.WndProc(ref m);
    }
}

and the usage

 myListView1.ColumnContextMenuClicked += (sndr, col) =>
 {
    this.Text = col.Text;
 };

Upvotes: 7

Related Questions