Author: Jonas Bilinkevicius
I want to enable/ disable the menu items of a TMainMenu according to the user and
his password. With the property Items I can only reach the subitems of each one of
the main items. Is it possible to process all the items (independently of its
parent) by its Name or Tag property?
Answer:
Well, this is basically a lookup task. If all the menu items are created at
design-time the form will have fields for them and you can find them by name using
the forms FindComponent method, using the menu items Name property. If you want to
find items by Tag value you have to iterate either over the menu items
(recursively) , starting at the forms Menu property, or over the forms Components
array, looking for components of class TMenuitem.
1 2 function Tform1.FindMenuItemByTag(atag: Integer): TMenuItem;
3 4 function FindItems(anItem: TMenuItem; aTag: Integer): TMenuItem;
5 var6 i: Integer;
7 begin8 Result := nil;
9 if Assigned(anItem) then10 begin11 if anItem.Tag = aTag then12 Result := anItem
13 else14 begin15 for i := 0 to anItem.Count - 1 do16 begin17 Result := FindItems(anItem[i], aTag);
18 if Assigned(result) then19 Break;
20 end;
21 end;
22 end;
23 end;
24 25 begin26 if Assigned(Menu) then27 Result := FindItems(Menu.Items, atag)
28 else29 Result := nil;
30 end;