ListView上的按钮覆盖隐藏在MouseMove上

时间:2014-02-05 00:07:23

标签: c# winforms listview button overlay

在ListView控件的详细视图中,我需要编辑光标指向的条目的其他功能,所以我只需在ListView控件上添加一个按钮覆盖。

以下代码用于在光标位于ListView控件上时显示ListView控件的详细信息视图的每个单元格最右侧的按钮。 为了确定悬停的是哪个细胞,使用了HitTest方法。

问题是,只有当光标位于按钮应显示的矩形区域时,按钮才会正确显示。换句话说,当光标位于任何字段的非最右边区域时,在ListView控件中会发生重绘并删除按钮(以及单元格的内容)。此外,BringToFront方法不起作用。 如何纠正这种行为?

class DocumentView {
    Button btn = new Button();
    ListView lv; // designer-generated

    public DocumentView(Document doc)
    {
        btn.AutoSize = true;
        btn.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        btn.AutoEllipsis = false;
        btn.Hide();
        this.Controls.Add(btn);
        InitializeComponent();
    }

    ListViewItem mouseMoveHitTestItem = null;
    ListViewItem.ListViewSubItem mouseMoveHitTestSubItem = null;
    int iCol_MouseMove = -1;
    int iRow_MouseMove = -1;
    private void lv_MouseMove(object sender, MouseEventArgs e)
    {
        var mousePos = lv.PointToClient(Control.MousePosition);
        var hitTest = lv.HitTest(mousePos);
        mouseMoveHitTestItem = hitTest.Item;
        mouseMoveHitTestSubItem = hitTest.SubItem;
        if (mouseMoveHitTestItem != null)
        {
            var iCol = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            var iRow = hitTest.Item.Index;
            if (iCol != iCol_MouseMove || iRow != iRow_MouseMove)
            { //Reposition button if the cursor moved to a different cell
                var bounds = hitTest.SubItem.Bounds;
                btn.SetBounds(
                    bounds.Right - btn.Width + lv.Left,
                    bounds.Top + lv.Top,
                    bounds.Width, bounds.Height);

                if (!btn.Visible)
                {
                    btn.Show();
                    btn.BringToFront();
                }
                btn.Text = "" + iRow + ", " + iCol; //test hittest row, col calc.
            }                
        }
        btn.BringToFront(); //takes no effect
    }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

错过了状态更新,因此每个MouseMove都发生了无效:

                btnAddName.SetBounds(
                    bounds.Right - btnAddName.Width + lvVertices.Left,
                    bounds.Top + lvVertices.Top,
                    bounds.Width, bounds.Height);

                //-->
                iColBtnAdd = iCol;
                iRowBtnAdd = iRow;
                //<--

                if (!btnAddName.Visible)
                {  

警告有帮助。 (CS0169)