Tom Davies
Tom Davies

Reputation: 2446

Prompt user to save changes when closing MFC view

I have an MFC MDI application, in which it is possible for documents to have multiple views, and for users to customise and then save layout data for the views. This data is associated with the views, not the documents.

I would like to prompt the users to save if they choose to close a view with unsaved layout changes, and am running into problems, as it seems MFC is only geared towards changes in the document. Here are some approaches I've tried:

  1. Override CDocument::SaveModified function, which gets called by the framework when a document is closed. In this function, I send a message to all the document's views, which can then check for unsaved changes and prompt the user.

  2. Perform the check inside the View's destructor.

  3. Perform the check inside the View's OnClose handler

Each of these approaches has problems. (1) is the best, but it fails to deal with cases where there are several views onto one document, and the user closes one of the views. As the document is still open, SaveModified is not called.

The problem with (2) is that on application shutdown, the application has already disappeard by the time any CView destrutors are called. This can leave an orphan dialog box open on the desktop. This is also the case if I try performing the check inside OnDestroy.

I can't get (3) to work - I can't get my views to respond to WM_CLOSE.

Currently, my best solution is to do both (1) and (2), but this requires some smelly logic to prevent the app from prompting the user to save view changes twice on app shutdown.

Anyone know of a better way of doing this? Where is the correct place to hook in?

Upvotes: 1

Views: 1314

Answers (2)

TonyP
TonyP

Reputation: 71

Concur.

ON_WM_DESTROY()
afx_msg void OnDestroy();

does the trick. It will not prevent the window from closing, but the question didn't request it.

Upvotes: 0

lakeweb
lakeweb

Reputation: 1939

I'm not sure if it is your solution, but I have several views that can not close on condition and I handle them in DestroyWindow( ). And a message box there does come up over the app before it closes down. So try using DestroyWindow( ) rather than the destructor.

Upvotes: 1

Related Questions