借助 TWebBrowser 可以把軟件做的更漂亮、更靈活, 很多軟件已經或者早就這樣做了.
盡管 HTML DOM 內容繁雜(涉及到 HTML、JavaScript、CSS), 但也都屬於 TWebBrowser 的功能范圍.
使用 TWebBrowser 時, 如果配合上 MSHTML, 將會有很好的代碼提示; 不然也可以, 就是寫代碼困難.
HTML DOM 中的一切都是源於一個叫 window 對象, 為了和 JS 中的 DOM 一致起來, 本次先獲取這個對象.
TWebBrowser 是調用 SHDocVw.dll 的功能並繼承與 TOleControl 類, 會用到 SHDocVw 和 OleCtrls 單元.
另外 window 是 IHTMLWindow2 接口類型的, 此接口定義在 MSHTML 單元.
本例效果圖:
代碼文件:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw, StdCtrls; type TForm1 = class(TForm) WebBrowser1: TWebBrowser; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} uses MSHTML; var window: IHTMLWindow2; {打開一個頁面} procedure TForm1.Button1Click(Sender: TObject); begin WebBrowser1.Navigate('http://del.cnblogs.com'); end; {獲取並試用 window 對象} procedure TForm1.Button2Click(Sender: TObject); begin window := (WebBrowser1.Document as IHTMLDocument2).parentWindow; window.document.body.innerHTML := '<hr>萬一的 Delphi 博客<hr>'; window.alert('JavaScript 的提示: 修改成功!'); end; {初始化} procedure TForm1.FormCreate(Sender: TObject); begin Position := poScreenCenter; WebBrowser1.Align := alTop; Button1.Caption := '打開'; Button2.Caption := '改寫'; end; end.
窗體文件:
object Form1: TForm1 Left = 0 Top = 0 Caption = 'Form1' ClientHeight = 167 ClientWidth = 318 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object WebBrowser1: TWebBrowser Left = 8 Top = 8 Width = 300 Height = 121 TabOrder = 0 ControlData = { 4C000000021F0000810C00000000000000000000000000000000000000000000 000000004C000000000000000000000001000000E0D057007335CF11AE690800 2B2E126208000000000000004C0000000114020000000000C000000000000046 8000000000000000000000000000000000000000000000000000000000000000 00000000000000000100000000000000000000000000000000000000} end object Button1: TButton Left = 154 Top = 135 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 1 OnClick = Button1Click end object Button2: TButton Left = 235 Top = 135 Width = 75 Height = 25 Caption = 'Button2' TabOrder = 2 OnClick = Button2Click end end
從一個外部的 IE 窗口獲取 window 對象也可以:
uses MSHTML, ComObj; var IE: Variant; window: IHTMLWindow2; procedure TForm1.Button1Click(Sender: TObject); begin IE := CreateOleObject('InternetExplorer.Application'); IE.Visible := True; IE.Navigate('http://del.cnblogs.com'); end; procedure TForm1.Button2Click(Sender: TObject); begin window := (IDispatch(IE.document) as IHTMLDocument2).parentWindow; window.document.body.innerHTML := '<hr>萬一的 Delphi 博客<hr>'; end;