簡體   English   中英

Position 直接在 DataGridView 單元格上的 Winforms 對話框

[英]Position a Winforms dialog directly over a DataGridView cell

我有一個包含 2 列文件名的 DataGridView。 我想在這些文件名上模擬 Windows 文件資源管理器的“重命名”上下文菜單。 為此,我創建了一個簡單的 WinForms 對話框,其中沒有 header 和一個用於重命名的文本框條目。 我在右鍵單擊網格的文件名單元格時顯示它。 我正在嘗試將 position 直接放在單元格上,但無法讓它顯示在正確的位置。 它向下幾行,向右幾個字符寬度。 我這樣定位對話框:

Point location;
void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) {
    var cellRect = dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
    // Point location = dataGridView.Location;
    location = dataGridView.Bounds.Location;
    location.Offset(cellRect.Location);
    location = dataGridView.PointToScreen(location);
}

async void renameToolStripMenuItem_Click(object sender, EventArgs e) {
    using (var rfd = new RenameFileDialog(fi)) {
      // Lifted from designer
        rfd.ControlBox = false;
        rfd.Text = string.Empty;
        rfd.formBorderStyle = FormBorderStyle.SizableToolWindow;
      // Actually in method
        rfd.StartPosition = FormStartPosition.Manual;
        rfd.Location = location;
        rfd.ShowDialog(dataGridView);
    }
}

我懷疑我被 Location 與 ClientRectangle 與 Control Bounds 或 margins 或 padding 絆倒了,但我無法確定不需要的偏移量來自哪里。 有人可以告訴我如何 position 對話框,或者建議一種在 dataGridView 中模擬 Explorer 的“重命名”的方法嗎?

原罪在這里:

location = dataGridView.Bounds.Location;

要將控件的原點轉換為屏幕坐標,使用控件本身作為相對參考,您必須考慮它自己的原點,它始終為(0, 0) ( Point.Empty )。
如果使用其Location屬性,則需要考慮控件相對於其父項的偏移量。
如果您隨后使用此度量並調用Control.PointToScreen() ,您將在控件的客戶區域內檢索到一個 position
其 ClientRectangle 內的某個位置的偏移量,添加到此度量,然后當然會向右和向下移動(因為控件的原點不在(0, 0)

換句話說,控件原點的屏幕坐標是:

 [Control].PointToScreen(Point.Empty);

Open a Form under a DataGridView中所述,您只需要考慮引發CellMouseDown事件的 Cell 的邊界:

    Point location = Point.Empty;
    private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        var dgv = sender as DataGridView;
        var cellRect = dgv.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
        location = dgv.RectangleToScreen(cellRect).Location;
    }

請注意,在正常情況下, GetCellDisplayRectangle()返回的坐標相對於單元格的網格向右移動 7 個像素並向下移動 1 個像素,因為它考慮了內部邊界
如果你想 position 你的表格超過單元格的網格,你可以添加:

location.Offset(-7, -1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM