6
votes

After applying a new style at runtime the MainForm of my application creates a new window handle – is there any way to stop this or reassign the Handle as I a getting a tonne of the following error:

'System Error. Code: 1400. Invalid window handle'

Is there any way to manipulate the process that forces the new handle to be assigned?

I solved this doing the following:

My main form created an unseen 'helper' form that is never displayed, but that does have visual components - it was throwing the handle error when it was trying to redraw these visual components, so I replaced the relevant components with objects instead (note I did not write this code originally).

1
Do not store copies of the window handle (especially in threads), see PostMessage returns “invalid window handle” in thread.LU RD
Yes there are ways to avoid that. If you would tell us why it happens then we could help. So, why do you have a stale window handle?David Heffernan
FWIW, changing style in Delphi 10.4 also changes the handle of the main form. I am using EnumWindows afresh if I need to determine form handles, no longer storing them.Mike Scott

1 Answers

6
votes

There is no way to avoid re-creating the window handles. Instead, override your window's CreateWnd and DestroyWnd methods so that you're notified when a window is re-created.

Also, avoid keeping persistent references to handles of windows that might get destroyed. Instead, read the Handle property each time you need it. Then you won't have to watch for notifications.

Beware of reading Handle from a different thread, though, since it may cause the window to become associated with the wrong thread. Wrap any code that needs to interact with a VCL window into a method that you call via Synchronize or Queue.