如何取消当前聚焦组件的焦点?

8

我有一个数据库组件,当它接收到CM_EXIT消息时会调用DataLink.UpdateRecord函数。这个消息是在失去焦点时发送的。当我点击post按钮时,它不会失去焦点,值也不会被写入数据源。那么,如何使组件失去焦点而不需要切换到其他组件呢?


顺便提一下,以下解决方案似乎都不能在表单的“OnCreate”或“OnShow”事件中起作用。“OnActive”可以工作,但是在仅单击窗体后仍会出现某些焦点。 - Jerry Dodge
4个回答

15

你可以使用以下代码:

procedure TCustomForm.DefocusControl(Control: TWinControl; Removing: Boolean);

3
我查看了这个过程,尝试使用它,但它没有起作用。现在我重新操作一遍,它可以正常工作了。该睡觉了 :) - LukLed
14
当出现这种情况时,将Self.ActiveControl设置为nil也可以完成任务,并且更加直观。显然不是对我来说... - LukLed
@LukLed 谢谢,太好了! - user1580348

11
我们通过设置Self.ActiveControl := nil来实现这一点。这会触发所有的退出事件。在我们的场景中,我们还希望在保存完成后重新将焦点聚焦到控件上。这需要进行一些额外的检查,以确保我们有一个可以接受焦点的好控件。
procedure TSaleEditor.SaveCurrentState();
var
  SavedActiveControl: TWinControl;
  AlternateSavedControl: TWinControl;
begin

  // Force the current control to exit and save any state.
  if Self.ActiveControl <> nil then
  begin
    SavedActiveControl := Self.ActiveControl;

    // We may have an inplace grid editor as the current control.  In that case we
    // will not be able to reset it as the active control.  This will cause the
    // Scroll box to scroll to the active control, which will be the lowest tab order
    // control.  Our "real" controls have names, where the dynamic inplace editor do not
    // find an Alternate control to set the focus by walking up the parent list until we
    // find a named control.
    AlternateSavedControl := SavedActiveControl;
    while (AlternateSavedControl.Name = '') and (AlternateSavedControl.Parent <> nil) do
    begin
      AlternateSavedControl := AlternateSavedControl.Parent;
    end;

    Self.ActiveControl := nil;

    // If the control is a radio button then do not re-set focus
    // because if you are un-selecting the radio button this will automatically
    // re-select it again
    if (SavedActiveControl.CanFocus = true) and
      ((SavedActiveControl is TcxRadioButton) = false) then
    begin
      Self.ActiveControl := SavedActiveControl;
    end
    else if (AlternateSavedControl.CanFocus = true) and
      ((AlternateSavedControl is TcxRadioButton) = false) then
    begin
      Self.ActiveControl := AlternateSavedControl;
    end;

  end;

end;

3

请查看TCustomForm.FocusControl。你不能让它失去焦点而不切换到其他东西,但你可以先切换,然后立即切换回来,这可能会起作用。


我该如何使用FocusControl实现呢?在活动控件上调用它不会触发事件。 - LukLed

2
在Windows单元中有一个SetFocus函数。尝试使用以下代码: Windows.SetFocus(0);

很棒,因为我正在寻找全局级别来完成这个。不幸的是,我刚尝试了表单的 OnCreateOnShow,但焦点仍然在任何情况下都会进入。 - Jerry Dodge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接