使用者習慣輸入完帳號按 Enter 移至密碼欄,但預設 Enter 會觸發預設按鈕 (Default 按鈕) 的 OnClick,導致提前送出表單。需攔截 Enter 鍵並轉發為 Tab 行為。
procedure TForm1.EditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then // Enter
begin
// 若焦點在 TDBGrid 內,改為欄位間導航
if ActiveControl is TDBGrid then
begin
with TDBGrid(ActiveControl) do
begin
if SelectedIndex < FieldCount - 1 then
SelectedIndex := SelectedIndex + 1
else
SelectedIndex := 0; // 循環到第一欄
end;
end
else
begin
// 一般控制項:模擬 Tab 移至下一個
Key := #0; // 吞掉 Enter,避免觸發預設按鈕
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end;
end;
KeyPreview := True,在表單 OnKeyPress 集中處理,或OnKeyPress 事件處理器。若某些控制項需保留 Enter 原本功能 (如 Memo 換行、按鈕點擊),可加入判斷:
if (ActiveControl is TMemo) or (ActiveControl is TButton) then Exit;
Key := #0 將字元設為 NUL,阻止後續處理 (含預設按鈕點擊)。Perform(WM_NEXTDLGCTL, 0, 0) 發送對話方塊導航訊息,等同按下 Tab。TDBGrid.SelectedIndex 控制當前焦點欄位,實現欄位間 Enter 導航。