Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set the position of a contextmenustrip?

I'm trying to open a contextmenustrip at the place where I right-clicked the mouse, but it always shows at top left of the screen.

Here is the code I used:

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));
    }
}
like image 895
Tarik Mokafih Avatar asked Sep 13 '11 15:09

Tarik Mokafih


2 Answers

if (e.Button == MouseButtons.Right)
{
    contextMenuStrip1.Show(Cursor.Position);
}

the reason it's not appearing is because you are using e.X and e.Y for the values. They are not the actual location on the screen. They are the location of the mouse within the datagrid. So say you clicked on the first cell of the first row, that will be near the top left of that component. e.X and e.Y are the mouse locations within the component.

like image 81
Stuart Thomson Avatar answered Oct 22 '22 12:10

Stuart Thomson


assuming you are in Windows Forms, try this:

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);
  ...
  ...
like image 34
Davide Piras Avatar answered Oct 22 '22 13:10

Davide Piras