Delphi TWebBrowser


Delphi WebBrowser控件的使用

WebBrowser控件屬性:
1、Application
      如果該對象有效,則返回掌管WebBrowser控件的應用程序實現的自動化對象(IDispatch)。如果在宿主對象中自動化對象無效,程序將返回WebBrowser控件的自動化對象
2、Parent
       返回WebBrowser控件的父自動化對象,通常是一個容器,例如是宿主或IE窗口
3、Containe
       返回WebBrowser控件容器的自動化對象。通常該值與Parent屬性返回的值相同
4、Document
       為活動的文檔返回自動化對象。如果HTML當前正被顯示在WebBrowser中,則Document屬性提供對DHTML Object Model的訪問途徑
5、TopLevelContainer
       返回一個Boolean值,表明IE是否是WebBrowser控件頂層容器,是就返回true
6、Type
       返回已被WebBrowser控件加載的對象的類型。例如:如果加載.doc文件,就會返回Microsoft Word Document
7、Left
       返回或設置WebBrowser控件窗口的內部左邊與容器窗口左邊的距離
8、Top
       返回或設置WebBrowser控件窗口的內部左邊與容器窗口頂邊的距離
9、Width
       返回或設置WebBrowser窗口的寬度,以像素為單位
10、Height
       返回或設置WebBrowser窗口的高度,以像素為單位
11、LocationName
       返回一個字符串,該字符串包含着WebBrowser當前顯示的資源的名稱,如果資源是網頁就是網頁的標題;如果是文件或文件夾 ,就是文件或文件夾的名稱
12、LocationURL
       返回WebBrowser當前正在顯示的資源的URL
13、Busy
       返回一個Boolean值,說明WebBrowser當前是否正在加載URL,如果返回true就可以使用stop方法來撤銷正在執行的訪問操作<br/>

 


WebBrowser控件的事件:

<br/>

1、BeforeNavigate2 導航發生前激發,刷新時不激發

2、CommandStateChange 當命令的激活狀態改變時激發。它表明何時激活或關閉Back和Forward菜單項或按鈕

3、DocumentComplete 當整個文檔完成是激發,刷新頁面不激發

4、DownloadBegin 當某項下載操作已經開始后激發,刷新也可激發此事件

5、DownloadComplete 當某項下載操作已經完成后激發,刷新也可激發此事件

6、 NavigateComplete2 導航完成后激發,刷新時不激發 NewWindow2 在創建新窗口以前激發

7、OnFullScreen 當FullScreen屬性改變時激發。該事件采用VARIENT_BOOL的一個輸入參數來指示IE是全屏顯示方式(VARIENT_TRUE)還是普通顯 示方式(VARIENT_FALSE)

8、OnMenuBar 改變MenuBar的屬性時激發,標示參數是VARIENT_BOOL類型的。VARIANT_TRUE是可見,VARIANT_ FALSE是隱藏

9、OnQuit 無論是用戶關閉瀏覽器還是開發者調用Quit方法,當IE退出時就會激發

10、 OnStatusBar 與OnMenuBar調用方法相同,標示狀態欄是否可見。

11、 OnToolBar 調用方法同上,標示工具欄是否可見。

12、 OnVisible 控制窗口的可見或隱藏,也使用一個VARIENT_BOOL類型的參數

13、StatusTextChange 如果要改變狀態欄中的文字,這個事件就會被激發,但它並不理會程序是否有狀態欄

14、TitleChange 網頁標題有效或改變時激發

例子程序
1、WebBrowser1.OleObject.document.all.item('btnName').click;//根據頁面中按鈕的名稱執行其點擊事件
 
2、WebBrowser1.OleObject.document.getElementByID('btnID').click;//根據按鈕ID點擊
 
3、WebBrowser1.OleObject.document.getElementsByTagName('input').item(0).click;//根據按鈕索引點擊
 
4、WebBrowser1.OleObject.document.all.item('userName').value:=userName;//修改文本框信息,也可用ID,同上
 
5、ShellExecute(0,'open','www.baidu.com',nil,nil,SW_SHOW);//為瀏覽器打開一個網頁

WebBrowser控件的函數:

1、GoBack 相當於IE的”后退”按鈕,使你在當前歷史列表中后退一項

2、GoForward 相當於IE的”前進”按鈕,使你在當前歷史列表中前進一項

3、 GoHome 相當於IE的”主頁”按鈕,連接用戶默認的主頁

4、GoSearch 相當於IE的”搜索”按鈕,連接用戶默認的搜索頁面

5、 Navigate 連接到指定的URL

6、Refresh 刷新當前頁面

7、Refresh2 同上,只是可以指定刷新級別,所指定的刷新級別的值來自RefreshConstants枚舉表,該表定義在ExDisp.h中,可以指定的不同值 如下: REFRESH_NORMAL 執行簡單的刷新,不將HTTP pragma: no-cache頭發送給服務器 REFRESH_IFEXPIRED 只有在網頁過期后才進行簡單的刷新 REFRESH_CONTINUE 僅作內部使用 REFRESH_COMPLETELY 將包含pragma: no-cache頭的請求發送到服務器 <br><br/>

 

初始化和終止化 這幾句話放在主窗口所有語句之后,“end.”之前(需引用ActiveX單元)。

Initialization
  OleInitialize(nil);
Finalization
try
  OleUninitialize;
except
end;

 

 
 
 
TWebBrowser瀏覽相關

Webbrower的顯示和隱藏
  WebBrowser1.Visible :=False; //這句是沒有效果的
  TWinControl(WebBrowser1).Visible :=False;

 

OnCommandStateChange事件
    
當執行TWebBrowser組件的某個方法的功能改變時被觸發,其狀態取值決定於執行Web瀏覽器中某個方法的功能。

property OnCommandStateChange: TWebBrowserCommandStateChange;

type TWebBrowserCommandStateChange = procedure(Sender: TObject; Command: Integer; Enable: WordBool) of object;

Sender:指出其功能已變化的Web瀏覽器組件。

Command:指出功能變化的調用方法,參數取值如表所示。

 

常量

說明

CSC_UPDATECOMMANDS

−1

不被其他常量包含的任何變化,應用程序必須檢查Web瀏覽器的該屬性以更新控制,

例如,事件處理程序可能在更新Stop按鈕時檢查Busy屬性

CSC_NAVIGATEFORWARD

1

歷史列表改變GoForward方法導航到一個新的URL的功能,Enable參數指定GoForward方法現在是否導航到一個新的URL

CSC_NAVIGATEBACK

2

歷史列表改變GoBack方法導航到一個新的URL的功能,Enable參數指定GoBack方法現在是否導航到一個新的URL

 

 

Enable:指定CSC_NAVIGATEFORWARDCSC_NAVIGATEBACK命令是否可用,其值為True時,可用;否則不可用。

示例:

OnCommandStateChange事件提供了一個命令狀態改變后的處理功能,通過該事件能夠判斷執行某個命令后的當前瀏覽器狀態,例如控制“后退”、“前進”或“停止”按鈕是否可用,代碼如下:


procedure TForm1.WebBrowser1CommandStateChange(ASender: TObject;Command: Integer; Enable: WordBool);
Var  bRtn:Boolean;
begin
  case Command of
    CSC_NAVIGATEBACK: ToolButton_Back.Enabled := Enable;    //“后退”按鈕
    CSC_NAVIGATEFORWARD: ToolButton_Forward.Enabled := Enable;    //“前進”按鈕
    CSC_UPDATECOMMANDS: ToolButton_Stop.Enabled := TWebBrowser(ASender).Busy;  //“停止”按鈕
  end;
end;

 

使用進度條查看瀏覽器狀態

procedure TForm1.WebBrowser1ProgressChange(ASender: TObject; Progress,
  ProgressMax: Integer);
begin
  ProgressBar1.Max:=ProgressMax;
  if Progress = -1 then
     //ProgressBar1.Visible:=false
  else
  begin
    ProgressBar1.Position := Progress;
    ProgressBar1.Visible := True;
  end;
  if  ProgressBar1.Position = ProgressMax then
    //ProgressBar1.Visible:=False;
end;

 

1、去掉TWebBrowser的滾動條

方法1
    uses  MSHTML_TLB,MSHTML;
    IHTMLBodyElementDisp(IHTMLDocument2(WebBrowser1.document).body).scroll:= 'no';
 
方法2
    WebBrowser1.oleobject.Document.body.style.overflow := 'hidden' ;

    

2、滾屏

uses MSHTML;
var
    a: IHTMLDocument2;
    x,y:Integer;
begin
    y:
=y+ 20;   // 加減進行上下滾動
    a :
= WebBrowser1.Document as IHTMLDocument2;
    a.Get_ParentWindow.Scroll(x,y);
end;

    

3、去邊框  邊框去掉后 Webbrowser編輯時使用Enter換行無效 但可以使用Shift+Enter換行 Xe2有這個問題XE4正常

margin

應該有上下左右的

WebBrowser1.OleObject.Document.Body.style.border := ' none ' ;
WebBrowser1.OleObject.Document.Body.Style.margin :
= ' 0px ';

    

 

 

4、禁止提示腳步錯誤

procedure TForm1.WebBrowser1NavigateComplete2(ASender: TObject;const pDisp: IDispatch; var URL: OleVariant);
begin
    WebBrowser1.Silent := True;
end;

    

5、禁止彈出窗口

procedure TForm1.WebBrowser1NewWindow2(ASender: TObject; var ppDisp: IDispatch;  var Cancel: WordBool);
begin
  Cancel := True;
end;
    

6、屏蔽右鍵菜單  先要添加ApplicationEvents1,指定其Message事件

//ApplicationEvents1.Event.OnMessage
procedure TForm1.ApplicationEvents1Message( var Msg: tagMSG;
   var Handled: Boolean);
begin
   with Msg do
   begin
     if not IsChild(WebBrowser1.Handle, hWnd) then
      Exit;
      Handled := (message = WM_RBUTTONDOWN) or (message = WM_RBUTTONUP) or (message = WM_CONTEXTMENU);
   end;
end;
    

屏蔽右鍵菜單

//Here's the code to disable the context menu (the one a user gets when it right-clicks inside a TWebBrowser) for TWebBrowser in a Delphi application:


function MouseProc(nCode: Integer; wParam, lParam: Longint): LongInt; stdcall;
var
   classbuf: array[ 0 .. 255] of Char;
const
   ie = 'Internet Explorer_Server';
begin
    case nCode < 0 of
     True:
       Result := CallNextHookEx(MouseHook, nCode, wParam, lParam) ;
     False:
        case wParam of
       WM_RBUTTONDOWN, WM_RBUTTONUP:
        begin
         GetClassName(PMOUSEHOOKSTRUCT(lParam)^.HWND, classbuf, SizeOf(classbuf)) ;
          if lstrcmp(@classbuf[ 0], @ie[ 1]) = 0 then
           Result := HC_SKIP
          else
           Result := CallNextHookEx(MouseHook, nCode, wParam, lParam) ;
        end
        else
        begin
         Result := CallNextHookEx(MouseHook, nCode, wParam, lParam) ;
        end;
      end; //case wParam
    end; //case nCode
end; (*MouseProc*)


//Form OnCreate
procedure TWebBrowserForm.FormCreate(Sender: TObject) ;
begin
   MouseHook := SetWindowsHookEx(WH_MOUSE, MouseProc, 0, GetCurrentThreadId()) ;
end;

//Form OnDestroy
procedure TWebBrowserForm.FormDestroy(Sender: TObject) ;
begin
    if MouseHook <> 0 then UnHookWindowsHookEx(MouseHook) ;
end;


If you want to find more about Windows hooks, read the :An introduction to hook procedures

7、替換右鍵菜單

aaaa
    
 

7、通過IUniformResourceLocator接口建立Internet快捷方式

aaaa
 

8、設置焦點 (當Webbrowser處於編輯模式)
TWebBrowser非常特殊,它從TWinControl繼承來的SetFocus方法並不能使得它所包含的文檔獲得焦點

//方法1
procedure TForm1.ToolButton1Click(Sender: TObject);
begin
    if Form1.WebBrowser1.Document <> nil then
      with WebBrowser1.Application as IOleobject do
        DoVerb(OLEIVERB_UIACTIVATE, nil, WebBrowser1, 0, Handle, GetClientRect());
end;
 
//方法2 Form1OnCreate事件無效
if WebBrowser1.Document <> nil then
    IHTMLWindow2(IHTMLDocument2(WebBrowser1.Document).ParentWindow).Focus();

 

 

    

9、縮放網頁 
    Ctrl+中鍵↑ 放大  
    Ctrl+中鍵↓ 縮小

const
  OLECMDID_OPTICAL_ZOOM = 63;
var
  ZoomIn: OleVariant;
begin
  ZoomIn := 10;
  WebBrowser1.ExecWB(OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT_DODEFAULT, ZoomIn);
end;

 

 

  

10、讀取當前頁面字體大小
 類似“字體”菜單上的從“最大”到“最小”五項(對應整數0~4,Largest等假設為五個菜單項的名字,Tag 屬性分別設為0~4)。

//讀取當前頁面字體大小
var

t: OleVariant;
Begin
  WebBrowser1.ExecWB(OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER,EmptyParam,t);
  case t of
    4: Caption :='最大';
    3: Caption :='較大';
    2: Caption :='中';
    1: Caption :='較小';
    0: Caption :='最小';
  end;
end;

//設置頁面字體大小 這句代碼Delphi7不能編譯通過 Delphi Xe2可以運行
   WebBrowser1.ExecWB(OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER,3);

 

 

  

11、添加到收藏夾 參考MFC的


const
    CLSID_ShellUIHelper: TGUID = '{64AB4BB7-111E-11D1-8F79-00C04FC2FBE1}';
procedure AddFavorite(Webbrowser:TWebBrowser);
var
ShellUIHelper: ISHellUIHelper;
url, title: Olevariant;
begin
  Title := Webbrowser.LocationName;
  Url :=  Webbrowser.LocationUrl;
   if Url <> '' then
    begin
      ShellUIHelper := CreateComObject(CLSID_SHELLUIHELPER) as IShellUIHelper;
      ShellUIHelper.AddFavorite(url, title);
    end;
end;
  

整理收藏夾

var  p:procedure(Handle: THandle; Path: PChar); stdcall;
procedure OrganizeFavorite();
var
H: HWnd;
begin
  H := LoadLibrary(PChar('shdocvw.dll'));
  if H <> 0 then
   begin
    p := GetProcAddress(H, PChar('DoOrganizeFavDlg'));
   if Assigned(p) then p(Application.Handle, PChar(''));
   end;
   FreeLibrary(h);
end;

 

 

11、 Internet 選項

uses ActiveX;
const
  CGID_WebBrowser: TGUID = '{ED016940-BD5B-11cf-BA4E-00C04FD70816}';
//  HTMLID_FIND = 1;      //查找對話框
//  HTMLID_VIEWSOURCE= 2; //查看源代碼
//  HTMLID_OPTIONS =3;    //Internet選項
procedure WB_ShellIEOptions(WebBrowser: TWebbrowser);

var
  CmdTarget : IOleCommandTarget;
  vaIn, vaOut: OleVariant;
  PtrGUID: PGUID;
begin
  New(PtrGUID) ;
  PtrGUID^ := CGID_WebBrowser;
   if WebBrowser.Document <> nil then
     try
      WebBrowser.Document.QueryInterface(IOleCommandTarget, CmdTarget) ;
       if CmdTarget <> nil then
         try
          CmdTarget.Exec(PtrGUID, 3, 0, vaIn, vaOut) ;
         finally
          CmdTarget._Release;
         end;
     except
     end;
  Dispose(PtrGUID) ;
end;

 

 

11、獲取網頁源碼相關

1

2

3

Memo1.Text := WebBrowser1.OleObject.document.body.outerHTML; //body內的所有代碼, 包含body標簽
Memo1.Text := WebBrowser1.OleObject.document.documentElement.innerHTML; //html內的所有代碼
Memo1.Text := WebBrowser1.OleObject.document.body.innerHTML; //body內的所有代碼
   

 

11、 獲取網頁源文件的代碼 網頁右鍵 查看源文件    f1dfb8ff-ddb6-4ff5-8c99-4044bff87a12_0.htm - 記事本

procedure GetHtmlSourceCode( const RichEdit:TRichEdit);
var
ms: TMemoryStream;
begin
    if not Assigned(Form1.WebBrowser1.Document) then Exit;
    ms := TMemoryStream.Create;
    (Form1.WebBrowser1.Document as IPersistStreamInit).Save(TStreamAdapter.Create(ms), True);
    ms.Position := 0;
    RichEdit.Lines.LoadFromStream(ms, TEncoding.UTF8);
     // Memo1.Lines.LoadFromStream(ms, TEncoding.Default); {GB2312 等雙字節}
    ms.Free;
end;

 

11、 獲取網頁源文件的代碼 出來的結果亂碼 unicode?

 
function   GetHtml( const   WebBrowser:TWebBrowser):    string;
const
    BufSize    =   $ 10000;
var
    Size:   Int64;
    Stream:   IStream;
    hHTMLText:   HGLOBAL;
    psi:   IPersistStreamInit;
begin
     if    not   Assigned(WebBrowser.Document)    then   Exit;

    OleCheck(WebBrowser.Document.QueryInterface
    (IPersistStreamInit,   psi));
     try
    OleCheck(psi.GetSizeMax(Size));
        hHTMLText    :=   GlobalAlloc(GPTR,   BufSize);
         if    0    =   hHTMLText    then   RaiseLastWin32Error;

        OleCheck(CreateStreamOnHGlobal(hHTMLText,True,   Stream));

         try
            OleCheck(psi.Save(Stream,   False));

            Size    :=   StrLen(PChar(hHTMLText));
            SetLength(Result,   Size);
            CopyMemory(PChar(Result),   Pointer(hHTMLText),   Size);
         finally
            Stream    :=    nil;
         end;
     finally
        psi    :=    nil;
     end;
end;

 

11、 用記事本查看源代碼

uses ActiveX;
const
  CGID_WebBrowser: TGUID = '{ED016940-BD5B-11cf-BA4E-00C04FD70816}';
 
  //HTMLID_FIND = 1;      //查找對話框
   //HTMLID_VIEWSOURCE= 2; //查看源代碼
   //HTMLID_OPTIONS =3;    //Internet選項

procedure WB_ViewSource(WebBrowser: TWebbrowser);
var
  CmdTarget : IOleCommandTarget;
  vaIn, vaOut: OleVariant;
  PtrGUID: PGUID;
begin
  New(PtrGUID) ;
  PtrGUID^ := CGID_WebBrowser;
   if WebBrowser.Document <> nil then
     try
      WebBrowser.Document.QueryInterface(IOleCommandTarget, CmdTarget) ;
       if CmdTarget <> nil then
         try
          CmdTarget.Exec(PtrGUID, 2, 0, vaIn, vaOut) ;
         finally
          CmdTarget._Release;
         end;
     except
     end;
  Dispose(PtrGUID) ;
end;

 

 

__、設置編碼

     procedure Set_charset(const p: WideString); safecall;
    function  Get_charset: WideString; safecall;
p的編碼列表有哪些
//設置編碼
procedure SetCharSet(AWebBrowser: TWebBrowser; ACharSet: String);
var
RefreshLevel: OleVariant;
Begin
  IHTMLDocument2(AWebBrowser.Document).Set_CharSet(ACharSet);
  RefreshLevel := 7; //這個7應該從注冊表來,幫助有Bug。
  AWebBrowser.Refresh2(RefreshLevel);
End;


//獲取當前頁面編碼
Caption:=IHTMLDocument2(Webbrowser1.Document).Get_charset;
 
 
 

Cookies

 

var
    doc: IHTMLDocument2; //定義變量
begin
    Doc :=WebBrowser1.Document as IHTMLDocument2;
    Doc.cookie :=redt_ViewSource.text; //把edit2中修改好的cookie重新賦值給doc
    WebBrowser1.Refresh; //刷新頁面,修改cookie
end;

 

11、執行網頁源代碼成網頁

procedure ExecHTML(WebBrowser:TWebBrowser;HtmlCode:string);
var
StringStream:TStringStream;
begin
StringStream := TStringStream.Create(HtmlCode);
//WebBrowser.Navigate('about:blank');
try
   StringStream.Position := 0;
   (WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(StringStream));
finally
   StringStream.Free;
end;
end;

我現在發現如果webbrowser內容比較少 就正常 如果內容多 右邊有滾動條 這時候進來 點擊滾動條
就會報“Floating point division by zero ” 這個錯誤 而且報完 界面被強制關閉掉 不知道閣下有沒遇到這個問題 這里我代碼中沒有任何除法操作 只要webbrowser內容多 有滾動條 點擊滾動條 就會這樣
使用Delphi XE4 就沒有這個問題

 

 
 

11、  加載HTML 將HTML代碼轉換成網頁 


procedure WBLoadHTML(WebBrowser: TWebBrowser; HTMLCode: string) ;
var
   sl: TStringList;
   ms: TMemoryStream;
begin
   WebBrowser.Navigate('about:blank') ;
   while WebBrowser.ReadyState < READYSTATE_INTERACTIVE do
    Application.ProcessMessages;

   if Assigned(WebBrowser.Document) then
   begin
     sl := TStringList.Create;
     try
       ms := TMemoryStream.Create;
       try
         HTMLCode:='<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>'+HTMLCode;
         sl.Text := HTMLCode;
         sl.SaveToStream(ms) ;
         ms.Seek(0, 0) ;
         (WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ;
       finally
         ms.Free;
       end;
     finally
       sl.Free;
     end;
   end;
end;


 

 
 

 

11、 加載HTML成WEB

  webbrowser.OleObject.Document.Writeln('HTML CODE');
  webbrowser.Refresh;


 

 
 

 

11、QueryStatusWB

function QueryStatusWB(cmdID: OLECMDID): OLECMDF;
 

cmdID列表

描述

OLECMDF_SUPPORTED

1

Web瀏覽器支持這個命令(但是該命令可能未被使用)

OLECMDF_ENABLED

2

該命令當前是使用的

OLECMDF_LATCHED

4

該命令是一個打開/關閉開關,當前處於打開的狀態

OLECMDF_NINCHED

8

當前尚未使用該值

OLECMDF_INVISIBLE

16

當前尚未使用該值

確定可以使用ExecWB方法執行的命令,即Web瀏覽器支持的命令信息,該方法使用IOleCommandTarget接口的QueryStatus方法來得到命令狀態的信息。

//QueryStatusWB
procedure
TForm1.Button1Click(Sender: TObject);
var
  bEnable,bSupport:Boolean;
begin
 bEnable:= WebBrowser1.QueryStatusWB(OLECMDID_PASTE)=OLECMDF_ENABLED;
 bSupport:=WebBrowser1.QueryStatusWB(OLECMDID_PASTE)=OLECMDF_SUPPORTED;
 if (bEnable or bSupport) then
     WebBrowser1.ExecWB(OLECMDID_COPY,1);
end;


//QueryCommandEnabled

if (Webbrowser1.Document as IHTMLDocument2).QueryCommandEnabled('Copy') then
   (Webbrowser1.Document as IHTMLDocument2).ExecCommand('Copy',false,'');
 

 

procedure ExecWB(cmdID: OLECMDID; cmdexecopt: OLECMDEXECOPT); overload;
cmdID參數列表
//文件
///新建    WebBrowser1.ExecWB(OLECMDID_NEW, 1);    //尚未實現
///打開    WebBrowser1.ExecWB(OLECMDID_OPEN, 1);
///保存    WebBrowser1.ExecWB(OLECMDID_SAVE, 1); //無保存網頁的能力
///另存    WebBrowser1.ExecWB(OLECMDID_SAVEAS, 1);//網頁,僅 HTML (*.htm;*.html)
///-
///打印     WebBrowser1.ExecWB(OLECMDID_PRINT, 1);
///打印預覽  WebBrowser1.ExecWB(OLECMDID_PRINTPREVIEW, 1);
///頁面設置  WebBrowser1.ExecWB(OLECMDID_PAGESETUP, 1);
///-
///屬性     WebBrowser1.ExecWB(OLECMDID_PROPERTIES, 1);

///編輯
///撤銷    WebBrowser1.ExecWB(OLECMDID_REDO , 1);
///重做    WebBrowser1.ExecWB(OLECMDID_UNDO , 1);
///-
///復制    WebBrowser1.ExecWB(OLECMDID_COPY, 1);
///剪切    WebBrowser1.ExecWB(OLECMDID_PASTE, 1);
///粘貼    WebBrowser1.ExecWB(OLECMDID_CUT , 1);
///刪除    WebBrowser1.ExecWB(OLECMDID_DELETE, 1);
///-
///全選    WebBrowser1.ExecWB(OLECMDID_SELECTALL, 1);
///不選    WebBrowser1.ExecWB(OLECMDID_CLEARSELECTION, 1);
    
///查找/替換
///查找對話框    WebBrowser1.ExecWB(OLECMDID_FIND, 1);

 

__、替換對話框

    

 

__、剪切板

uses Clipbrd;
procedure TForm1.ToolButton1Click(Sender: TObject);
var
  i: integer;
  Buffer: PChar;
  s: string;
begin
  Memo1.Lines.Clear;  
   with TClipboard.Create do  
   begin
    GetMem(Buffer, 20);
     for i := 0 to FormatCount - 1 do
     begin
      GetClipboardFormatName(Formats[i], Buffer, 20);
      s := StrPas(Buffer);
      Memo1.Lines.Add(Format( '%s:%d', [s, Formats[i]]));
     end;
  FreeMem(Buffer);
  Free;
   end;
end;

 

 

__、保存文檔為 .HTML

The TWebBrowser component (located on the "Internet" page of the Component Palette) provides access to the Web browser functionality from your Delphi applications. In general, you'll want to enable saving of a web page displayed inside a WebBrowser as a HTML file to a disk.
Saving a web page as a raw HTML
If you only want to save a web page as a raw HTML you would select "Web Page, HTML only (*.htm, *.html)". It will simply save the current page's source HTML to your drive intact. This action will NOT save the graphics from the page or any other files used within the page, which means that if you loaded the file back from the local disk, you would see broken image links.
uses ActiveX;

procedure WB_SaveAs_HTML(WB : TWebBrowser; const FileName : string) ;
var
   PersistStream: IPersistStreamInit;
   Stream: IStream;
   FileStream: TFileStream;
begin
    if not Assigned(WB.Document) then
    begin
     ShowMessage( 'Document not loaded!') ;
     Exit;
    end;

   PersistStream := WB.Document as IPersistStreamInit;
   FileStream := TFileStream.Create(FileName, fmCreate) ;
    try
     Stream := TStreamAdapter.Create(FileStream, soReference) as IStream;
      if Failed(PersistStream.Save(Stream, True)) then ShowMessage( 'SaveAs HTML fail!') ;
    finally
     FileStream.Free;
    end;
end; (* WB_SaveAs_HTML *)
 
Usage sample:
 
//first navigate
WebBrowser1.Navigate( 'about:blank') ;

//then save
WB_SaveAs_HTML(WebBrowser1, 'c:\WebBrowser1.html') ;

 

__、

__、保存文檔為 .mht

uses CDO_TLB, ADODB_TLB;
procedure WB_SaveAs_MHT(WB: TWebBrowser; FileName: TFileName) ;
var
   Msg: IMessage;
   Conf: IConfiguration;
   Stream: _Stream;
   URL : widestring;
begin
    if not Assigned(WB.Document) then Exit;

   URL := WB.LocationURL;

   Msg := CoMessage.Create;
   Conf := CoConfiguration.Create;
    try
     Msg.Configuration := Conf;
     Msg.CreateMHTMLBody(URL, cdoSuppressAll, '', '') ;
     Stream := Msg.GetStream;
     Stream.SaveToFile(FileName, adSaveCreateOverWrite) ;
    finally
     Msg := nil;
     Conf := nil;
     Stream := nil;
    end;
end; (* WB_SaveAs_MHT *) 

Sample usage:

//first navigate
WebBrowser1.Navigate( 'http://delphi.about.com') ;

//then save
WB_SaveAs_MHT(WebBrowser1, 'c:\WebBrowser1.mht') ;

 

__、

 

__、粘貼位圖選擇粘貼
粘貼 HTML
粘貼純文本
粘貼Unicode文字
粘貼RTF

  

 

 

__、Ctrl+V粘貼位圖

 

 

__、查找突出顯示匹配項


 

 

 

__、查找突出顯示匹配項苗紅

 

 

__、查找對話框

uses ActiveX;
const
  CGID_WebBrowser: TGUID = '{ED016940-BD5B-11cf-BA4E-00C04FD70816}';
//  HTMLID_FIND = 1;      //查找對話框
//  HTMLID_VIEWSOURCE= 2; //查看源代碼
//  HTMLID_OPTIONS =3;    //Internet選項
procedure WB_FindDialog(WebBrowser: TWebbrowser);

var
  CmdTarget : IOleCommandTarget;
  vaIn, vaOut: OleVariant;
  PtrGUID: PGUID;
begin
  New(PtrGUID) ;
  PtrGUID^ := CGID_WebBrowser;
   if WebBrowser.Document <> nil then
     try
      WebBrowser.Document.QueryInterface(IOleCommandTarget, CmdTarget) ;
       if CmdTarget <> nil then
         try
          CmdTarget.Exec(PtrGUID, 1, 0, vaIn, vaOut) ;
         finally
          CmdTarget._Release;
         end;
     except
     end;
  Dispose(PtrGUID) ;
end;

 

 

function execCommand(const cmdID: WideString; showUI: WordBool; value: OleVariant): WordBool; safecall;
cmdID參數列表
uses Mshtml;

///網頁查看模式     
    (WebBrowser1.Document as IHTMLDocument2).designMode := 'on';
    (WebBrowser1.Document as IHTMLDocument2).execCommand('EditMode',False,1);
///網頁編輯模式 
    (WebBrowser1.Document as IHTMLDocument2).designMode := 'off';
    (WebBrowser1.Document as IHTMLDocument2).execCommand('BrowseMode',False,1);

///選中文本編輯
///設置字體

//////名稱        (WebBrowser1.Document as IHTMLDocument2).execCommand( 'FontName', False, '宋體');
//////大小        (WebBrowser1.Document as IHTMLDocument2).execCommand( 'FontSize', False, 7); ///字體大小是從1到7
////樣式 
//////粗體        (WebBrowser1.Document as IHTMLDocument2).execCommand( 'Bold', False, 1);
//////斜體        (WebBrowser1.Document as IHTMLDocument2).execCommand( 'Italic', False, 1);
/////下划線       (WebBrowser1.Document as IHTMLDocument2).execCommand( 'Underline', False, 1);
/////刪除線       (WebBrowser1.Document as IHTMLDocument2).execCommand( 'StrikeThrough', False, 1);

///超鏈接          (WebBrowser1.Document as IHTMLDocument2).execCommand( 'CreateLink', False, 1);
///刪除超鏈接      (WebBrowser1.Document as IHTMLDocument2).execCommand( 'UnLink', False, 1);

///設置
///設置文字前景色   (WebBrowser1.Document as IHTMLDocument2).execCommand( 'ForeColor',False, 'Red');
///設置文字背景色   (WebBrowser1.Document as IHTMLDocument2).execCommand( 'BackColor',False, 'Blue');

///設置下標        (WebBrowser1.Document as Ihtmldocument2).execCommand( 'SubScript',False, 1);
///設置上標        (WebBrowser1.Document as Ihtmldocument2).execCommand( 'SuperScript',False, 1);

///設置對齊方式
///設置左對齊       (WebBrowser1.Document as IHTMLDocument2).execCommand( 'JustifyLeft', False, 0);
///設置中對齊       (WebBrowser1.Document as IHTMLDocument2).execCommand( 'JustifyCenter', False, 0);
///設置右對齊       (WebBrowser1.Document as IHTMLDocument2).execCommand( 'JustifyRight', False, 0);
///設置兩端對齊     (WebBrowser1.Document as IHTMLDocument2).execCommand( 'JustifyFull', False, 0);


///縮進
///向右縮進        (WebBrowser1.Document as Ihtmldocument2).execCommand( 'Indent',True, 1);
///向左縮進        (WebBrowser1.Document as Ihtmldocument2).execCommand( 'Outdent',True, 1);

///清除格式        (WebBrowser1.Document as Ihtmldocument2).execCommand( 'Removeformat',True, 0);

///序列查看
///數字格式         (WebBrowser1.Document as Ihtmldocument2).execCommand( 'InsertOrderedList',True, 0);
///圓點查看         (WebBrowser1.Document as Ihtmldocument2).execCommand( 'InsertUnorderedList',True, 0);

///插入圖片(靜態)  (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertImage', True, '');
                   (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertImage', False, 'C:\1.png');
 
///插入書簽 (WebBrowser1.Document as Ihtmldocument2).execCommand( 'CreateBookmark',True, 0);
///取消書簽 (WebBrowser1.Document as Ihtmldocument2).execCommand( 'UnBookmark',True, 0);
 
///插入HTML組件
///后面的字符串為這個控件的ID號
///直線          Line         (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertHorizontalRule', True, '');
///按鈕          Button       (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertButton', True, '');
///復選框        CheckBox     (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertInputCheckbox', True, '');
///單選框        Radio        (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertInputRadio', True, '');
///編輯框        Edit         (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertInputText', True, '');
///文本框        Memo         (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertTextArea', True, '');
///密碼框        PswEdit      (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertInputPassword', True, '');
///組框架        GroupBox     (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertIFrame', True, '');
///列表框        ListBox      (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertSelectListbox', True, '');
///組合框        Combobox     (WebBrowser1.Document as IHTMLDocument2).execCommand( 'InsertSelectDropdown', True, '');
 

 

__、初始化成編輯模式

procedure TForm1.FormCreate(Sender: TObject);
begin

    WebBrowser1.Align :=alClient;
    WebBrowser1.Navigate( 'about:blank');
    while WebBrowser1.busy do
         Application.ProcessMessages;
    (WebBrowser1.Document as IHTMLDocument2).designMode := 'On';
end;

 

 

 

 

 

__、工具欄感應

function queryCommandValue(const cmdID: WideString): OleVariant; safecall;

  1. 字體名稱
  2. 字符大小
function GetFontName():string;
begin
      Result:=(Form1.webbrowser1.Document as IHTMLDocument2).queryCommandValue('FontName');
end;

function GetFontSize():string;
begin
    Result:=(Form1.webbrowser1.Document as IHTMLDocument2).queryCommandValue('FontSize');
end;

 


 

function queryCommandState(const cmdID: WideString): WordBool; safecall;
  1. 粗體
  2. 斜體
  3. 下划線
  4. 刪除線
  5. 對齊方式 左 中 右
  6. 數字排序
  7. 圓的排序
  8. 上標
  9. 下標
function IsBold():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('Bold');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsItalic():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('Italic');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsUnderline():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('Underline');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsStrikeThrough():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('StrikeThrough');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsSubScript():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('SubScript');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsSuperScript():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('SuperScript');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsJustifyLeft():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('JustifyLeft');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsJustifyCenter():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('JustifyCenter');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsJustifyRight():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('JustifyRight');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsJustifyFull():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('JustifyFull');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsInsertOrderedList():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('InsertOrderedList');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;

function IsInsertUnorderedList():Boolean;
Var  bRtn:Boolean;
begin
    bRtn:= (Form1.webbrowser1.Document as IHTMLDocument2).queryCommandState('InsertUnorderedList');
    if bRtn then
        Result:=True
    else
        Result:=False;
end;
 

 

 
工具欄感應的使用
procedure TForm1.WebBrowser1CommandStateChange(ASender: TObject;Command: Integer; Enable: WordBool);
   Var  bRtn:Boolean;
begin

try
  cbb_FontNameList.Text :=GetFontName();
  cbb_FontSize.Text :=GetFontSize();

  btn_Bold.Down :=IsBold();
  btn_Italic.Down :=IsItalic();
  btn_Underline.Down :=IsUnderline();
  btn_strikethrough.Down :=IsStrikeThrough();

  btn_SubScript.Down :=IsSubScript();
  btn_SuperScript.Down :=IsSuperScript();

  ToolButton_AlignTwo.Down :=IsJustifyFull();
  ToolButton_AlignLeft.Down :=IsJustifyLeft();
  ToolButton_AlignCenter.Down :=IsJustifyCenter();
  ToolButton_AlignRight.Down :=IsJustifyRight();

  ToolButton_UnoredredList.Down :=IsInsertUnorderedList();
  ToolButton_OrderedList.Down :=IsInsertOrderedList();
except
  Exit;
end;
end;
 
 
 

 

 

__、截圖

先截圖然后保存到 C:\Windows\temp  
然后使用方法(WebBrowser1.Document as IHTMLDocument2).execCommand('InsertImage', False, 'C:\1.jpg');插入到指定位置

aaaa
 
 
 

__、______

__、______

aaaa
 
 
 

__、______

__、______

aaaa
 
 
 

__、______

__、______

aaaa
 
 
 

__、______

 

__、表格操作

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、WebBrowser選中文本操作
設置Webbrowser的內容

//獲得WebBrowser1里的文本相當於 Caption = Webbrowser1.Text
//獲得當前選中的文本  Webrowser.Selection.Text
//獲得當前選中的文本  Webrowser.Selection.HTML
//設置選中的文本Webrowser.Selection.Text="ABC";
function GetSelText():string;
var
  Doc: IHtmlDocument2;
begin
  Result:=( (Form1.WebBrowser1.Document as IHTMLDocument2).selection.createRange as IHtmlTxtRange).text;
end;

procedure SetSelText(s:string);
var
  Doc: IHtmlDocument2;
begin
  ( (Form1.WebBrowser1.Document as IHTMLDocument2).selection.createRange as IHtmlTxtRange).text:=s;
end;

function GetSelHtmlText():string;
var
  Doc: IHtmlDocument2;
begin
  Result:=( (Form1.WebBrowser1.Document as IHTMLDocument2).selection.createRange as IHtmlTxtRange).htmlText;
end;

procedure SetSelHtmlText(s:string);
var
  Doc: IHtmlDocument2;
begin
  ( (Form1.WebBrowser1.Document as IHTMLDocument2).selection.createRange as IHtmlTxtRange).pasteHTML(s);
end;
 
 
 

__、______

 

Application.ProcessMessages;
//Webbrowser的文本等於什么
(WebBrowser1.Document as IHTMLDocument2).body.innerHTML := 'abc';
 WebBrowser1.OleObject.document.body.innerText :='abc' //文本

WebBrowser1.OleObject.Document.Writeln('ok');
  webbrowser.OleObject.Document.Writeln(SynEdit.Text); //LOAD HTML
  webbrowser.Refresh;

(WebBrowser1.Document as IHTMLDocument2).selection.clear; //刪除選中區的內容。
Caption:=(WebBrowser1.Document as IHTMLDocument2).title; //獲取當前文檔的標題
Caption:=WebBrowser1.LocationName;//獲取當前文檔的標題


WebBrowser1.OleObject.document.body.background := 'C:\1.png';//Webbrowser的背景圖片
WebBrowser1.OleObject.document.body.bgcolor := '#FF0000';  //Webbrowser的背景色
 
 
 
 
show a miniature view of a Webpage in TWebbrowser?

 

 

procedure TForm1.WebBrowser1NavigateComplete2(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
begin
    WebBrowser1.OleObject.Document.Body.Style.Zoom := 0. 50;
end;
WebBrowser1.OleObject.Document.Body.Style.Zoom := 0.50;//WebBrowser 中頁面的放大或縮小 百分比
 
 
 
WebBrowser1.OleObject.Document.designMode:='On';//編輯模式
WebBrowser1.OleObject.Document.designMode:='Off';//瀏覽模式
WebBrowser1.OleObject.document.body.contentEditable := CheckBox1.Checked;//是讓整個頁面可編輯, 也可以單獨編輯某個元素
//定位光標到指定位置
//判斷Webbrowser是否修改過

//使用網頁彈消息
   (Webbrowser1.Document as IHTMLDocument2).parentWindow.alert('aaaa');

WebBrowser1.OleObject.document.body.style.fontSize :=StrToInt(cbb_Style.Text);//設置全部的字體大小



 
 
 

 

 
 
 

 

aaaa

 

 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

__、______

aaaa
 
 
 

Webbrowser Bug
當Webbrowser處於編輯模式 此時如果往里面粘貼大量文本 並且使用 水平和垂直的滾動條出現 當拖拽垂直滾動條時 則出現以下問題

aaaa
 
 
 
 






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM