3

当我右键单击 ListView 列标题时,我显示一个不同的 ContextMenuStrip,另一个在 ListView 内。

class ListViewExx : ListView
{
    public ContextMenuStrip HeaderContextMenu { get; set; }
    int contextMenuSet = 0;
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        base.WndProc(ref m);
        switch(m.Msg)
        {
            case 0x210: //WM_PARENTNOTIFY
                contextMenuSet = 1;
                break;
            case 0x21:  //WM_MOUSEACTIVATE
                contextMenuSet++;
                break;
            case 0x7b:  //WM_CONTEXTMENU
                if(contextMenuSet == 2 && HeaderContextMenu != null)
                    HeaderContextMenu.Show(Control.MousePosition);
                break;
        }
    }
}

这很好用。问题是我第一次在 ListView 内右键单击 - 显示了标题 contextMenuStrip。

4

2 回答 2

5

依赖激活状态太hacky了。更简单的是,WM_CONTEXTMENU 消息传递生成消息的窗口句柄。因此,您可以简单地将其与列表视图的句柄进行比较。如果它不匹配,那么你知道它是标题控件:

protected override void WndProc(ref System.Windows.Forms.Message m)
{
    base.WndProc(ref m);
    if (m.Msg == 0x7b) {  //WM_CONTEXTMENU
        if (m.WParam != this.Handle) HeaderContextMenu.Show(Control.MousePosition);
    }
}

从技术上讲,您应该使用 LVM_GETHEADER 但这应该可以正常工作。

于 2013-07-24T17:09:50.063 回答
1

我试图找到一种干净的方法来Column Header Rectangle检查ListView用户右键单击的点是否在 a 中Column Header。但是,我刚刚发现Column Header RectangleaListView似乎只在DrawColumnHeader事件处理程序中显示。这个解决方案是我能想到的所有可以帮助你的方法:

public class CustomListView : ListView
{
    //This contains the Column Index and its corresponding Rectangle in screen coordinates.
    Dictionary<int, Rectangle> columns = new Dictionary<int, Rectangle>();
    public CustomListView()
    {
        OwnerDraw = true;//This will help the OnDrawColumnHeader be called.
    }
    protected override void OnDrawItem(DrawListViewItemEventArgs e)
    {
        e.DrawDefault = true;
        base.OnDrawItem(e);
    }
    protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e)
    {
        e.DrawDefault = true;
        base.OnDrawSubItem(e);
    }
    protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e)
    {
        columns[e.ColumnIndex] = RectangleToScreen(e.Bounds);
        e.DrawDefault = true;
        base.OnDrawColumnHeader(e);
    }
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x7b)//WM_CONTEXTMENU
        {
            int lp = m.LParam.ToInt32();
            int x = ((lp << 16) >> 16);
            int y = lp >> 16;
            foreach (KeyValuePair<int, Rectangle> p in columns)
            {
                if (p.Value.Contains(new Point(x, y)))
                {
                    //MessageBox.Show(Columns[p.Key].Text); <-- Try this to test if you want.
                    //Show your HeaderContextMenu corresponding to a Column here.
                    break;
                }
            }                
        }
        base.WndProc(ref m);
    }
}
于 2013-07-24T17:27:34.393 回答