1. 程式人生 > 實用技巧 >delphi 設定預設控制元件得到焦點

delphi 設定預設控制元件得到焦點

如果同一窗體有多個按鈕的話,追蹤原始碼發現最後是taborder來的

如: 在空白窗體上拖入兩個button (btn1,btn2)

如果在btn2設定default = True 執行後,預設焦點還是在btn1上。需要把btn2的taborder設定為0才可以。

如此看來還是以taborder 來認的。

 1 procedure TCustomForm.SetActive(Value: Boolean);
 2 begin
 3   FActive := Value;
 4   if FActiveOleControl <> nil then
 5     FActiveOleControl.Perform(CM_DOCWINDOWACTIVATE, Ord(Value), 0
); 6 if Value then 7 begin 8 if (ActiveControl = nil) and not (csDesigning in ComponentState) then 9 ActiveControl := FindNextControl(nil, True, True, False); 10 MergeMenu(True); 11 SetWindowFocus; 12 end; 13 end;

其中的FindNextControl 可以看出是gettaborderlist來認的

 1 function TWinControl.FindNextControl(CurControl: TWinControl;
2 GoForward, CheckTabStop, CheckParent: Boolean): TWinControl; 3 var 4 I, StartIndex: Integer; 5 List: TList; 6 begin 7 Result := nil; 8 List := TList.Create; 9 try 10 GetTabOrderList(List); 11 if List.Count > 0 then 12 begin 13 StartIndex := List.IndexOf(CurControl);
14 if StartIndex = -1 then 15 if GoForward then StartIndex := List.Count - 1 else StartIndex := 0; 16 I := StartIndex; 17 repeat 18 if GoForward then 19 begin 20 Inc(I); 21 if I = List.Count then I := 0; 22 end else 23 begin 24 if I = 0 then I := List.Count; 25 Dec(I); 26 end; 27 CurControl := List[I]; 28 if CurControl.CanFocus and 29 (not CheckTabStop or CurControl.TabStop) and 30 (not CheckParent or (CurControl.Parent = Self)) then 31 Result := CurControl; 32 until (Result <> nil) or (I = StartIndex); 33 end; 34 finally 35 List.Free; 36 end; 37 end;