Delphi WebBrowser 技巧

來源:互聯網
上載者:User

初始化和終止化(Initialization & Finalization)

  大家在執行TWebBrowser的某個方法以進行期望的操作,如ExecWB等的時候可能都碰到過“試圖啟用未註冊的丟失目標”或“OLE對象未註冊”等錯誤,或者並沒有出錯但是得不到希望的結果,比如不能將選中的網頁內容複寫到剪貼簿等。以前用它編程的時候,我發現ExecWB有時侯起作用但有時侯又不行,在Delphi產生的預設工程主視窗上加入TWebBrowser,運行時並不會出現“OLE對象未註冊”的錯誤。同樣是一個偶然的機會,我才知道OLE對象需要初始化和終止化(懂得的東東實在太少了)。
  Initialization
   OleInitialize(nil);
  finalization
   try
    OleUninitialize;
   except
   end;

 

 去掉捲軸的方法:
核心代碼:WebBrowser1.oleobject.Document.body.Scroll:= ‘no’;
利用這個代碼去掉捲軸的前提是webbrowser中必須有開啟的網頁,也就是在網頁載入完完畢後再去掉捲軸。所以首先要判斷頁面是否載入完畢,如果載入完畢,就執行上面的語句去掉捲軸。
第一步:在WebBrowser1DocumentComplete事件中置一個標誌tag:=1(代表載入完畢)
代碼如下:
procedure TForm1.WebBrowser1DocumentComplete(Sender: TObject;
  const pDisp: IDispatch; var URL: OleVariant);
begin
tag:=1;  //去掉Webbrowser1捲軸的標誌
end;

第二步:
procedure TForm1.SpeedButton1Click(Sender: TObject);
var
Doc: IHTMLDocument2;
begin
tag := 0; //去掉Webbrowser1捲軸的標誌
WebBrowser1.Navigate2(’http://www.163.com’);
while(tag=0) do Application.ProcessMessages;
WebBrowser1.oleobject.Document.body.Scroll := ‘no’;
end;

注意:使用前必須在uses中加入mshtml;

==========================題外話
//去掉捲軸後如何翻頁呢?用如下代碼
var
 Doc: IHTMLDocument2;
begin
  Doc :=WebBrowser1.Document as IHTMLDocument2;
  Doc.Get_ParentWindow.Scroll(x,y);
end;                          ^^^你要滾動的位置

 

webbrowser不彈出錯誤提示框

設定一下這個屬性:webbrowser1.silent :=true

 

讓Webbrowser中的連結點擊時在自身視窗開啟

 在WebBrowser的NewWindow2事件中設定代碼:
procedure TForm1.WebBrowserNewWindow2(Sender: TObject; var ppDisp: IDispatch;
  var Cancel: WordBool);
begin
    // 將新視窗在自身開啟
        ppdisp := webBrowser.Application;
end;

 

屏蔽WebBrower的右鍵菜單

放一個ApplicationEvents控制項,在ApplicationEvents的事件OnMessage中設定如下代碼:
(ApplicationEvents控制項在delphi中的additional選項卡上找)

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
  var Handled: Boolean);
begin
     //屏敝網頁右鍵
 if Msg.message = WM_RBUTTONDOWN then
begin
   //如果去掉下面這行就是屏蔽右鍵菜單,現在為自訂右鍵菜單
//  popupmenu1.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);
  Handled := True;
 end;
   end;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.