Old article - TWEBBROWSER programming

xiaoxiao2021-03-06  71

Speech

This article was first published on July 25, 2000. The last revision was on February 07, 2001. The purpose of this again, one is the end of the previous stage, so the errors in the article do not make changes; the other is the hope as a new starting point. I am going to organize the knowledge of the browser programming, which is accumulated, and more written, and with netizens.

Tevebrowser programming

Abstract: Delphi 3 starts with TWEBBROWSER components, but it appears in the form of ActiveX controls, and it is necessary to introduce itself. In its subsequent 4.0 and 5.0, it is in the packaged shdocvw.dll as an Internet component group. An appearance is on the component panel. Often heard someone to help Delphi is very poor, this TWebBrowser is Microsoft's stuff, naturally will not get better, although there is everything on MSDN, but the content is too interable, if there is no entry point more It is an annoying thing, finding a feeling of people can be described in one sentence: very complicated, complicated.

Here is some examples and information collected by TWebBrowser to collect the programs in the Internet, and hopes that you can bring some help to friends who are interested in programming with TwebBrowser.

1. Initialization & Finalization, you may have encountered a "OLE Object" or "OLE Object" or "OLE object" or "OLE object" or "OLE object" attempts to activate unregistered missing targets "or" OLE object "or" OLE object "in executing a method of performing TWEBBROWSER, such as Execwb et al. "Waiting for errors, or there is no error, but does not have a desire result, such as copying the selected webpage content to the clipboard. When I used it before, I found that Execwb sometimes hung's role but sometimes, I didn't do TwebBrowser on the default engineering main window generated by Delphi, and the "OLE Object Unregistered" error occurred. It is also an accidental opportunity, I know that the OLE object needs to initialize and terminate (knowing that the Dongdong is too small). I used my previous article "Delphi program window animation & normally arranged the solution" to solve the method, running out the mistakes mentioned above, I guess the statement such as Oleinitialize, so, Found and add a few words below, finally get it! The reason, I think about because TWebBrowser is an embedded OLE object and is not a VCL written in Delphi.

Initialization Oleinitialize (NIL); Finalization Try OleunInInInIze; Except End;

These sentences are placed behind the main window, "end." Before.

-------------------------------------------------- -------------------------------------------------- ----

2, EMPTYPARAM

The NaviGate method of TWEBBROWSER in Delphi 5 has been overloaded 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 applications, when using the latter method, we rarely use several parameters, but the function declaration is required to be variable parameters, the general practices are as follows:

Var T: olevariant; begin webbrowser1.navigate (edit1.text, t, t, t, t); end;

It is very troublesome to define variable t (there are many places to use it). In fact, we can use EmptyParam instead (EmptyParam is a public Variant empty variable, do not assign it), just one sentence:

WebBrowser1.naviGate (Edit1.Text, EmptyParam, EmptyParam, EmptyParam, EmptyParam);

Although a little longer, it is much easier to define variables each time. Of course, the first way can also be used.

WebBrowser1.naviGate (Edit1.Text)

-------------------------------------------------- -------------------------------------------------- ----

3, command operation

Commonly used command operations can be completed using an ExecwB method, and Execwb has also been overloaded many times:

procedure ExecWB (cmdID: OLECMDID; cmdexecopt: OLECMDEXECOPT); overload; procedure ExecWB (cmdID: OLECMDID; cmdexecopt: OLECMDEXECOPT; var pvaIn: OleVariant); overload; procedure ExecWB (cmdID: rOLECMDID; cmdexecopt: OLECMDEXECOPT; var pvaIn: OleVariant; var PVAOUT: OLEVARIANT; OVERLOAD;

Open: A "Open Internet Address" dialog box pops up, and CommandId is OLECMDID_OPEN (if the browser version is IE5.0, this command is not available). Save As: Call the Save As dialog. Execwb (OLECMDID_SAVEAS, OLECMDEXECOPT_DODEFAULT, EMPTYPARAM, EMPTYPARAM);

Print, Print Preview, and Page Settings: Call "Print", Print Preview, and Page Setup dialog (IE5.5 and above to support print previews, so the implementation should check if 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); Cut, Copy, Paste, Select : There is no need to say, you need to pay attention to: cutting and paste not only pair the edit box text, but also to the non-edit box text on the web, may make a special stuff. There are two ways to obtain its command enable state and execution commands (with copying as an example, cut, paste, and allocation to replace the respective keywords, respectively, Cut, Paste and Selectall): a, use TwebBrowser QueryStatusWB method. if (QueryStatusWB (OLECMDID_COPY) = OLECMDF_ENABLED) or OLECMDF_SUPPORTED) then ExecWB (OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT, EmptyParam, EmptyParam); B, with the IHTMLDocument2 QueryCommandEnabled method. Var Doc: htmldocument2; begin doc: = webbrowser1.document as htmldocument2; if doc.querycommandenabled ('Copy') Then Doc.execCommand ('Copy', False, EmptyParam);

Find: Refer to Article 9 "Find" function.

-------------------------------------------------- -------------------------------------------------- ----

4, font size

Similar to the "Maximum" menu (the maximum "to" minimum "(corresponding integer 0 ~ 4, Largest, etc., the name of the five menu items, the TAG attribute is set to 0 ~ 4). A, read the current page font size. var t: OleVariant; Begin WebBrowser1.ExecWB (OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, EmptyParam, t); case t of 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; larse; 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); -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- ----------------------

5, add to favorites and finishing favorites

Const CLSID_SHELLUIHELPER: Tguid = '{64AB4BB7-111E-11D1-8F79-00C04FC2FBE1}';

VAR P: ​​Procedure (Handle: Thandle; Path: pchar); stdcall;

Procedure tform1.organizefavorite; var h: hwnd; begin h: = loadinglibrary (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) as IShellUIHelper; ShellUIHelper.AddFavorite (url, title); end; end; used above The method of opening the Add to Favorites dialog through the iShelluiHelper interface is relatively simple, but there is a defect, that is, the window is not a mode window, but independent of the application. Imagine, if you open the dialog using the same method as the OrganizeFavorite process, you can naturally implement the mode window because you can specify the handle of the parent window (the effect is the same as the "Add to Favorites" dialog box in the Explorer. . The problem is obviously like this. The author of the above two processes only knows the prototype of Doorganizefavdlg in shdocvw.dll at the time, so I have to implement the ISHELLUIHELPER interface (perhaps he is not rigorous enough, think it is the model window does not matter? ). The following procedure tells you the function prototype of DoaddTofavdlg. It should be noted that this open dialog does not perform the "Add to Favorites" operation, it just tells the application user to select "OK", and return to the user in the second parameter of DoaddTofavdlg to place the Internet Express The way the way is created .url file works by the application yourself.

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: = htmldocument2 (IE.Document); if fdoc = nil dam; s (Title, fdoc.get_title; strpcopy (url, fdoc.get_ur); if url <> '' Then Begin H: = loadingLibrary (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; FreeELELIBRARY (H); if Fretok Ten CreateURL (URLPATH, URL); end end; ------- -------------------------------------------------- -----------------------------------------------

6, get webbrowser to get focus

TWEBBROWSER is very special, it does not allow the setfocus method inherited from TwinControl to get the documentation to get the focus, so that you cannot use the Internet Explorer itself with shortcuts, 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, here is listed here: if WebBrowser1.Document <> nil damlwindow2 (webbrowser1.document) .parentWindow) .focus .focus

Just found a simpler method, perhaps the simplest:

IF WebBrowser1.Document <> nil damlwindow4 (webbrowser1.document) .focus

Also, you need to judge whether the document gets focusing:

IHTMLWindow4 (WebBrowser1.document) .hasfocus

-------------------------------------------------- -------------------------------------------------- ----

7. Click the "Submit" button

Like a "default" button on each form in the program, each form on the web page also has a "default" button - that is, the property "submit" button, when the user presses the Enter key It is equivalent to the mouse click "Submit". But TWEBBROWSER does not seem to respond to the Enter key, and even if the keypreview containing the TWebBrowser form is set to True, the key to TWEBBROWSER is not intercepting the button of the TWEBBROWSER. My solution is to use the Applicatinevents component or write the onMessage event of the Tapplication object yourself, and determine the message type and respond to the keyboard message. As for the "Submit" button, you can implement the method of analyzing the web source code, but I found more simple and fast methods, there are two kinds, the first one is what I think, the other is someone writing. Code, here are all available to do this.

A. Send the Enter button to WebBrowser in the info / extras / sendkeys directory on the Delphi 5 disc, which contains two functions and appactivate, which we can send WebBrowser with the SendKeys function. Enter key, I am using this method now, using very simple, in the case of WebBrowser gets focus (not required to get the document included in WebBrowser), use a statement:

SendKeys ('~', true); // Press Return Key

The detailed parameter description of the SendKeys function is included in the SNDKEY32.PAS file.

B, pass the keyboard message accepted to WebBrowser in the OnMessage event.

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} as IOleInPlaceActiveObject do Handled: = TranslateAccelerator (Msg) = S_OK; if not Handled then begin Handled: = True; TranslateMessage (Msg); DispatchMessage (Msg); end END; Except End; end; // messageagehandler (this method comes from Embeddedwb.pas)

-------------------------------------------------- -------------------------------------------------- ----

8, get the web source code and HTML directly from TWebBrowser

Let's first introduce an extremely simple way to get TWEBBROWSER is accessing the web source code. The general method is to implement the IPersistStreaminit interface provided by the Document object in the TWebBrowser control. Specifically, check if the webbrowser.document object is valid, if you quit; then get the IPersistStreaminit interface, then get the size of the HTML source code, allocate in the global heap memory block , Establish a stream, write HTML text to the stream. Although the program is not complicated, there is a simpler method, so the code is not given. In fact, all IE functions TWEBBROWSER should have a simpler way to achieve, and the source code is also the same. The following code displays the web source code in MEMO1.

Memo1.Lines.Add (IHTMLDocument2 (WebBrowser1.Document) .Body.outerHTML;

At the same time, it is very simple to save it as a text file when browsing the HTML file with TWebBrowser, does not need any syntax parsing tool, because TWebBrowser is also completed, as follows: Memo1.Lines.Add (IhtmlDocument2 (webbrowser1.document) .Body.outertext);

-------------------------------------------------- -------------------------------------------------- ----

9, "Find" function

The Find Dialog box can be called by the button Ctrl-f when the document gets focus. The program is called the member function of the IOLCOMMANDTARGET object executes OLECMDID_FIND operations to call, how is the method given in the program? Text selection, you can design the lookup dialog box yourself.

VAR DOC: htmldocument2; txtrange: htmltxtXtrange; begin doc: = webbrowser1.document as htmldocument2; doc.selectall; // This is short, select all documents, please refer to Article 3 Command Operation // This sentence is especially important. Because the premise of the IHTMLTXTRANGE object is to operate, // Document already has a text selection area. Since the following statement is then performed, the process of selection of documents will not be //. TXTRANGE: = doc.selection.createrange as htmltxtXtrange; txtrange.findtext ('text to be search ", 0.0); txtrange.select;

Also, from txt.get_text can get the currently selected text content, some useful.

-------------------------------------------------- -------------------------------------------------- ----

10. Extract all links in the page

This method comes from the answer to a question of a question from the Dafan Forum Hopfield, I want to test myself, but I have not succeeded.

var doc: IHTMLDocument2; all: IHTMLElementCollection; len, i: integer; item: OleVariant; begin doc: = WebBrowser1 .Document as IHTMLDocument2; all: = doc.Get_links; //doc.Links also len: = all.length; For i: = 0 to Len-1 Do Begin Item: = All.Item (i, Varempty); // EmpRyParam can also memo1.Lines.Add (item.href); end;

-------------------------------------------------- -------------------------------------------------- ----

11, set the encoding of TWEBBROWSER

Why do I always miss a lot of opportunities? In fact, I have already thought of it, but the difference is the difference in the world. At that time, I would like to consider it more, and I will not be able to rank 11. A function is given below, it is easy to imagine. procedure SetCharSet (AWebBrowser: TWebBrowser; ACharSet: String); var RefreshLevel: OleVariant; Begin IHTMLDocument2 (AWebBrowser.Document) .Set_CharSet (ACharSet); RefreshLevel: = 7; // 7 this should come from the registry, help the Bug. AWEBBROWSER.REFRESH2 (REFRESHLEVEL);

-------------------------------------------------- -------------------------------------------------- ----

12. Activate the problem of the menu when you enter characters in TWebBrowser.

Many friends have encountered such a problem when they are programmed. When entering the TWebBrowser, the typed characters are activated if the menu is the same as the menu (menu made with Toolbar). There is a friend solution to remove the "&" symbol in front of the accelerator button, so that the characters lose "acceleration" function, this method has not been tasted, but it is not "professional". In fact, we can think that it is to process the button first, because Toolbar itself is designed to implement a Windows new style menu, so you only need to modify the section of Toolbar's source code to process the menu button. However, the method is as follows:

1) Locate Comctrls.PAS in $ (Delphi) / Source / VCL directory, copy to your own program, and then open it. 2) Locate the TtoolBar.cmdialogchar process, annotate the process (if you want, you can modify it). 3) recompile your own procedure.

How is it, isn't it very simple? But it is really effective.

-------------------------------------------------- -------------------------------------------------- ----

13, remove the Twebbrowser scroll bar

By default, TWebBrowser is a scroll bar. Although we can set up no scroll bars in the web page, but sometimes there will be special requirements, for example, the webpage has scroll bar, but want to remove it. What should I do? ? Very simple, the two lines of code can be achieved below, which can be described as the same.

1), IHTMLBODYEELEMENTDISP (webbrowser1.document) .body). Scroll: = 'NO'; 2), webbrowser1.oleObject.document.body.scroll: = 'NO';

Note: The first method needs to add MSHTML_TLB or MSHTML in the USES section.

-------------------------------------------------- -------------------------------------------------- ---- 14, establish Internet shortcuts through the IUNIFORMRESOSOLOCATOR interface

The previous display of the "Add to Favorites" mode dialog box has set up an example of building an Internet shortcut, which is less specific, which belongs to a method of happens. The method described below is achieved by an interface.

procedure CreateIntShotCut (aFileName, aURL: PChar); var IURL: IUniformResourceLocator; PersistFile: IPersistfile; begin if Succeeded (CoCreateInstance (CLSID_InternetShortcut, nil, CLSCTX_INPROC_SERVER, IID_IUniformResourceLocator, IURL)) then begin IUrl.SetURL (aURL, 0); Persistfile: = IURL AS IPERSISTFILE; persistfile.save (StringToolestr (AfileName), false; end;

Where the IUNIFORMRESourceLocator interface is in Ieconst.Pas, IEConst.pas can find on the website IE & Delphi; the declaration of the IPersistFile interface is in ActiveX.PAS.

Note: The AURL parameters of this function must contain protocol prefixes, such as "http://eagleboost.myrice.com".

First date: July 25, 2000

Last modified date: February 07, 2001

Quote Address: Old Article - TWEBBROWSER Programming

转载请注明原文地址:https://www.9cbs.com/read-120388.html

New Post(0)