Reputation: 173
How is it possible to loop through all ContextMenus within a Windows Form?
What I currently have is:
public void SearchContextMenuStrip(Form Window)
{
foreach (Control item in Window.Controls)
{
if (item is ContextMenuStrip)
{
MessageBox.Show("ContextMenuStrip found!", "ContextMenuStrip found");
}
else
{
}
}
}
This works fine for all other controls but not for the ContextMenus.
I want this to be able to translate all text for a multi language application so if someone knows a better solution for this it is much appreciated.
Thanks in advance!
Upvotes: 0
Views: 691
Reputation: 1164
I think the best solution is using reflection and finding the ContextMenuStrips between all objects. this script will be able to return all ContextMenuStrips.
public static bool IsLastObject(object obj)
{
if (obj == null) return true;
Type type = obj.GetType();
return
type.IsArray ||
type.IsEnum ||
type.IsPointer ||
type.IsAbstract ||
type.IsSealed;
}
public static IEnumerable<Control> GetAllControls(object obj, int maxNests = 25)
{
if (obj == null || maxNests < 0) yield break;
Type type = obj.GetType();
List<Control> list = new List<Control>();
if (obj is Control)
foreach (Control item in ((Control)obj).Controls)
{
list.Add(item);
yield return item;
}
foreach (var item in type.GetFields())
{
var nobj = item.GetValue(obj);
if (nobj == null) continue;
if (nobj is Control && !list.Contains((Control)nobj)) yield return (Control)nobj;
if (IsLastObject(nobj)) continue;
foreach (var ni in GetAllControls(nobj, maxNests - 1))
yield return ni;
}
}
public static IEnumerable<ContextMenuStrip> GetAllToolStrips(object control, int maxNests = 25)
{
foreach (var item in GetAllControls(control, maxNests))
if (item is ContextMenuStrip) yield return (ContextMenuStrip)item;
}
Enjoy...
Upvotes: 0
Reputation: 1806
You can associate just one ContextMenuStrip
to each control so I think you want ToolStripMenuItem
foreach( var item in Window.ContextMenuStrip.Items)
{
}
Upvotes: 1
Reputation: 1999
Use resx file and for each region-language create it with translation. Use the settings.NAME instead of hard coding. Localization will be applied automatically.
https://msdn.microsoft.com/en-us/library/aa992030(v=vs.100).aspx
Upvotes: 0