views:

494

answers:

2

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.

+6  A: 

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

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).

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.

Have fun with it!

--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.
Jeroen Pluimers
+1  A: 
David M
Thanks! My C++ is a bit rusty, hence the Delphi example I gave :-)
Jeroen Pluimers
Thanks. I program in c++ builder, but have no problem reading Delphi so mr Pluimers solution is nice. And is some sort of what I did.
Qwark