如何从当前关注的组件中删除焦点?

Luk*_*Led 6 delphi focus delphi-7

我有一个数据库组件,当接收到CM_EXIT消息时,会调用DataLink.UpdateRecord.失去焦点时会发送此消息.当我单击发布按钮时,它不会失去焦点,并且值不会写入数据源.如何在不将焦点转移到其他组件的情况下实现组件失去焦点的效果?

And*_*dré 10

你可以使用:

procedure TCustomForm.DefocusControl(Control: TWinControl; Removing: Boolean);
Run Code Online (Sandbox Code Playgroud)

  • 当它发生时,设置Self.ActiveControl:= nil也可以完成工作并且更直观.显然不适合我.... (9认同)
  • 我查看了这个程序,尝试使用它,但它没有用.现在我又做了它,它的工作原理.是时候去睡觉了:) (2认同)

Mar*_*der 8

我们通过设置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;
Run Code Online (Sandbox Code Playgroud)