开发者

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 = (Co开发者_运维技巧ntrol)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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜