Friday, September 14, 2007

Fooling around with TWebbrowser #3

Some more tips to make a webbrowser application that rocks!

Get the right popupwindow size
In episode #2 we managed to retain the ASP.NET Session for popup windows in our TWebbrowser application.
Initially we don't know what the size of our popup form must be. Fortunately TWebbrowser has two events for that, so that we can size our window accordingly.
Use the OnWindowSetHeight and OnWindowSetWidth event to do this.

procedure TfrmPopUpBrowser.WebBrowser1WindowSetHeight(
ASender: TObject; Height: Integer);
Self.Height := WebBrowser1.Height + 20;

procedure TfrmPopUpBrowser.WebBrowser1WindowSetWidth(
ASender: TObject; Width: Integer);
Self.Width := WebBrowser1.Width + 20;

The additional distance of 20, is to avoid scrollbars.

Filling up a combobox with the visited websites
If you use a combobox to harvest the visited websites, just like Internet Explorer then you could use the OnDocumentComplete event to get the complete URL and then add it to your combobox. I use this event for three reasons:

1. It gives you a complete URL (not not but
2. If the typed address is not available (a non existing website) the OnNavigateError event will trigger, so you could then decide not to add the URL to the webbrowser.
3. Having a good URL gives the ability to locate the URL in combobox again if the user navigates back to the page.

You don't have this advantages if you add the URL into the combobox directly after input.

procedure TfrmPopUpBrowser.WebBrowser1DocumentComplete(
ASender: TObject;
const pDisp: IDispatch;
var URL: OleVariant);

procedure TfrmPopUpBrowser.AddAddressToCombobox(
Adres : string);
Adres := LowerCase(Adres);
If (Adres <> '')
and (cboAddress.Items.IndexOf(Adres) = -1) then begin

Enable/Disable navigatebuttons (back/forward) automatically
If you put two buttons on your form to navigate back and forward in the webbrowser you will get an error if there is no page to go back to. (Webbrowser1.GoBack and Webbrowser1.GoForward methods)
You can use the OnCommandChange event to make this buttons 'case sensitive':

procedure TfrmPopUpBrowser.WebBrowser1CommandStateChange(
ASender: TObject; Command: Integer; Enable: WordBool);
case Command of
CSC_NAVIGATEBACK: tbApplicationBack.Enabled := Enable;
CSC_NAVIGATEFORWARD: tbApplicationNext.Enabled := Enable;

Add a progress bar to your application
If you want to see the load progress of a page then use the OnProgressChange event.

procedure TfrmPopUpBrowser.WebBrowser1ProgressChange(
ASender: TObject; Progress, ProgressMax: Integer);
ProgressBar.Max := ProgressMax;
ProgressBar.Min := 0;
ProgressBar.Position := Progress;

Have the url in your statusbar or label
Use the OnStatusChange event to show the navigated address in a label or statusbar.

procedure TfrmPopUpBrowser.WebBrowser1StatusTextChange(
ASender: TObject; const Text: WideString);
StatusBar.SimpleText := Text;

1 comment:

Anonymous said...

Great, thanks!