Search code examples
c#.netformsdatagridview

PointToScreen doesn't calculates the X value of a column in a DataGridView


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?


Solution

  • 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);
        }
    }