3

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

Joan Venge
  • 315,713
  • 212
  • 479
  • 689

2 Answers2

6

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;
 };
L.B
  • 114,136
  • 19
  • 178
  • 224
  • Thanks, it works. it tells me that I can only award the points in 20 hours. So will do then. – Joan Venge Oct 23 '11 at 22:56
  • @EdS.: What do you mean by that? I thought it was a custom control inheriting from ListView, no? – Joan Venge Oct 24 '11 at 17:47
  • 3
    [UserControl](http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol.aspx) is actually a .NET class used to house multiple controls, i.e., a composite control. In this case, you have a *user defined* type that inherits from `ListView`. I was being a bit pedantic, but I thought it was worth a mention since the term `UserControl` actually has a different meaning. – Ed S. Oct 24 '11 at 17:52
  • @EdS.:Thanks Ed, I see what you mean now. – Joan Venge Oct 24 '11 at 18:09
0

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

  • 1
    With a bit more rep, [you will be able to flag duplicate questions like this](https://stackoverflow.com/privileges/comment). Until then, posting links as answers is not really ideal, and they will generally be deleted. Or, if the question is not a duplicate, *tailor the answer to this specific question*. – Nathan Tuggy Sep 14 '17 at 07:45