3

For displaying a context menue at a click into the header of a DataGridView I use:

private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        System.Drawing.Point ptScreen = ((Control)sender).PointToScreen(e.Location);
        cmsSpalten.Show(ptScreen);
    }
}

The Y value is converted fine. But the X value doesn't change at all and the context menue opens always near to the left border of the screen with the offset of the mouse click within the cell.
Why is that so?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
UHM
  • 303
  • 1
  • 7
  • Can you check what control sender is? I assume its the DataGridView but maybe. And while you are add it check if the coordinates in the args seem to fit in relation to the sender control. That would be the precondition that PointToScreen calculates the correct coordinates. – Ralf Aug 29 '23 at 13:43

1 Answers1

1

PointToClient the Cursor.Position instead and pass the SourceControl of the ContextMenuStrip to its Show method.

private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var p = dgv.PointToClient(Cursor.Position);
        cmsSpalten.Show(dgv, p);
    }
}
dr.null
  • 4,032
  • 3
  • 9
  • 12