首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 文字編輯器開發實戰:取代對話框、檔案對話框與列印功能

     編輯:Delphi

取代對話框實作

TReplaceDialog 擴充尋找功能,新增 ReplaceText 屬性與 frReplace、frReplaceAll 選項。OnReplace 事件處理邏輯:

procedure TEditForm.Replace(Sender: TObject);
var Found: Boolean;
begin
  with ReplaceDialog1 do
  begin
    if AnsiCompareText(Memo1.SelText, FindText) = 0 then
      Memo1.SelText := ReplaceText;
    Found := SearchMemo(Memo1, FindText, Options);
    while Found and (frReplaceAll in Options) do
    begin
      Memo1.SelText := ReplaceText;
      Found := SearchMemo(Memo1, FindText, Options);
    end;
    if (not Found) and (frReplace in Options) then
      ShowMessage('Cannot find "' + FindText + '".');
  end;
end;

開啟/儲存對話框進階選項

TOpenDialog/TSaveDialog 的 Options 屬性控制行為(ofAllowMultiSelect、ofFileMustExist、ofOverWritePrompt 等)。儲存前檢查唯讀屬性並備份:

function IsReadOnly(const FileName: string): Boolean;
begin
  Result := Boolean(FileGetAttr(FileName) and faReadOnly);
  if Result then MessageDlg(...);
end;

procedure TEditForm.Save1Click(Sender: TObject);
begin
  if (FileName = '') or IsReadOnly(FileName) then
    SaveAs1Click(Sender)
  else
  begin
    CreateBackup(FileName); // 更名備份
    Memo1.Lines.SaveToFile(FileName);
    Memo1.Modified := False;
  end;
end;

列印功能兩種實作方式

  1. 文字檔導向:AssignPrn、Rewrite、Writeln、Close。
  2. TPrinter 物件(推薦):Printer.BeginDoc、Canvas.TextOut、EndDoc、Abort 中止。配合 TPrintDialog 設定範圍、份數、印表機。
procedure TEditForm.Print1Click(Sender: TObject);
var DistanceLine, Line: Integer;
begin
  if PrintDialog1.Execute then
  begin
    Printer.Canvas.Font := Memo1.Font;
    DistanceLine := Trunc(1.5 * FontDialog1.Font.Size);
    OpenPrintCancelDialog; // 顯示取消列印對話框
    Printer.BeginDoc;
    for Line := 0 to Memo1.Lines.Count - 1 do
      Printer.Canvas.TextOut(0, DistanceLine * Line, Memo1.Lines[Line]);
    Printer.EndDoc;
    BtnBottomDlg.Free;
  end;
end;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved