如何在系统默认浏览器中从TCppWebBrowser组件打开链接 [英] How do I open links from a TCppWebBrowser component in the systems default browser

查看:480
本文介绍了如何在系统默认浏览器中从TCppWebBrowser组件打开链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在我们的程序中使用TCppWebBrowser组件作为一种聊天窗口,但由于TCppwebrowser使用IExplorerengine,所有单击的链接都在IExplorer中打开。
我有一个想法是取消导航Onbeforenavigate2一个做Shell.execute,但希望一个更优雅的解决方案像一个windowsmessage我可以处理或事件或某事。

We are using a TCppWebBrowser Component in our program as a kind of chatwindow, but since the TCppwebrowser is using the IExplorerengine all links that are clicked is opening in IExplorer. One idea I have is to cancel the navigation in Onbeforenavigate2 an do a Shell.execute, but where hoping for a more elegant solution like a windowsmessage i could handle or an event or something.

推荐答案

假设TCppWebBrowser类似于Delphi中的TWebBrowser,下面的代码应该可以让你去。

Assuming that TCppWebBrowser is like TWebBrowser in Delp something like the code below should get you going.

在TWebBrowser导航到之前, OnBeforeNavigate2事件会被触发一个新的URL。
您所做的是取消导航,并将网址重定向到ShellExecute到外部应用程序(这是在Windows中配置的默认Web浏览器)。

The OnBeforeNavigate2 event gets fired before the TWebBrowser navigates to a new URL. What you do is cancel that navigation, and redirect the URL with ShellExecute to an external application (which is the default web browser as configured in Windows).

为了让代码如下工作,双击你的窗体,然后输入FormCreate事件方法内容。
然后删除一个TWebBrowser,去做对象检查器的事件页面,双击OnBeforeNavigate2事件并输入该代码。

In order to get the code below working, double click on your form, then enter the FormCreate event method content. Then drop a TWebBrowser, go do the events page of the object inspector and double click on the OnBeforeNavigate2 event and enter that code.

玩得开心!

- jeroen

--jeroen

unit MainFormUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, OleCtrls, SHDocVw;

type
  TForm1 = class(TForm)
    WebBrowser1: TWebBrowser;
    procedure FormCreate(Sender: TObject);
    procedure WebBrowser1BeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
        var URL, Flags, TargetFrameName, PostData, Headers: OLEVariant; var Cancel:
        WordBool);
  private
    RedirectUrls: Boolean;
  end;

var
  Form1: TForm1;

implementation

uses
  ShellAPI;

{$R *.dfm}

procedure TForm1.Create(Sender: TObject);
begin
  WebBrowser1.Navigate('http://www.stackoverflow.com');
  RedirectUrls := True;
end;

procedure TForm1.WebBrowser1BeforeNavigate2(ASender: TObject; const pDisp:
    IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OLEVariant;
    var Cancel: WordBool);
var
  UrlString: string;
begin
  if not RedirectUrls then
    Exit;
  UrlString := URL;
  ShellExecute(Self.WindowHandle, 'open', PChar(UrlString), nil, nil, SW_SHOWNORMAL);
  Cancel := True;
end;

end.

这篇关于如何在系统默认浏览器中从TCppWebBrowser组件打开链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆