承接前文架構,本文深入剖析 PassForm.dll 兩大核心窗體的內部實現細節,展示 Delphi 如何在 DLL 中封裝複雜的視覺化邏輯與狀態管理。
type
TSetPassWordForm = class(TForm)
Label1: TLabel; Edit1: TEdit; OKBtn, CancelBtn: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
private
Verified: Boolean; // 確認狀態旗標
public
PassWord: PChar; // 儲存設定的密碼(供外部輸出)
end;
procedure TSetPassWordForm.FormCreate(Sender: TObject);
begin
Verified := False;
PassWord := StrAlloc(40); // 分配緩衝區
OKBtn.Enabled := False; // 預設禁用確定鍵
Label1.Caption := 'Please Input PassWord:';
end;
透過 OKBtn.Enabled := False 強制用戶完成「輸入→確認」雙重驗證流程,唯有密碼正確設定後才啟用確定鍵,確保資料完整性。
procedure TSetPassWordForm.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Edit1.Text = '' then Exit;
if Key = #13 then begin // Enter 鍵觸發
if Verified then begin // 第二次輸入:驗證一致性
if StrPas(PassWord) = Edit1.Text then begin
OKBtn.Enabled := True; Edit1.Enabled := False; OKBtn.SetFocus;
end else begin // 不一致:重置重來
Verified := False;
MessageDlg('PassWord is InValid.', mtWarning, [mbOK], 0);
Edit1.Text := ''; PassWord := '';
Label1.Caption := 'Please Input PassWord:';
end;
end else begin // 第一次輸入:記錄密碼,進入確認階段
Verified := True;
StrPCopy(PassWord, Edit1.Text);
Edit1.Text := '';
Label1.Caption := 'Please Verify PassWord:';
end;
Key := #0; // 吞掉 Enter,避免發出嗶聲
end;
end;
function GetPassword(Password: PChar): Boolean;
var GetPasswordForm: TGetPasswordForm;
begin
Result := False;
GetPasswordForm := TGetPasswordForm.Create(Application);
try
with GetPasswordForm do
if ShowModal = mrOK then
if UpperCase(Edit1.Text) <> StrPas(StrUpper(Password)) then
MessageDlg('Invalid Password', mtWarning, [mbOK], 0)
else
Result := True;
finally
GetPasswordForm.Free; // 確保資源釋放
end;
end;
ShowModal 模態顯示,阻塞呼叫端直到用戶操作完成。UpperCase),提升用戶友善度。try...finally 保證窗體實例在任何異常情況下都能正確釋放。library PassForm;
uses GetPass in 'GETPASS.PAS' {PasswordForm},
SetPass in 'SETPASS.PAS' {SetPassWordForm};
exports GetPassword, SetPassWord;
begin end.
exports 子句將兩個函式公開為 DLL 進入點,供外部應用靜態或動態連結。
StrAlloc),否則 StrCopy 會觸發 GPF。try...finally 配合 Free 是 Delphi 管理視窗資源的標準慣例。PasswordChar 屬性控制回顯字元(如 *),增強安全性。此範例完美示範了 Delphi 將完整視窗邏輯(狀態機、驗證流程、資源管理)封裝進 DLL 的最佳實踐,為構建企業級可復用 UI 元件庫奠定基礎。