gpt4 book ai didi

c# - 单击数据网格的空白部分时防止出现上下文菜单

转载 作者:太空狗 更新时间:2023-10-30 00:11:47 25 4
gpt4 key购买 nike

当在 C# 中右键单击 DataGridView 的空白部分(单击不包含行的网格部分)时,上下文菜单仍会显示基于行的选项。如何仅在点击落在一行上时才显示上下文菜单?

据我所知:

    private void f_context_select_row(object sender, MouseEventArgs e)
{

if (e.Button == MouseButtons.Right)
{

var hti = jobs_datagrid.HitTest(e.X, e.Y);
if (hti.RowIndex >= 0)
{
jobs_datagrid.ClearSelection();
jobs_datagrid.Rows[hti.RowIndex].Selected = true;
}
else
{
//what can I do here to collapse the context menu?
}
}

}

我正在以编程方式构建 Datagrid 和上下文菜单,如下所示:

                    //on right click select row
jobs_datagrid.MouseDown += new MouseEventHandler(f_context_select_row);

//generate context menu
ContextMenuStrip m = new ContextMenuStrip();

ToolStripMenuItem context_datagrid_run = new ToolStripMenuItem("Run All Selected Campaigns");
ToolStripMenuItem context_datagrid_edit = new ToolStripMenuItem("Edit This Campaign");
ToolStripMenuItem context_datagrid_delete = new ToolStripMenuItem("Delete This Campaign");
context_datagrid_delete.Click += f_context_datagrid_delete;
context_datagrid_run.Click += f_run_selected_campaigns;
context_datagrid_edit.Click += f_context_datagrid_edit;

m.Items.Add(context_datagrid_delete);
m.Items.Add(context_datagrid_run);
m.Items.Add(context_datagrid_edit);
jobs_datagrid.ContextMenuStrip = m;

splitContainer3.Panel2.Controls.Add(jobs_datagrid);

最佳答案

ContextMenuStrip.Opening 事件怎么样?

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
var cms = sender as ContextMenuStrip;
var mousepos = Control.MousePosition;
if (cms != null)
{
var rel_mousePos = cms.PointToClient(mousepos);
if (cms.ClientRectangle.Contains(rel_mousePos))
{
//the mouse pos is on the menu ...
//looks like the mouse was used to open it
var dgv_rel_mousePos = dataGridView1.PointToClient(mousepos);
var hti = dataGridView1.HitTest(dgv_rel_mousePos.X, dgv_rel_mousePos.Y);
if (hti.RowIndex == -1)
{
// no row ...
e.Cancel = true;
}
}
else
{
//looks like the menu was opened without the mouse ...
//we could cancel the menu, or perhaps use the currently selected cell as reference...
e.Cancel = true;
}
}
}

关于c# - 单击数据网格的空白部分时防止出现上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9709227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com