我正在尝试在我右键单击鼠标的位置打开contextmenustrip
,但它始终显示在屏幕的左上角。
以下是我使用的代码:
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Show(new Point(e.X,e.Y));
doss.getdossier(connection.conn, Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value));
}
}
答案 0 :(得分:11)
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Show(Cursor.Position);
}
它没有出现的原因是因为你使用e.X和e.Y作为值。它们不是屏幕上的实际位置。它们是数据网格中鼠标的位置。所以说你点击了第一行的第一个单元格,它将靠近该组件的左上角。 e.X和e.Y是组件内的鼠标位置。
答案 1 :(得分:2)
假设您使用的是Windows窗体,请尝试以下操作:
if (e.Button == MouseButtons.Right)
{
Control control = (Control) sender;
// Calculate the startPoint by using the PointToScreen
// method.
var startPoint = control.PointToScreen(new Point(e.X, e.Y));
contextMenuStrip1.Show(startPoint);
...
...