Search code examples
delphimessage-queuetform

Dynamic Delphi form creation - ensuring correct mouse message handling


I have an Application layout that is based on a treeView at the left, and a panel on the right. The panel hosts a differnt TForm class depending on the tree node selected (a kind of 'form explorer'). There is only one form displayed at a time which exposes underlying data stored elsewhere and the form instance is created and destroyed on each new tree node click.

This all works fine except for the following scenario. Click a button on the form which launches an action that takes a second or so. During this action there may be a call to Application.ProcessMessages. Now just before this action has actually completed, the User clicks a new tree node. This wmMousedown message is processed causing the form to be freed immeditely. The action code then returns to the form code to find that self has changed and causes an AV.

My question is, is there a way to know that the form's messages have all been processed and completed before I allow the form to be freed? Modal forms seem to do this when the close button is clicked because they pause before closing if busy...

Thanks Brian


Solution

  • To answer the actual question in the final paragraph... :)

    If you call Release on a form this posts a message to the form which will result in it Free'ing itself when it receives that message.

    Since the message is posted to the message queue, it will arrive only after any/all other current messages for that form have been processed, neatly achieving exactly what you ask for I think.