Get the SourceControl of a DropDownMenu

可紊 提交于 2019-12-17 21:32:58

问题


I have two click events of menu items in a ContextMenuStrip.
I can get the SourceControl of the clicked context menu item by doing this code:

Control c = ((sender as ToolStripItem).Owner as ContextMenuStrip).SourceControl;

But when I use this code on a context menu item that is in another level it, returns null.

How can I get the SourceControl in the click event of the second screenshot's menu item?


回答1:


The ContextMenuStrip SourceControl (the reference of the current Control where the Context Menu is activated) can be retrieved, from a ToolStripMenuItem, inspecting the OwnerItem reference and moving upstream until the OwnerItem reference is null, then inspecting the Owner value, which references the ContextMenuStrip.
(Unfortunately, the SourceControl reference is only available in the ContextMenuStrip control).

A simple alternative method is using a Field that references the Control where the current ContextMenuStrip has been activated (you can have just one active ContextMenuStrip).
This Field reference, set when the ContextMenuStrip is opened - by subscribing to the Opened() event - can then be accessed by any of the ToolStripMenuItem.
The Field reference is then set back to null when then ContextMenuStrip is closed.

An example:
(toolStripMenuItem is a generic name, it must be set to an actual control name).

Control CurrentContextMenuOwner = null;

private void contextMenuStrip1_Opened(object sender, EventArgs e)
{
    CurrentContextMenuOwner = (sender as ContextMenuStrip).SourceControl;
}

private void toolStripMenuItem_Click(object sender, EventArgs e)
{
    CurrentContextMenuOwner.BackColor = Color.Blue;
    //(...)
}

private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
    CurrentContextMenuOwner = null;
}


来源:https://stackoverflow.com/questions/53261340/get-the-sourcecontrol-of-a-dropdownmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!