Using one click event for menu items.

Started by
2 comments, last by Nypyren 6 years, 1 month ago

protected void menuImage_ChildClick(Object sender, EventArgs e)
{
    if(pbxPhoto.Image != null && sender is MenuItem)
    {
        MenuItem mi = (MenuItem)sender;
        pbxPhoto.SizeMode = modeMenuArray[mi.Index];
        pbxPhoto.Invalidate(); 
    }
}

I'm trying to make one click function to handle multiple menus. Using this code does not work when I click the menu buttons after the image is loaded in the picture box. Here is where I set the event handler of both menu items. 


// 
            // menuStretch
            // 
            this.menuStretch.Name = "menuStretch";
            this.menuStretch.Size = new System.Drawing.Size(152, 22);
            this.menuStretch.Text = "S&tretch to Fit";
            this.menuStretch.Click += new System.EventHandler(this.menuImage_ChildClick);
            // 
            // menuActual
            // 
            this.menuActual.Name = "menuActual";
            this.menuActual.Size = new System.Drawing.Size(152, 22);
            this.menuActual.Text = "&Actual Size";
            this.menuActual.Click += new System.EventHandler(this.menuImage_ChildClick);

Menu Stretch and Menu Actual are ToolStripMenuItems, which don't have an index variable as I've noticed. How do I get this to work? Otherwise I have to make a separate event function per menu item, which, depending on the amount of image properties, could be a a lot. 

Advertisement

In the sender argument you have the instance of whatever fired the event so you already have the object that was responsable for it. What you now need to do is to identify it, by name, by tag or whatever is up to you

You could possibly use a Dictionary<object, SizeMode> instead of your array.  Use the menu item or whatever other kind of object as the dictionary key.  Otherwise the code could look pretty much like what you're doing with the array.

You'll just have to fill out the dictionary somehow before you click things.  Maybe in your form constructor or whatever.

This topic is closed to new replies.

Advertisement