I dont have my Petzold book handy and I am having difficulty with asking the user to save the file when File|Exit is selected and the file has changes that are unsaved.
When I select the save dialog directly from the menu it works flawlessly, but I can't get it to ask the user to save the file, when a user selects 'exit' from the menu or the 'close' button.
Dialog box asks: "Save current changes?"
1. When I press: 'no' it closes the application as it should.
2. When I press: 'cancel' the dialog box is dismissed and the application continues as it should!
3. The trouble begins when I press: 'yes' the dialog box is destroyed and the application contiues running without exiting or running the IDM_FILE_SAVE.
What have I done incorrectly?
I am guessing my error is somewhere in the following code:
Code:
case IDM_FILE_EXIT:
SendMessage (hwnd, WM_CLOSE, 0, 0);
return 0 ;
case WM_DESTROY: // This case actually terminates the process.
PostQuitMessage (0);
return 0;
case WM_CLOSE :
if ( !bFileNeedsSaved || IDCANCEL != AskAboutSave())
DestroyWindow(hwnd);
return 0;
case WM_QUERYENDSESSION :
if ( !bFileNeedsSaved || IDCANCEL != AskAboutSave())
return 1;
return 0;
int AskAboutSave ()
{
int iReturn ;
iReturn = MessageBox (hwnd, "Save current changes?", szAppName,
MB_YESNOCANCEL | MB_ICONQUESTION) ;
if (iReturn == IDYES)
if (!SendMessage (hwnd, WM_COMMAND, IDM_FILE_SAVE, 0))
iReturn = IDCANCEL ;
// SendMessage(hwnd, WM_COMMAND, IDM_FILE_SAVE, 0);
return iReturn ;
}
case IDM_FILE_SAVE:
strcat(PathAndFilename, pDefaultSaveLocation);
if(GetSaveFileName(&ofn))
{
pPathAndFilename = ofn.lpstrFile;
if((fp = fopen (pPathAndFilename, "w"))==NULL) //a+ append/create and or overwrite.
{
MessageBox (hwnd, TEXT ("Cannot save file!"),
szAppName, MB_ICONEXCLAMATION | MB_OK);
exit(1);
}
// Write the file!
WriteData ();
fclose(fp);
bFileNeedsSaved = false;
//strip everything but filename from pPathAndFilename and store it into szFileName. See
char Temp[MAX_PATH];
char* pTemp = &Temp[0];
pTemp = strrchr(pPathAndFilename, '\\');
pTemp++;
char * szFileName = pTemp;
}
MessageBeep (0) ;
return 0 ;