Delphi获取外部程序菜单并模拟点击菜单


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ComCtrls;

type
  TForm1 = class(TForm)
   TreeView1: TTreeView;
   BitBtn1: TBitBtn;
   procedure BitBtn1Click(Sender: TObject);
   procedure TreeView1DblClick(Sender: TObject);
  private
   hnotepad: THandle;
   procedure AddChildMenus(pnd:TTreenode;m:hMenu);
  public
   { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.AddChildMenus(pnd:TTreenode;m:hMenu);
VAR
  i,id:integer;
  nd:TTreenode;
  MText : ARRAY[0..255] OF Char;
begin
  for i:=0 to GetMenuItemCount(m)-1 do begin
  Id := Integer(GetMenuItemID(m, i));
  GetMenuString(m, i, MText, 255, MF_BYPOSITION);
  if id = -1 then begin
   nd:=Treeview1.items.AddChild(pnd, mText);
   AddChildMenus(nd, GetSubMenu(m, i));
  end
  else if length(Trim(MText)) > 0 THEN
   Treeview1.items.AddChildObject(pnd, Format('%s {ID=%d}',[MText, Id]), Pointer(Id));
  END;
END;

procedure TForm1.BitBtn1Click(Sender: TObject);
var
  root:TTreenode;
begin
  hnotepad:=FindWindow(nil, '记事本');
  if hnotepad <> 0 then
  if GetMenu(hnotepad) <> 0 then begin
   root:=Treeview1.items.Add(nil, 'Main Menu');
   AddChildMenus(root, GetMenu(hnotepad));
   Treeview1.FullExpand;
   Refresh;
  end;
end;

procedure TForm1.TreeView1DblClick(Sender: TObject);
begin
  BringWindowToTop(hNotePad);
  PostMessage(hNotePad,WM_COMMAND,Integer(Treeview1.Selected.Data), 0);
end;

end.


联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678