Overview of TWebBrowser programming in Delphi

Source: Internet
Author: User
Overview of twebbrowser programming in Delphi

Delphi3 began to have the twebbrowser component, but it was then in the form of ActiveX controls and needs to be introduced by itself. In the subsequent 4.0 and 5.0, it encapsulates shdocvw. dll appears on the component panel as one of the Internet component groups. I often hear people scold Delphi for their poor help. This time twebbrowser is Microsoft's stuff, and naturally it won't be good where to go. Although there is everything on msdn, the content is too complicated, if there is no entry point, it is even more annoying. It can be described in one sentence as a result of Search: very complicated and complicated.
Here are some of my experiences in using twebbrowser as a program and some examples and materials collected on the Internet. I have sorted out some examples and materials, hoping to help my friends who are interested in using twebbrowser programming.
  
  
  
1. Initialization and termination (initialization & finalization)
You are executing a method of twebbrowser to perform the expected operation, for example, execwb may encounter errors such as "trying to activate unregistered lost targets" or "OLE object not registered", or no errors but no expected results, for example, you cannot copy the selected webpage content to the clipboard. When I used it for programming, I found that execwb sometimes works but sometimes does not work. I added twebbrowser to the default Project Main Window generated by Delphi, the "OLE object not registered" error does not occur during the runtime. It is also an accidental opportunity to know that the OLE object needs initialization and termination (there are too few things to understand ).
I used the method programming described in my previous article "Delphi program window animation & normal arrangement and tile solution", and the above error occurred during running, I guess there should be a statement like oleinitialize, so I found and added the following sentence to finally solve it! The reason is that twebbrowser is an embedded OLE object rather than a VCL written in Delphi.
Initialization
Oleinitialize (NiL );
Finalization
Try
OleUninitialize;
Except
End;
These statements are placed after all the statements in the Main Window and before "end.
Bytes -----------------------------------------------------------------------------------
2. EmptyParam
In Delphi 5, The Navigate method of TWebBrowser is reloaded multiple times:
Procedure Navigate (const URL: WideString); overload;
Procedure Navigate (const URL: WideString; var Flags:
OleVariant); overload;
Procedure Navigate (const URL: WideString; var Flags:
OleVariant; var TargetFrameName: OleVariant); overload;
Procedure Navigate (const URL: WideString; var Flags:
OleVariant; var TargetFrameName: OleVariant; var PostData:
OleVariant); overload;
Procedure Navigate (const URL: WideString; var Flags:
OleVariant; var TargetFrameName: OleVariant; var PostData:
OleVariant; var Headers: OleVariant); overload;
In practical application, we seldom use the following parameters when using the last several methods, but the function declaration must be a variable parameter. The general practice is as follows:
Var
T: OleVariant;
Begin
Webbrowser1.Navigate (edit1.text, t, t );
End;
It is very troublesome to define the variable t (which is used in many other places. In fact, we can replace EmptyParam with EmptyParam (EmptyParam is a common Variant empty variable, so don't assign values to it). You only need one sentence:
Webbrowser1.Navigate (edit1.text, EmptyParam, EmptyParam );
Although a little longer, it is much easier than defining variables every time. Of course, you can also use the first method.
Webbrowser1.Navigate (edit1.text)
Bytes -----------------------------------------------------------------------------------
3. ExecWB can be used to perform common command operations. ExecWB is also overloaded multiple times:
Procedure ExecWB (Region ID: oleeneid; cmdexecopt:
OLECMDEXECOPT); overload;
Procedure ExecWB (Region ID: oleyun ID; cmdexecopt: OLECMDEXECOPT;
Var pvaIn:
OleVariant); overload;
Procedure ExecWB (role ID: rolesponid; cmdexecopt:
OLECMDEXECOPT; var pvaIn:
OleVariant; var pvaOut: OleVariant); overload;
Open: the "open Internet address" dialog box is displayed. CommandID is OLECMDID_OPEN (if the browser version is IE5.0,
The command is unavailable ).
Save as: Call the "Save as" dialog box.
ExecWB (OLECMDID_SAVEAS, OLECMDEXECOPT_DODEFAULT,
EmptyParam,
EmptyParam );
  
  
Print, print preview, and page settings: Call the "print", "print preview", and "page settings" dialog boxes (for IE5.5 and later versions
Print preview, so the implementation should check whether this command is available ).
ExecWB (OLECMDID_PRINT, OLECMDEXECOPT_DODEFAULT,
EmptyParam,
EmptyParam );
If QueryStatusWB (OLECMDID_PRINTPREVIEW) = 3 then
ExecWB (OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_DODEFAULT,
EmptyParam, EmptyParam );
ExecWB (OLECMDID_PAGESETUP, OLECMDEXECOPT_DODEFAULT,
EmptyParam,
EmptyParam );
  
  
Cutting, copying, pasting, and selecting all functions: cut and paste not only edit box text, but also non-Edit
The text in the edit box is equally valid. If you use it well, you may be able to make something special. Obtain the command enable
There are two ways to run commands (take the copy as an example, cut, paste, and select all to replace their respective keywords
You can change them to CUT, PASTE, and SELECTALL ):
A. Use the QueryStatusWB method of TWebBrowser.
If (QueryStatusWB (OLECMDID_COPY) = OLECMDF_ENABLED) or
OLECMDF_SUPPORTED) then
ExecWB (OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT,
EmptyParam,
EmptyParam );
B. Use the QueryCommandEnabled method of IHTMLDocument2.
Var
Doc: IHTMLDocument2;
Begin
Doc: = WebBrowser1.Document as IHTMLDocument2;
If Doc. QueryCommandEnabled ('copy') then
Doc. ExecCommand ('copy', false, EmptyParam );
End;
Search: refer to the ninth "Search" function.
Bytes -----------------------------------------------------------------------------------
4. font size
Similar to the five items from "Max" to "min" on the "font" menu (corresponding to the integer 0 ~ 4. Largest and so on are assumed to be the names of the five menu items, Tag
Set the attribute to 0 ~ 4 ).
A. Read the font size of the current page.
Var
T: OleVariant;
Begin
WebBrowser1.ExecWB (OLECMDID_ZOOM,
OLECMDEXECOPT_DONTPROMPTUSER,
EmptyParam, t );
Case t
4: Largest. Checked: = true;
3: Larger. Checked: = true;
2: Middle. Checked: = true;
1: Small. Checked: = true;
0: Smallest. Checked: = true;
End;
End;
B. Set the page font size.
Largest. Checked: = false;
Larger. Checked: = false;
Middle. Checked: = false;
Small. Checked: = false;
Smallest. Checked: = false;
TMenuItem (Sender). Checked: = true;
T: = TMenuItem (Sender). Tag;
WebBrowser1.ExecWB (OLECMDID_ZOOM,
OLECMDEXECOPT_DONTPROMPTUSER,
T, t );
Bytes -----------------------------------------------------------------------------------
5. Add to favorites and organize favorites
Const
CLSID_ShellUIHelper: TGUID =
'{64AB4BB7-111E-11D1-8F79-00C04FC2FBE1 }';
Var
P: procedure (Handle: THandle; Path: PChar); stdcall;
Procedure TForm1.OrganizeFavorite (Sender: Tobject );
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 (FavFolder ));
End;
FreeLibrary (h );
End;
       
Procedure TForm1.AddFavorite (Sender: TObject );
Var
ShellUIHelper: ISHellUIHelper;
Url, title: Olevariant;
Begin
Title: = Webbrowser1.LocationName;
Url: = Webbrowser1.LocationUrl;
If Url <> ''then
Begin
ShellUIHelper: = CreateComObject (CLSID_SHELLUIHELPER)
IShellUIHelper;
ShellUIHelper. AddFavorite (url, title );
End;
End;
The above method to open the "add to Favorites" dialog box through the ISHellUIHelper interface is relatively simple, but there is a defect that the window opened is not a mode window, but independent of the application. As you can imagine, if you use the same method as the OrganizeFavorite process to open a dialog box, you can specify the handle of the parent window, you can naturally implement the mode window (the effect is the same as that in the "add to Favorites" dialog box in resource manager and IE ). Obviously, the problem is that the authors of the above two processes only knew shdocvw. the prototype of DoOrganizeFavDlg in dll does not know the prototype of DoAddToFavDlg, so we have to use the ISHellUIHelper interface for implementation (maybe he is not rigorous enough and doesn't think it is a pattern window ?).
The following process tells you the DoAddToFavDlg function prototype. Note that the "add to Favorites" operation is not performed in the displayed dialog box. It only tells the application user whether to select "OK ", in the second parameter of DoAddToFavDlg, return the path to which the user wants to place the Internet shortcut. the Url file is done by the application itself.
Procedure TForm1.AddFavorite (IE: TEmbeddedWB );
Procedure CreateUrl (AUrlPath, AUrl: PChar );
Var
URLfile: TIniFile;
Begin
URLfile: = TIniFile. Create (String (AUrlPath ));
RLfile. WriteString ('internetshortcut ', 'url ',
String (AUrl ));
RLfile. Free;
End;
Var
AddFav: function (Handle: THandle;
UrlPath: PChar; UrlPathSize: Cardinal;
Title: PChar; TitleSize: Cardinal;
FavIDLIST: pItemIDList): Bool; stdcall;
FDoc: IHTMLDocument2;
UrlPath, url, title: array [0 .. MAX_PATH] of char;
H: HWnd;
Pidl: pItemIDList;
FRetOK: Bool;
Begin
FDoc: = IHTMLDocument2 (IE. Document );
If FDoc = nil then exit;
StrPCopy (Title, FDoc. Get_title );
StrPCopy (url, FDoc. Get_url );
If Url <> ''then
Begin
H: = LoadLibrary (PChar ('shdocvw. dll '));
If H <> 0 then
Begin
SHGetSpecialFolderLocation (0, CSIDL_FAVORITES, pidl );
AddFav: = GetProcAddress (H, PChar ('doaddtofavdlg '));
If Assigned (AddFav) then
FRetOK: = AddFav (Handle, UrlPath, Sizeof (UrlPath ),
Title, Sizeof (Title), pidl)
End;
FreeLibrary (h );
If FRetOK then
CreateUrl (UrlPath, Url );
End
End;
  
  
Bytes -----------------------------------------------------------------------------------
6. Make WebBrowser focus
TWebBrowser is very special. The SetFocus method inherited from TWinControl does not allow it to focus on the documents it contains, and thus cannot use the Internet immediately.
Explorer has the shortcut key. The solution is as follows: <
Procedure TForm1.SetFocusToDoc;
Begin
If WebBrowser1.Document <> nil then
With WebBrowser1.Application as IOleobject do
DoVerb (OLEIVERB_UIACTIVATE, nil, WebBrowser1, 0, Handle,
GetClientRect );
End;
In addition, I also found a simpler method, which is listed here:
If WebBrowser1.Document <> nil then
IHTMLWindow2 (IHTMLDocument2 (WebBrowser1.Document). ParentWindow). focus
  
  
I just found a simpler method, maybe the simplest:
If WebBrowser1.Document <> nil then
IHTMLWindow4 (WebBrowser1.Document). focus
Also, you need to determine whether the document gets the focus in this way:
If IHTMLWindow4 (WebBrowser1.Document). hasfocus then
Bytes -----------------------------------------------------------------------------------
7. Click Submit.
Just as there is a "default" button on each Form in the program, each Form on the web page also has a "default" button-that is, the button with the attribute "Submit, when you press the Enter key, it is equivalent to clicking "Submit" with the mouse ". However, TWebBrowser does not seem to respond to the carriage return key. Even if the KeyPreview of a form containing TWebBrowser is set to True, the user's buttons sent to TWebBrowser cannot be intercepted in the KeyPress event of the form.
My solution is to use the ApplicatinEvents component or write the OnMessage event of the TApplication object, determine the Message Type in it, and respond to the keyboard message. You can click the "Submit" button to analyze the source code of the Web page. However, I have found two simple and quick methods. The first one is my own, the other is the code written by others, which is provided for reference.
A. Use the SendKeys function to send the return key to WebBrowser.
In Delphi
5. There is an SndKey32.pas file under the Info/Extras/SendKeys directory on the CD, which contains two functions: SendKeys and AppActivate. We can use the SendKeys function to send a carriage return key to WebBrowser, this method is used now. It is easy to use. When WebBrowser obtains the focus (the document contained in WebBrowser is not required to obtain the focus), use a statement:
Sendkeys ('~ ', True); // press RETURN key
Detailed parameter descriptions of the SendKeys function are included in the SndKey32.pas file.
B. In the OnMessage event, pass the received Keyboard Message to WebBrowser.
Procedure TForm1.ApplicationEvents1Message (var Msg: TMsg;
VaR handled: Boolean );
{Fixes the malfunction of some keys within webbrowser
Control}
Const
Stdkeys = [vk_tab, vk_return]; {standard keys}
Extkeys = [vk_delete, vk_back, vk_left, vk_right]; {
Extended keys}
Fextended = $01000000; {extended key flag}
Begin
Handled: = false;
With MSG do
If (Message> = wm_keyfirst) and (Message <= wm_keylast ))
And
(Wparam in stdkeys) or
{$ Ifdef ver120} (getkeystate (vk_control) <0) or {$ endif}
(Wparam in extkeys) and
(Lparam and fextended) = fextended) then
Try
If IsChild (Handle, hWnd) then {handles all browser
Related messages}
Begin
With {$ IFDEF
VER120} Application _ {$ ELSE} Application {$ ENDIF}
IOleInPlaceActiveObject do
Handled: = TranslateAccelerator (Msg) = S_ OK;
If not Handled then
Begin
Handled: = True;
TranslateMessage (Msg );
DispatchMessage (Msg );
End;
End;
Except
End;
End; // MessageHandler
(This method is from EmbeddedWB. pas)
Bytes -----------------------------------------------------------------------------------
8. Get the webpage source code and Html directly from TWebBrowser
The following describes an extremely simple method to obtain the web page source code that TWebBrowser is accessing. The general method is to use the IPersistStreamInit interface provided by the Document object in the TWebBrowser control, specifically: first check WebBrowser. if the Document object is valid or not, exit. Then, obtain the IPersistStreamInit interface, obtain the HTML source code size, allocate the global heap memory block, create a stream, and write the HTML text to the stream. Although the program is not complex, there are simpler methods, so the implementation code is not given. In fact, basically all the features of IE TWebBrowser should be implemented in a relatively simple way, the same is true for obtaining the web page source code. The following code displays the webpage source code in memo1.
Memo1.Lines. Add (IHtmlDocument2 (WebBrowser1.Document). Body. OuterHtml );
  
  
At the same time, it is easy to save the HTML file as a text file when you use TWebBrowser to browse the HTML file. No Syntax Parsing tools are required because TWebBrowser is also complete, as shown below:
Memo1.Lines. Add (IHtmlDocument2 (WebBrowser1.Document). Body. OuterText );
  
  
Bytes -----------------------------------------------------------------------------------
9. Search
The Search dialog box can be called by pressing Ctrl-F to get the focus of the document. In the program, the member function Exec of the IOleCommandTarget object is called to execute the OLECMDID_FIND operation, the following describes how to use code to select text in a program. That is, you can design your own Search dialog box.
Var
Doc: IHtmlDocument2;
TxtRange: IHtmlTxtRange;
Begin
Doc: = WebBrowser1.Document as IHtmlDocument2;
Doc. SelectAll; // This is short for. For how to select all documents, see the third command operation.
// This sentence is particularly important, because the premise that the IHtmlTxtRange object method can operate is
// The Document already has a text selection area. Since the following statement is executed, no
// View the process of selecting all documents.
TxtRange: = Doc. Selection. CreateRange as IHtmlTxtRange;
TxtRange. FindText ('text to be searched', 0.0 );
TxtRange. Select;
End;
Also, you can obtain the selected text content from Txt. Get_text, which is useful in some cases.
Bytes -----------------------------------------------------------------------------------
10. Extract all links on the webpage
This method comes from the answer to a question from a friend of the great millionaire BBs. I wanted to test it myself, but it was always unsuccessful.
Var
Doc: IHTMLDocument2;
All: IHTMLElementCollection;
Len, I: integer;
Item: OleVariant;
Begin
Doc: = WebBrowser1. Document as IHTMLDocument2;
All: = doc. Get_links; // doc. Links is also supported.
Len: = all. length;
For I: = 0 to a len-1 do begin
Item: = all. item (I, varempty); // EmpryParam is also supported
Memo1.lines. add (item. href );
End;
End;
Bytes -----------------------------------------------------------------------------------
11. Set TWebBrowser Encoding
Why do I always miss many opportunities? In fact, I should have thought of it for a long time. At that time, if I had to think more about it and try more, this would not have ranked 11th. The following is a function that is easy to imagine.
Procedure SetCharSet (AWebBrowser: TWebBrowser; ACharSet:
String );
Var
RefreshLevel: OleVariant;
Begin
IHTMLDocument2 (AWebBrowser. Document). Set_CharSet (ACharSet );
RefreshLevel: = 7; // This 7 should be from the Registry to help with bugs.
AWebBrowser. Refresh2 (RefreshLevel );
End;

From: satanmonkey, time: 8:32:06, ID: 2657028
Uses
Mshtml
...
Var
Doc: IHTMLDocument2;
Doc: descriwebbrowser1.doc ument as IHTMLDocument2;

Then, access what you want.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.