Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke ToolStripMenuItem

I'm trying to figure out if there's a way to Invoke ToolStripMenuItem.

For example,I am calling a web service(ASynchrously) when result is returned.i populate drop down items according to result,(In call back method)

 ToolStripMenuItem.DropDownItems.Add(new ToolStripItemEx("start"));

but I get exception

Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

There is no invoke function associated with the toolstrip item, Is there another way I can do this? Am I trying to do this the completely wrong way? Any input would be helpful.

like image 884
Zain Ali Avatar asked Aug 22 '11 09:08

Zain Ali


People also ask

What is ToolStripMenuItem?

The ToolStripMenuItem class provides properties that enable you to configure the appearance and functionality of a menu item. To display a check mark next to a menu item, use the Checked property.

How to add click Event to ToolStripMenuItem?

Solution 1. When you add menu items give unique text for them, then you can easily identify which menu item clicked by event sender object. ToolStripMenuItem menu = new ToolStripMenuItem(submenuName); menu. Click += new EventHandler(menu_Click); myToolStripMenuItem.

How do I set up Toolstripitem?

Creating Menu Strips and Tool Strip Menu Items You can create a MenuStrip at design time in the same way that you create any control: by dragging it from the Toolbox onto the design surface. Once it has been added to the design surface, an interface for creating tool strip menu items appears.


2 Answers

You are trying to execute code that rely on control main thread in another thread, You should call it using Invoke method:

toolStrip.Invoke(() =>
{
    toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));
});

When accessing controls members/methods from a thread that is different from thread that the control originally created on, you should use control.Invoke method, it will marshal the execution in the delegate of invoke to the main thread.

Edit: Since you are using ToolStripMenuItem not ToolStrip, the ToolStripMenuItem doesn't have Invoke member, so you can either use the form invoke by "this.Invoke" or your toolStrip its parent "ToolStrip" Invoke, so:

toolStrip.GetCurrentParent().Invoke(() =>
{
    toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));
});
like image 154
Jalal Said Avatar answered Oct 19 '22 10:10

Jalal Said


You are trying to access the menu item from a thread rather than the main thread, so try out this code:

MethodInvoker method = delegate
{
    toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));
};

if (ToolStripMenu.InvokeRequired)
{
    BeginInvoke(method);
}
else
{
    method.Invoke();
}
like image 32
Sara S. Avatar answered Oct 19 '22 12:10

Sara S.