Fusion Technology between Delphi and WORD

zhaozj2021-02-16  51

Fusion Technology between Delphi and Word YZHSHI@263.net

First, VBA code meaning

Microsoft Word is an integrated environment, which is the word processing system of Microsoft, but it is not just a word processing system. It integrates Microsoft Visual Basic, which can be programmed to extension to Word features.

Microsoft Visual Basic's code in Word is the macro of Word, by writing a Word macro, can implement some document processing, such as automatic backup, storage, etc. to implement documents, can extend the function of the Word document, so it can make full use of Word Features, even make Word a part of our software.

Word's macro is only part of it, because it can help us achieve the automation of documents, but Word's macro is not purely beneficial, sometimes it may endanger our documentation, computer system and even network, from the most beginning TAIWAN NO1 macro virus Go to the current Melissa macro virus, from the starting simple tips, exhaust the system resources to the current e-mail, send personal information to the network, even to the hard disk's autoexec.bat (automatic batch file) Add DELTREE C: -Y to destroy the entire Windows system.

Second, COM technology in Word can say that Word is the best software for COM technology, which seems to be too extreme, but the powerful programming interface technology provided by Word can be any of our controlled Word. Part. Whether it is the opening of the file, the storage, printing is the automatic drawing of the table in the document. By programming software, you can flexible manipulation of Word, which is only described in detail with Borland Delphi: 1. Calling Word Software / files in Delphi, calling Word software in Word, summarizing three methods:. Tolecontainer through Delphi to embed Word into a. Call Word using the Servers control provided by Delphi, using the word attribute B. By real COM technology, put all the libraries in the office software in the office software msword9.olb into Delphi, using COM technology programming c. Word will start using CreateoleObject, and then control Word in OLE mode.

2. Judgment of the difficulty of several methods

a. Controls for Delphi Tolecontainer will embed Word

This is the simplest OLE embedding, you can directly call the Word document, just start the Word document directly. And the Word document with this started and the delphi program is a whole (see on the interface), but it does not overcome the shortcomings, that is, the Word document cannot be controlled by Delphi, and cannot be flexible to manipulate the purpose of Word.

b. Calling Word using the Servers control provided by Delphi, using the attribute of the Word to manipulate the word, when programming, Delphi can implement code prompt, overall, can better implement Delphi's control for Word, but there are Some Word features cannot be called in Delphi (such as the VBA macro code written). And when implementing functions, the optional parameters in the VBA code must be added at the Delphi call, otherwise, even compilation cannot pass. The Word and Delphi program initiated in this way are two forms. This method can only be used as a reference.

c. Through the real COM technology, all the class libraries in the Office software catalog in the Office software directory into Delphi, using COM technology to program the real COM technology, use the MSWORD9.OLD file class library, then use COM technology to carry out use. The whole is similar to the Servers control using Delphi, a bit more troublesome than the Servers control, the advantages and disadvantages are the same as the Servers control. d. Use CreateoleObject will start Word and then control the Word in an OLE mode. This method is to use the CreateoleObjects mode to call Word, actually OLE, but this way can truly control the Word file, you can use all properties of Word, including your own VBA macro code. Compared with the Servers control and COM technology, this method can truly use the various properties of Word, and the code that is written in VBA, the default code is not required. The Word and Delphi program initiated in this way are two forms. The disadvantage is that the use of this method has no Delphi code prompts, all exception processing requires yourself, and there may be more exploratory knowledge when writing.

Third, the Word Macro Editor Word can really perform the editing of VBA code, you can write forms, functions. Methods of entering the Word Macro Editor: Tools -> Macro -> Visual Basic Editor, you can enter the Visual Basic editor interface. The Word's Visual Basic editor interface and the real Visual Basic editor are basically the same, and this is no longer detailed. In VBA code, you can add user forms, modules, class modules. The concept of user form, module, class module is identical, and Visual Basic. The comments are also identical to Visual Basic. The cursor can be done on any subroutine of the form and module, press "F5" to run the current subroutine directly.

4. Overview of Word Macros WORD fully combines document editing and VB to truly implement the documentation. Using Word Programming, similar to using Visual Basic, where is in Word, you can directly run a subroutine, see the result, Word's macro, can only interpret the run, and Visual Basic, now you have written into true The machine code, from the code of the code, should reduce the number of Word's VBA code, especially the critical code as much as possible. The VBA macro can be divided into four: 1, and the same macro, FileSave, FileOpen, which contains the same name with Word in the VBA code, and ignore the Word itself command. 2, Word's specific macro these macro contains AutoExec (starting Word or load global template), AutoOpen (when new documentation), AutoOpen (time to open an existing document), AutoExit (When you exit Word or uninstall global template). If the VBA code contains a function of these names, the corresponding condition is met, the corresponding code is automatically executed. 3, the VBA macro of the corresponding event is a macro triggered by an event. If Document_Close triggers events when the document is turned off, Document_New is triggered when the document is created, and Document_Open triggers when the document is opened. 4, the independent macro you wrote the VBA code, that is, the VBA code that is not above the above case, can be called by other VBA code, more importantly, can be called by other programs. In this way, we can discard the macro executed by Word, and call the corresponding macro directly through Delphi to achieve the purpose. [B] V. Detailed Description of Word Command Macro [/ b] The command function of Word itself contains a lot, but whether it is Word online help or MSDN help, there is no introduction in this regard, so it can only explore its own experiment. function preliminary probe follows: macro name interpreted comments FileNew New FileNewDefault New blank document FileSaveAs Save as FileOpen open FileClose close FilePrint print FilePrintPreview Print preview ToolsCustomize toolbar inside custom ToolsOptions tool options ToolsRevisions highlight Changes ToolsReviewRevisions Accept or reject Changes ToolsRevisionMarksAccept accept the amendment ToolsRevisionMarksReject reject changes ToolsRevisionMarksToggle revised ToolsMacro macro ToolsRecordMacroToggle record new macro ViewSecurity security ViewVBCode view the VB editor environment FileTemplates templates and add-ins ToolsProtectUnprotectDocument unprotect InsertHyperlink of the document into hyperlinks EditHyperlink edit hyperlinks DeleteHyperlink delete hyperlinks EditLinks view, delete links EditPasteAsHyperlink Paste Hyper Link FormatStyle Style EditBookmark Bookmark Oleword Some Useful Code YZHSHI@263.net

First, the Delphi program launches Word to start Word, call VBA code, the specific implementation process is: First use getActiveoleObject ('word.application') to determine if there is a Word program in the current memory, if present, then directly, if Without a Word program, use CreateoleObject ('Word.Application') to start Word II, Delphi Program New Word Format: WordDocuments.Add (Template, NewTemplate, DocumentType, Visible) Template: Using Templates Name, NewTemplate: New Document Type True is expressed as template, False is expressed as document DocumentType: Document type, default is blank document Visible: Whether the window is visible

Example: doc_handle: = word_ole.documents.add (Template: = 'c: /temlate.dot' ,newtemplate: = false);

Three, Delphi program to open Word document format: WordDocuments.Open (FileName, ConfirmConversions, ReadOnly, PassWordDocument, PasswordTemplate, Revent, WritePasswordDocument, WritePassWordTemplate, Format, Encoding, Visible)

FileName: Document Name (included path) ConfirmConversions: Whether to display file conversion dialog readonly: Do you open document in read-only mode: Whether to add a file to the recently used file list of the file at the bottom of the File menu: Open this document Needed password PasswordTemplate: The password required when opening this template: If the document has been reopened WritePasswordDocument: Save the password required for the document change WritePasswordTemplate: Save the password required for the template to change the password Format: Open the document Document Converter Encoding: Document Code Page Visible: Opens the window of the document visible

Example: doc_handle: = word_ole.documents.open (filename: = DOC_FILE, Readonly: = false, addtorecentfiles: = false);

Four, Delphi program save Word presentation Format: WordDocuments.SaveAs (FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter)

FileName: File name. The default is the current folder and file name. FileFormat document saved format. Lockcomments If you are True, this document only allows annotations. Password opens the password when documentation. AddTorecentFiles If true, add a document to the "File" menu in the list of documents. WritePassword saves the password required to modify the document. ReadonlyRecommended If you are True, Word will recommend a read-only mode when you open a document each time you open a document. EmbedTrueTypefonts If you are TRUE, you save the document with the TrueType font. SavenativePictureFormat If true, the graphically imported graphics imported from other system platforms (such as Macintosh) only saves its Windows version. SaveFormsData If True, save the data in the form into a data record. SaveASaocletter If the document contains an additional, when this property value is TRUE, the document is saved as an AOCE letter (simultaneously). Example: Word_ole.documents.saveas (filename: = doc_file, fileformat = wdformator, addtorecentfiles = false);

5. Read files from the database to the local hard drive and read files from the local hard drive to the database

Use the Image binary field on the database to use the Stream stream.

Create a file stream: Word_FileStream: = TFileStream.create (target_name, fmopenwrite or fmcreate); Word_FileStream.position: = 0;

Image field saved to the database: tblobfield (adoQuery1.fieldbyname). Savetostream (Word_FileStream);

Read files from the database to the local hard drive: TBLOBFIELD (AdoQuery1.fieldByname (Column_name)). LoadFromstream (Word_FileStream);

Release file stream: Word_FileStream.free;

Sixth, the definition of global messages Because Word and Delphi programs are two software, communication between each other is more troublesome, so the method of global messages is used. Global message must first register, Windows returns the message number of the system, when the registered message is the same, the Windows system returns the same value, which ensures that the message number is communicating between the two programs.

Method for defining the message: szMessageString: pchar = 'xidian_11_stone'; fmyjoinMessage: = registerWindowMessage (SzmessageString);

Method for sending messages: sendMessage (other handle, message, message with short variable, message with long variable)

7. The method of the Delphi program receives the message, the Delphi receives the message, one is to overload a specific message, and the other is to overload the WndProc function, and the corresponding message is selected in it. Fifth, only one message can be handled each time, and the second can handle multiple messages simultaneously.

For the method, the declaration is as follows: Procedure WndProc (Var message: tMessage); Override must pay attention to the WndProc (Message) function after processing your message processing, otherwise the system will crash! Eight, the dynamic generation of the Combo dialog box in Word, and the Change event creation class module ComboHander, internally defined events public WitHevents ComboBoxEvent As Office.comMandbarCombox

Define module DIM CTLCOMBOXHANDAL AS New ComboBoxHandler

Generate Combo-dialog SET CBO_CHOOSEDOC = Commandbars ("Add Menu") .controls.add (Type: = msoControlComboBox, TempoRoRary: = true)

Perform file handle settings to generate Combo_Change events set ctlcomboBoxHandler.comBoboxEvent = CBO_CHOOSEDOC

After generating an event, select ComboBoxEvent's Change Event in Class Module ComboHander, you can write event code SUB ComboBoxEvent_change (Byval Ctrl as Office.commandbarComboBox)

Nine, some Word events in the VBA code have: DocumentBeforeClose, DocumentChange, which is: DocumentBeforeClose, DocumentChange.

Document_close: Events Generate Event DocumentBeforeClose when the document is turned off: Before the document is turned off, the Word determines whether the document is saved, gives the corresponding prompt and processed accordingly. DocumentChange: Document Switching, switching between documents to switch between documents and other people modified by other people, primarily handle setting document authority, etc.

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

New Post(0)