2005. november 5., szombat

How to disable/ enable a menu item depending on the user and his password


Problem/Question/Abstract:

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.

function Tform1.FindMenuItemByTag(atag: Integer): TMenuItem;

  function FindItems(anItem: TMenuItem; aTag: Integer): TMenuItem;
  var
    i: Integer;
  begin
    Result := nil;
    if Assigned(anItem) then
    begin
      if anItem.Tag = aTag then
        Result := anItem
      else
      begin
        for i := 0 to anItem.Count - 1 do
        begin
          Result := FindItems(anItem[i], aTag);
          if Assigned(result) then
            Break;
        end;
      end;
    end;
  end;

begin
  if Assigned(Menu) then
    Result := FindItems(Menu.Items, atag)
  else
    Result := nil;
end;

Nincsenek megjegyzések:

Megjegyzés küldése