Delphi

How to Ensure TEdits are defocused and changes saved on form closure

Some controls that create edit boxes or combos to allow editing of the information they display, for example the TVirtualStringTree, component do not loose the focus when a form is closed, and as such the changes to the edit are not applied. This can be fixed easily with a one-liner.

To ensure that popup edits, independant of the type of control have finished editing, i.e. have lost their focus when a form is closed, simply put the following line in the closequery event.

if assigned(ActiveControl) and (ActiveControl).Focused then DefocusControl(ActiveControl,false);

This line will ensure that the current control that has focus is defocused. It basically checks to see if a control is focused and if it is, Defocuses it.  This should work with all controls, e.g. dropdowns, edits and ensures that edit changes are committed.