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

Kal*_*exx 7 c# contextmenu winforms

在我的应用程序中,我有一个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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

Han*_*ant 18

 menu.Show(this, e.Location, LeftRightAlignment.Right);
Run Code Online (Sandbox Code Playgroud)

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

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

 Point pos = this.PointToClient(Cursor.Position);
 menu.Show(this, pos, LeftRightAlignment.Right);
Run Code Online (Sandbox Code Playgroud)

你可以随意用grvFieldData 替换.