简体   繁体   中英

Enabling/Disabling the menu item from another thread

I am trying to change a menu item from another thread. I am able to use the InvokeRequired/Invoke on other controls, but since the menu item is not a Control, I am having difficulty in achieving the same functionality.

For other controls, I am doing this:

private delegate void SetControlEnableHandler(object sender, Boolean bValue);

private void SetControlEnabled(object sender, Boolean bValue)
{
  Control control = (Control)sender;
  if (control.InvokeRequired)
    control.Invoke(
        new SetControlEnableHandler(SetControlEnabled),
        new object[] { sender, bValue }
    );
  else
    control.Enabled = bValue;
}

From the worker thread I simple call:

this.SetControlEnabled(btnPress, true);

and it does the job.

Can anyone help me with the menu item here?

Thank You, -Bhaskar

The menu item is not a control, but the Form hosting the menustrip is. So, a method in that form can modify the menuitem, if called in the correct thread.

so,

private void EnableMenuItem(ToolStripMenuItem item, bool enabled)
    {
        this.BeginInvoke(new MethodInvoker(delegate()
        {
            item.Enabled = enabled;
        }
        ));
    }

will probably do what you want. Note the use of an anonymous method to save have to define a delegate that (probably) isn't going to be used elsewhere.

Also, as an aside, the overload of Control.Invoke that you're using has it's second argument marked with the params [] - this is how c# inplements variable numbers of arguments. You don't have to contstruct an object array, just add as many objects you need as parameters.

For example,

control.Invoke(new SetControlEnableHandler(SetControlEnabled), new object[] { sender, bValue } );

can be written as

control.Invoke( new SetControlEnableHandler(SetControlEnabled), sender, bValue);

It's much nicer, i'm sure you'll agree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM