Search code examples
c#winformsdatagridviewmouseeventcontextmenustrip

ContextManuStripTool.show() position is wrong


I'm trying to learn how to use the ContextMenuStrip

when using this code :

private void DG_dataGridView_MouseClick(object sender, MouseEventArgs e)
{
        if (e.Button == MouseButtons.Right)
        {
            var hitTest = DG_dataGridView.HitTest(e.X, e.Y);

            if (hitTest.Type == DataGridViewHitTestType.ColumnHeader)//currentMouseOverRow >= 0)
            {
                string colName = DG_dataGridView.Columns[hitTest.ColumnIndex].Name;
                GlobalParam.Insatance.ClickData = new RightClickData(hitTest, colName);

                RightClickToolStrip.Show(DG_dataGridView, new Point(e.X, e.Y));
            }
        }
}

I see the menu pop up in the right position

but when instead I use this code :

    private void DG_dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {

            var hitTest = DG_dataGridView.HitTest(e.Location.X, e.Location.Y);

            string colName = DG_dataGridView.Columns[e.ColumnIndex].Name;
            GlobalParam.Insatance.CustomMouseGridClickData = new CustomMouseOnGridClickData(e, hitTest.Type, colName);


            RightClickToolStrip.Show(DG_dataGridView, new Point(e.X, e.Y));

        }

    }

I see the menu pop on the top left corner of my DataGridView

I know this is due to the operation of DataGridViewCellMouseEventArgs I have tried to set other control in the toolStrip.Show method without success what is the proper way to get my click position


Solution

  • With the ColumnHeaderMouseClick event, you don't have to test for the column getting clicked or not using that HitTest method. Also, I think the coordinates are relative to the column being clicked, so you can try using the GetColumnDisplayRectangle function to offset it property:

    void DG_dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
      if (e.Button == MouseButtons.Right) {
        if (e.ColumnIndex > -1) {
          Rectangle r = DG_dataGridView.GetColumnDisplayRectangle(e.ColumnIndex, true);
          RightClickToolStrip.Show(DG_dataGridView, r.Left + e.X, r.Top + e.Y);
        }
      }
    }