繁体   English   中英

为什么我的WinForms上下文菜单没有出现在鼠标所在的位置?

[英]Why does my WinForms context menu not appear where the mouse is?

在我的应用程序中,我有一个DataGridView ,用于配置一些选项。 我们的想法是您可以在第一列中输入您想要的任何文本,但如果您右键单击它将为您提供明确支持的值。 我需要它是一个文本框而不是下拉列表,因为我需要支持编辑无效(或旧)配置。

我想要的是用户右键单击字段名称列,并根据这是什么类型的配置有一个有效的上下文菜单。 因此,我编写了以下事件

    private void grvFieldData_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        // If this is a right click on the Field name column, create a context menu 
        //   with recognized options for that field
        if (e.Button == MouseButtons.Right && grvFieldData.Columns[e.ColumnIndex].Name == "clmFieldName")
        {
            ContextMenu menu = new ContextMenu();

            if (_supportedDataGrids.ContainsKey((cmbDataGrid.SelectedItem as DataGridFieldList).GridName))
            {
                // Loop through all the fields and add them to the context menu
                List<string> fields = _supportedDataGrids[((cmbDataGrid.SelectedItem as DataGridFieldList).GridName)];
                fields.Sort();

                foreach (string field in fields)
                    menu.MenuItems.Add(new MenuItem(field));

                // Make sure there is at least one field before displaying the context menu
                if (menu.MenuItems.Count > 0)
                    menu.Show(this, e.Location, LeftRightAlignment.Right);
            }
        }
    }

这工作“正确”,但上下文菜单出现在窗体的顶部,而不是鼠标指针所在的位置。 如果我更改Show()调用以使用DataGridView而不是表单,我有相同的问题,但它出现在网格的左上角,而不是鼠标的位置。

奇怪的是,如果我改变了事件的MouseClick事件(而不是CellMouseclick事件)的一切工作和出现的上下文菜单的确切位置,鼠标指针。 此选项的问题是用户可能没有右键单击当前选定的单元格,这意味着当他们单击菜单项时,将更改所选单元格而不是他们右键单击的单元格。

有没有人有任何提示为什么使用CellMouseClick创建的上下文菜单没有显示在正确的位置?

 menu.Show(this, e.Location, LeftRightAlignment.Right);

第二个参数是鼠标位置,相对于单元格的左上角。 按照编程,您可以相对于此形式创建偏移量,这将使菜单显示在表单的左上角。 使用DGV作为第一个参数也不起作用,现在它位于网格的左上角。

有几种方法可以解决这个问题,但这是一种简单的方法:

 Point pos = this.PointToClient(Cursor.Position);
 menu.Show(this, pos, LeftRightAlignment.Right);

你可以随意用grvFieldData替换

在datagridview鼠标单击事件中:

if e.button= mousebutton.right 
{
   contextmenu1.Show(MousePosition);
}

尝试使用PointToClient获取正确的位置

它没有显示在正确的位置,因为e.Location是相对于父对象左上角的位置,在这种情况下是单元本身。 位置属性始终相对于其容器。

要获取鼠标光标相对于表单本身左上角的位置,可以使用

this.PointToClient(Cursor.Position);

我已经解决了这个问题......有人会发现这个方法很奇怪,但它运行正常!)如果我们想在datagridview单元格中按右键btn同时看到一个上下文菜单,就在那里,而不是在屏幕中间或者在其他地方,我们需要:

做一些变数

int x=0;
int y=0;

为datagridview1做一个'MouseMove'事件lke:

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
   x = e.X;
   y = e.Y;
}

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
   if (e.Button == System.Windows.Forms.MouseButtons.Right)
   {
      contextMenuStrip1.Show(dataGridView1, x,y);
   }
}

别客气

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM