As a workaround you can create a new application called MyAppCloser which will send a custom message to your server for example WM_USER+15
You have to include a window message listener to the server and once the message is received you have to shutdown everything from your app (disconnect from DB, etc) and when you are ready you send back a message to the MyAppCloser like WM_USER+16. Then you terminate server.
When MyAppCloser receives WM_USER+16 it just sleeps 1-2 seconds (give some time to exe to terminate) and then terminate (exit).
To make sure your app will close in all cases (including server hang/freeze) you can add a timer that will timeout in X seconds (number of seconds is totally up to your app shutdown process). If no WM_USER+16 is received within X seconds you will force kill the executable using ShellExecute the command
taskkill /F /IM ParamStr(1) /T
Then add a pre-built event as @NelsonFS adviced
If you further have many UniGui apps at the same time a fixed WM_USER + 15 will mess up things. You can configure the WM_USER + X numbers in command line
MyAppCloser.exe $(OUTPUTFILENAME) 15 16
so it will check for executable file as well as the WM_USER + X to send and WM_USER + X to receive make it unique for a specific unigui app.