У меня есть компонент БД, который DataLink.UpdateRecord вызывается, когда он получает сообщение CM_EXIT. Это сообщение отправляется, когда оно теряет фокус. Когда я нажимаю кнопку публикации, она не теряет фокус, и значение не записывается в источник данных. Как я могу добиться эффекта потери фокуса компонента, не переключая его на другой?
Как убрать фокус с текущего компонента?
Ответы (4)
Вы можете использовать:
procedure TCustomForm.DefocusControl(Control: TWinControl; Removing: Boolean);
person
André
schedule
15.02.2010
Я посмотрел на эту процедуру, попытался использовать ее, и это не сработало. Теперь я сделал это снова, и это работает. Пора спать :)
- person LukLed; 15.02.2010
Как оказалось, установка Self.ActiveControl := nil тоже делает свою работу и более интуитивно понятна. Явно не для меня....
- person LukLed; 15.02.2010
@LukLed Спасибо, это здорово!
- person user1580348; 28.05.2017
Мы достигаем этого, устанавливая 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;
person
Mark Elder
schedule
15.02.2010
Посмотрите на TCustomForm.FocusControl
. Вы не можете заставить его потерять фокус, не переключая фокус на что-то другое, но вы можете переключиться, а затем сразу же переключиться обратно, что, вероятно, сработает.
person
Mason Wheeler
schedule
15.02.2010
И как мне это сделать с помощью FocusControl? Вызов его на активном элементе управления не запускает события.
- person LukLed; 15.02.2010
В оконном блоке есть функция SetFocus. Попробуй это:
Windows.SetFocus(0);
person
Balu
schedule
24.01.2014
Было бы здорово, так как я ищу глобальный уровень для достижения этой цели. К сожалению, я только что попробовал в форме
OnCreate
и OnShow
, но фокус все равно остался.
- person Jerry Dodge; 26.02.2019
OnCreate
илиOnShow
формы.OnActive
работает, но затем что-то все равно получает фокус после простого нажатия на форму. - person Jerry Dodge   schedule 26.02.2019