首页  编辑  

菜单和可视树相互转换

Tags: /超级猛料/Friends.网友专栏/zswang/函数大全/   Date Created:
(* //
  标题:菜单和可视树相互转换
  说明:支持菜单项和接点添加
  设计:Zswang
  日期:2002-01-24
  支持:wjhu111@21cn.com
  // *)
/// ////Begin Source
function MenuItemToTreeNode(mMenuItem: TMenuItem; mTreeView: TTreeView; mTreeNode: TTreeNode): Boolean;
{ 返回菜单项转换成树节点是否成功 }
var
    I: Integer;
    vTreeNode: TTreeNode;
begin
    Result := False;
    if (not Assigned(mTreeView)) or (not Assigned(mMenuItem)) then
        Exit;
    try
        for I := 0 to Pred(mMenuItem.Count) do
            if mMenuItem[I].Visible then
            begin
                vTreeNode := mTreeView.Items.AddChildObject(mTreeNode, StripHotkey(mMenuItem[I].Caption), mMenuItem[I]);
                // ~~~~~~~~~~~除快捷键
                vTreeNode.ImageIndex := mMenuItem[I].ImageIndex;
                vTreeNode.SelectedIndex := mMenuItem[I].ImageIndex;
                MenuItemToTreeNode(mMenuItem[I], mTreeView, vTreeNode);
            end;
    except
        Exit;
    end;
    Result := True;
end; { MenuItemToTreeNode }

function TreeNodeToMenuItem(mTreeView: TTreeView; mTreeNode: TTreeNode; mMenuItem: TMenuItem): Boolean;
{ 返回树节点转换成菜单项是否成功 }
var
    I, J, K: Integer;
    vMenuItem: TMenuItem;
begin
    Result := False;
    if (not Assigned(mTreeView)) or (not Assigned(mMenuItem)) then
        Exit;
    if Assigned(mTreeNode) then
    begin
        vMenuItem := TMenuItem.Create(mMenuItem.Owner);
        vMenuItem.Caption := mTreeNode.Text;
        vMenuItem.ImageIndex := mTreeNode.ImageIndex;
        vMenuItem.Tag := mTreeNode.Index;
        mMenuItem.Add(vMenuItem);
        for I := 0 to mTreeNode.Count - 1 do
            TreeNodeToMenuItem(mTreeView, mTreeNode[I], vMenuItem);
    end
    else
    begin
        K := -1;
        for I := 0 to mTreeView.Items.Count - 1 do
        begin
            for J := mTreeView.Items[I].Level to K do
                mMenuItem := mMenuItem.Parent;
            vMenuItem := TMenuItem.Create(mMenuItem.Owner);
            vMenuItem.Caption := mTreeView.Items[I].Text;
            vMenuItem.ImageIndex := mTreeView.Items[I].ImageIndex;
            vMenuItem.Tag := I;
            mMenuItem.Add(vMenuItem);
            mMenuItem := vMenuItem;
            K := mTreeView.Items[I].Level;
        end;
    end;
    Result := True;
end; { TreeNodeToMenuItem }

/// ////End Source
/// ////Begin Demo
procedure TForm1.Button1Click(Sender: TObject);
begin
    MenuItemToTreeNode(MainMenu1.Items, TreeView1, nil);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
    TreeNodeToMenuItem(TreeView1, nil, MainMenu1.Items);
end;
/// ////End Demo