Search code examples
c#castingcontextmenustrip

How to properly cast ContextMenuStrip C#


I have been reading for many hours now trying to figure out how to properly cast the Context Menu Strip in Visual Studio 2012 using C#. I built a little test application to show you what I am trying to accomplish. Here is a screen shot.

enter image description here

I have assigned the context menu strip to both controls. I can return the control that raised the MenuStrip but if I add another menu item Like in this example (Test) I get "Cant Cast" errors. Here is the code that I am trying to use.

private void testToolStripMenuItem_Click(object sender, EventArgs e)
{
    var item = (ToolStripMenuItem)sender;
    var menu = (ContextMenuStrip)item.Owner;

    MessageBox.Show(menu.SourceControl.Name);
}

Solution

  • Following the possible already answered question link at the top I was finally able to figure it out. I believe doing it this way is much cleaner and simpler anyhow. What I had to do is set an event for the ContextMenuStrip.Opening. On that event you set the Source Control. Here is the code.

        public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private PictureBox p;
    
        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show(p.Name);
        }
    
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            p = ((ContextMenuStrip)sender).SourceControl as PictureBox;
        }
    }