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.
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.
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.
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.
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"));
});
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With