Mega Code Archive

 
Categories / Delphi / Examples
 

Ole

procedure TEditorForm.EditMenuCopyToWordClick(Sender: TObject); {copy ALL Editor text to Word for Windows (if present). Text is first copied via the Clipboard to a hidden 'reformat' RichEdit, where (screen) margins set by the user are RE-set back to 0. We do this because in the Editor we use 'FirstIndent' and 'RightIndent' Editor properties to set margins, and while this is an OK kind of solution we DON'T want the same margins appearing in Word because if the user then set print margins in Word the value they gave would then be added to the current margins and this is not good. Better to allow them to reformat their document in Word if necessary...} var oldLeftMargin, oldRightMargin: LongInt; MSWord: Variant; errorMessage, OLECommand: String; exePathName, tempFileName: String; edPlainText: Boolean; begin Screen.Cursor := crHourGlass; exePathName := Application.ExeName; exePathName := ExtractFilePath(exePathName); tempFileName := exePathName + 'TempDoc'; {next line is there to avoid copying an empty document...} if (Editor.GetTextLen > 0) then begin {keep track of current margins...} {oldLeftMargin := Editor.Paragraph.FirstIndent; oldRightMargin := Editor.Paragraph.RightIndent;} Editor.SelStart := 0; Editor.SelLength := Editor.GetTextLen; SendMessage(Editor.Handle, WM_COPY, 0, 0); Editor.SelLength := 0; SendMessage(ReformatRichEdit.Handle, WM_PASTE, 0, 0); {set the margins of the 'reformat' Rich Edit to 0...} ReformatRichEdit.SelStart := 0; ReformatRichEdit.SelLength := ReformatRichEdit.GetTextLen; ReformatRichEdit.Paragraph.FirstIndent := 0; ReformatRichEdit.Paragraph.RightIndent := 0;; ReformatRichEdit.SelLength := 0; {save text IN THE 'REFORMAT' RICHEDIT to file, IN RTF FORMAT...} ReformatRichEdit.Lines.SaveToFile(tempFileName); try OLECommand := 'Creating OLE Object.'; MSWord := CreateOLEObject('Word.Basic'); OLECommand := 'Show MS Word.'; MSWord.AppShow; OLECommand := 'Open document file >' + tempFileName + '<.'; MSWord.FileOpen(Name := tempFileName, ConfirmConversions := 0, ReadOnly := 0, AddToMru := 0, PasswordDoc := '', PasswordDot := '', Revert := 0, WritePasswordDoc := '',WritePasswordDot := ''); except on EOleException do begin errorMessage := 'Unable to copy current document into Word for Windows'; Application.MessageBox(PChar(errorMessage), ' OLE Error', mb_OK); end end; end else begin errorMessage := 'There is no text to copy into Word for Windows'; Application.MessageBox(PChar(errorMessage), ' Blank Document', mb_OK); end; {delete the temporary RTF file we have used to transfer data (so leaving it to the user to save the file in Word format if they choose to do so...} {-it doesn't matter if the file isn't there by the way...} DeleteFile(tempFileName); Screen.Cursor := crDefault; end;