Tuesday, November 29, 2005

Take Care When Changing FormStyle in Delphi

A new bug from my assessment-tool project pops up this morning. I wrote a Hotkey Configuration Component which enables the users to define their preferred hotkey mode for certain provided functions. On the other hand, there is an 'Always on Top' menu item in the main form. I found that every time I changed the formStyle between 'fsAlwaysOnTop' and 'fsNormal' all my registered hotkeys were inactivated.

Then I refer to the VCL Help, it says in the document:

TCustomForm.FormStyle
Note: It is not advisable to change FormStyle at runtime.


And then, I made a experiment to see why it's 'not advisable'. I guess that would be problems with Handle of form.

ShowMessage(IntToStr(Handle);
if Self.FormStyle <> fsStayOnTop then
Self.FormStyle := fsStayOnTop
else
Self.FormStyle := fsNormal;
ShowMessage(IntToStr(Handle);


Yes, when FormStyle property is changed, the Handle of the form will be re-allocated. As a result, all hotkey message(WM_HOTKEY) were not received by the form with new handle.

My solution for this bus is to deactivate all hotkeys before changing FormStyle and then re-activate them after the change.

But, I still wonder whether there are yet any other traps here.