我已经环顾了一段时间,试图找到一个可行的解决方案,但我想问一个问题:
我的应用程序中的对话框表单中有一个 DataGridView,我希望右键单击单元格时显示一个 ContextMenu。
我右键单击,ContextMenu 看起来很好,但是无论我在 StackExchange 上尝试什么解决方案,它总是会偏移很多。
这与表单和/或其父项有关吗?或者我只是愚蠢地错过了一些东西?
谢谢
杰米
Form.cs
private void dataGridContents_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
Debug.WriteLine("Cell right clicked!");
DataGridViewCell cell = (sender as DataGridView)[e.ColumnIndex, e.RowIndex];
contextCell.Show(cell.DataGridView, PointToClient(Cursor.Position));
if (!cell.Selected)
{
cell.DataGridView.ClearSelection();
cell.DataGridView.CurrentCell = cell;
cell.Selected = true;
}
}
}
}
Edit
抱歉,我已经尝试过:
new Point(e.X, e.Y)
new Point(e.Location.X, e.Location.Y)
new Point(MousePosition.X, MousePosition.Y)
PointToClient(e.X, e.Y)
new Point(Cursor.Position.X, Cursor.Position.Y)
Control.MousePosition
Cursor.Position
可能还有其他一些。
Edit 2
这就是我所说的偏移的意思 - 一些解决方案会导致此偏移在一定程度上变化(有些非常远等) - 但所有解决方案都会像实际光标一样进行偏移。
Edit 3
My contextCell
is a new ContextMenu()
选项1:显示行上下文菜单的最简单解决方案是将上下文菜单分配给RowTemplate.ContextMenuStrip
DataGridView 的属性:
dataGridView1.RowTemplate.ContextMenuStrip = contextMenuStrip1;
选项2:另外,如果您想在显示之前选择单元格ContextMenuStrip
,足以处理CellContextMenuStripNeeded
event:
private void dataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
e.ContextMenuStrip = contextMenuStrip1;
}
}
你犯了什么错?
您正在计算鼠标在DataGridView
以错误的方式。您正在使用PointToClient
意思是this.PointToClient
,而你需要使用的方法DataGridView
, 例如dataGridView1.PointToClient
:
myContextMenu.Show(dataGridView1,dataGridView1.PointToClient(Cursor.Position));
仅供您参考,您可以简单地显示ContextMenu
使用此代码,无需使用ContextMenuStrip
.
但我强烈建议你使用ContextMenuStrip
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)