2016-02-29 41 views
1

我想學習如何使用此代碼時使用的ContextMenuStripContextManuStripTool.show()的位置是錯誤的

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

我看到菜單在正確的位置彈出

但是當我改爲使用此代碼:

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

     } 

    } 

我看到在頂部的菜單彈出我DataGridView

左上角我知道這是因爲我曾嘗試設置其他控制沒有成功 的toolStrip.Show方法什麼是正確的辦法讓我的點擊位置

回答

1

隨着的DataGridViewCellMouseEventArgs 操作ColumnHeaderMouseClick事件,您不必測試獲取點擊的列是否使用該HitTest方法。此外,我認爲座標是相對於被點擊的列,所以你可以嘗試使用GetColumnDisplayRectangle函數來抵消它的屬性:

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