The classic rule in Windows is that you cannot change focus during the focus change event. The OnDeactivate
event occurs during a focus change event. Your form says that it is deactivated - the OS does not request permission - and at the same time, it tells the other form that it is being activated. No window has the right to speak on this issue, and an attempt to change focus during these events will lead to confusion of all windows. Symptoms include the presence of two windows that draw themselves, as if they have focus, and messages with the keyboard go nowhere, despite the fact that the input cursor blinks. MSDN is even more terrible, although I have never seen anything wrong:
When processing this message [ WM_KILLFOCUS ], do not make any function calls that display or activate the window. This causes the thread to take control and may cause the application to stop responding to messages. See Message Alerts for more information.
Since you cannot deny a change in focus after it has begun, you need to do so to postpone the processing of the event until everything goes down. When your editing form is deactivated and the data on it is still invalid, publish the message form. Posting puts the message at the end of the message queue, so it will not be processed until all previous messages, in particular notifications of focus changes, are processed. When the message arrives, indicate that the data is invalid and set the focus back to the editing form:
const efm_InvalidData = wm_User + 1; type TEditForm = class(TForm) ... private procedure EFMInvalidData(var Msg: TMessage); message efm_InvalidData; end; procedure TEditForm.FormDeactivate(Sender: TObject); begin if DataNotValid then PostMessage(Handle, efm_InvalidData, 0, 0); end; procedure TEditForm.EFMInvalidData(var Msg: TMessage); begin Self.SetFocus; ShowMessage('Invalid data'); end;
I must point out that this answer does not technically answer your question, since it does nothing to prevent the decontamination of the form, but you rejected my other answer , which really prevents decontamination.
Rob kennedy
source share