Reputation: 14356
I have a dialog-based MFC application which needs to stop Windows Wifi service in order to run correctly, but I want to enable it again when my application exits.
So I thought I'd put the code that restarts the service in the destructor of the main dialog class.
Now it has come to my attention that others put their code which should be run during program termination into a WM_CLOSE
message handler.
Both ways seem to work, but I would like to know if there are downsides to either way.
Upvotes: 5
Views: 894
Reputation: 6657
Aim to maintain symmetry: if you are stopping the wifi service in a constructor, then restart it in the same class's destructor. If instead you stop the service in InitInstance
, you would restart it in ExitInstance
; if as a response to WM_CREATE
or some other message, then restart it in WM_CLOSE
, etc.
Constructors and destructors have no way of returning an error status, so normally they are better suited for simple tasks such as initialization and memory allocation/deallocation.
InitInstance
and ExitInstance
, as well as windows messages such as WM_CLOSE
, happen at a good spot in the application's lifetime to display error messages if necessary, or to abort in response to error conditions.
Upvotes: 3
Reputation: 43311
For MFC dialog based application you can place finalization code to application class InitInstance
method, immediately after main dialog DoModal
call. For other MFC application types (MDI, SDI) finalization code is usually placed to ExitInstance
method.
The difference between dialog based application and SDI/MDI applications, is that InitInstance
in dialog based applications returns FALSE, and application exits - all action is done in the main dialog DoModal
call.
You can prefer to use ExitInstance
for all application types, it should work as well.
Edit. If you want to make cleanup code inside of the dialog class, WM_DESTROY
(already mentioned by Roger Rowland) is better place than WM_CLOSE
. Sometimes we can handle WM_CLOSE
message and prevent a dialog to be closed, for example, by asking "Exit the program? Yes - No". In the case you want to use some child windows, they exist in WM_CLOSE
and WM_DESTROY
message handlers, and don't exist in a dialog destructor. Also, message queue doesn't exist when main dialog destructor is called, so you should not use Windows messaging in this case.
Upvotes: 3