c#判断右键菜单(ContextMenuStrip)是从哪个控件弹出来的方法

1.方法一:在contextMenuStrip1打开时获取控件名称

双击contextMenuStrip1在它的opening事件中写入下面的代码:

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
string whichcontrol_name= (sender as ContextMenuStrip).SourceControl.Name;
MessageBox.Show(whichcontrol_name);
}

————————————————

2.方法二:目前不是很懂

private void MenuViewDetails_Click(object sender, EventArgs e)
{
// Try to cast the sender to a ToolStripItem
ToolStripItem menuItem = sender as ToolStripItem;
if (menuItem != null)
{
// Retrieve the ContextMenuStrip that owns this ToolStripItem
ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip;
if (owner != null)
{
// Get the control that is displaying this context menu
Control sourceControl = owner.SourceControl;
}
}
}
————————————————

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/u014683488/article/details/106189658

posted @ 2024-09-04 11:46  87obXR  阅读(91)  评论(0编辑  收藏  举报