在我的应用程序中,我有一个DataGridView
,用于配置某些选项。这个想法是,你可以在第一列输入你想要的任何文本,但如果你右键点击它会给你显式支持的值。我需要这是一个文本框而不是下拉列表,因为我需要支持编辑无效(或旧)配置。为什么我的WinForms上下文菜单不出现在鼠标所在的位置?
我想要的是用户在字段名称列中右键单击并具有基于这是什么类型的配置有效的上下文菜单。因此,我编写了以下事件
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
创建的上下文菜单没有显示在正确的位置?
嘿,我的答案会稍微复杂一些X和Y坐标的添加。我希望我几周前知道Cursor.Position!为简单起见+1! – Yetti 2011-02-23 17:17:00
真棒,那就像一个魅力! 'Cursor.Position'是我错过的! – KallDrexx 2011-02-23 17:20:29