简体   繁体   English

从另一个线程启用/禁用菜单项

[英]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. 我可以在其他控件上使用InvokeRequired / Invoke,但是由于菜单项不是Control,因此很难实现相同的功能。

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 谢谢,-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. 另外,顺便说一句,您正在使用的Control.Invoke的重载有第二个参数标记为params []-这是c#如何填充可变数量的参数。 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. 更好,我敢肯定你会同意的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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