procedure TForm1.Button1Click(Sender: TObject); var o: TComponent; i, j: Integer; maxLevel: Integer; begin maxLevel := 0; for i := 0 to ComponentCount - 1 do if Components[i] is TMenuItem then begin o := Components[i]; j := 0; while TMenuItem(o).Parent <> nil do begin o := TMenuItem(o).Parent; Inc(j); end; if j > maxLevel then maxLevel := j; end; ShowMessage(IntToStr(maxLevel)); o := FindComponent('mmExample'); if o is TMenuItem then ShowMessage((o as TMenuItem).Caption); end;
to d983074(d983074) : TMenuItem好像没有Find方法呀
楼主是要找TMenuItem.Name还是TMenuItem.Caption为‘mmExample’的? 如果是Name,则用上面的FindComponent; 如果是Caption,则: for i := 0 to ComponentCount - 1 do if Components[i] is TMenuItem then if (Components[i] as TMenuItem).Caption = 'mmExample' then ...
怎么可能?(D6 enterprise) Locates a menu item in the Items property array given its caption.function Find(ACaption: string): TMenuItem;DescriptionUse Find to locate the menu item in the Items property array with the caption specified by the ACaption parameter. Find ignores accelerator characters when comparing item captions to the ACaption parameter.Find returns the first menu item in the Items property array with the specified caption, or, if no item is found, nil.
to sysu(死树) :高手!
to d983074(d983074) : 不好意思,找到了,以caption作为依据不符合我的要求!
sysu(死树) 的遍历不如这样的快 var mi:tmenuitem; i, j: Integer; maxLevel: Integer; ... maxLevel:=0; for I := 0 to MenuItem1.Count-1 do begin mi:=MenuItem1.Items[I]; while mi.parent<>nil do begin mi:=mi.parent; inc(j); end; maxLevel:=max(maxLevel,j); end;
2.function Find(ACaption: string): TMenuItem;
var
o: TComponent;
i, j: Integer;
maxLevel: Integer;
begin
maxLevel := 0;
for i := 0 to ComponentCount - 1 do
if Components[i] is TMenuItem then begin
o := Components[i];
j := 0;
while TMenuItem(o).Parent <> nil do begin
o := TMenuItem(o).Parent;
Inc(j);
end;
if j > maxLevel then maxLevel := j;
end;
ShowMessage(IntToStr(maxLevel)); o := FindComponent('mmExample');
if o is TMenuItem then
ShowMessage((o as TMenuItem).Caption);
end;
如果是Name,则用上面的FindComponent;
如果是Caption,则:
for i := 0 to ComponentCount - 1 do
if Components[i] is TMenuItem then
if (Components[i] as TMenuItem).Caption = 'mmExample' then
...
Locates a menu item in the Items property array given its caption.function Find(ACaption: string): TMenuItem;DescriptionUse Find to locate the menu item in the Items property array with the caption specified by the ACaption parameter. Find ignores accelerator characters when comparing item captions to the ACaption parameter.Find returns the first menu item in the Items property array with the specified caption, or, if no item is found, nil.
var
mi:tmenuitem;
i, j: Integer;
maxLevel: Integer;
...
maxLevel:=0;
for I := 0 to MenuItem1.Count-1 do
begin
mi:=MenuItem1.Items[I];
while mi.parent<>nil do
begin
mi:=mi.parent;
inc(j);
end;
maxLevel:=max(maxLevel,j);
end;