用Delphi编程控制IE浏览器的窗口

来源:互联网 发布:删除多余的网络连接 编辑:程序博客网 时间:2024/05/21 17:30
程序说明

  本程序用于打开IE、链接到指定的网页、获取IE地址栏中的URL地址信息及该窗口名称、激活最近打开的窗口以及关闭最近打开的窗口。程序的界面如图1:

  设计思想

  使用Delphi编程控制IE的方法有多种,在本程序中使用DDE来控制IE,应注意须先确保IE已经运行,因为此时IE要作为DDE服务器,用户的程序只能作DDE客户端,而DDE客户端无法与一个没有运行的服务器进行数据交换。在本程序中调用API函数ShellExecute来打开IE。


图1

  在本程序中使用DDE客户端时用到了类TDdeClientConv的以下几个函数及过程:

  function SetLink(Service:String;Topic:String):Boolean;

  function OpenLink:Boolean;

  function RequestData(const Item:String):Pchar;

  procedure CloseLink;

  其中,参数Service为DDE服务器的ApplicationName,对IE来说就是Iexplore;参数Topic是DDE会话的TopicName,不同功能对应的Topic不同;参数Item为会话的ItemName,也因功能不同而不同。函数SetLink用来设置会话主题,若成功返回True,否则返回False;函数RequestData用来返回会话的数据。

  设计步骤

  新建一个应用程序,为窗体加入两个Edit组件、6个Button组件。各组件属性如图2:


图2

  在uses中加入对DDEman,ShellAPE和ComObj单元的引用,并定义一个TDdeClientConv类型的全局变量DDE。

  编写相关代码

  ......

  var DDE:TDdeClientConv;

  //DDE为客户端全局变量

  implementation

  {R *.DFM}

  //创建窗体时创建DDE客户端

  procedure TForm1.FormCreate(Sender: TObject);

  begin

  DDE:=TDdeClientConv.Create(Self);

  end;

  //单击Open IE启动默认浏览器并自动打开指定的网页(若IE不是默认浏览器,需手工打开)

  procedure TForm1.Button3Click(Sender: TObject);

  begin

  //调用ShellExecute打开默认浏览器,将窗口模式设为SW_SHOWNORMAL

  ShellExecute(Handle,nil,PChar('www.chinaren.com/index.shtml'),nil,nil,SW_SHOWNORMAL);

  end;

  //单击Get URL按钮获取IE地址栏URL以及对应窗口标题

  procedure TForm1.Button1Click(Sender: TObject);

  begin

  //设置会话连接成功

  if DDE.SetLink('Iexplore', 'WWW_GetWindowInfo') then

  begin

  DDE.OpenLink;

  //返回信息并在组件Edit1中显示

  Edit1.Text:=DDE.QequestData('-1');

  DDE.CloseLink;

  end

  else

  ShowMessage('IE没在运行');

  end;

  //单击Open URL按钮链接到指定网页

  procedure TForm1.Button2Click(Sender: TObject);

  begin

  if DDE.SetLink('Iexplore', 'WWW_

  OpenURL') then

  begin

  //链接到指定Web页

  DDE.OpenLink;

  DDE.RequestData(Edit2.Text);

  DDE.CloseLink;

  end

  else

  ShowMessage('IE没在运行');

  end;

  //单击Activate IE按钮激活最近打开的IE窗口

  procedure TForm1.Button4Click(Sender: TObject);

  begin

  if DDE.SetLink('Iexplore', 'WWW_Activate') then

  begin

  DDE.OpenLink;

  DDE.RequestData('-1');

  DDE.CloseLink;

  end

  else

  ShowMessage('IE没有运行');

  end;

  //单击Close IE按钮关闭最近打开的IE窗口

  procedure TForm1.Button5Click(Sender: TObject);

  begin

  if DDE.SetLink('Iexplore', 'WWW_Exit') then

  begin

  DDE.OpenLink;

  DDE.RequestData('WWW_Exit');

  DDE.CloseLink;

  end

  else

  ShowMessage('IE没有运行');

  end.

原创粉丝点击