Arun kumar Arun kumar - 1 year ago 64
C++ Question

Painting Issue when selecting file using CFileDialog

I am facing an issue using

in my code.

When I call the
from ModalDialog, to select a file.
My whole ModalDialog background gets erased once the current view is exited and reopened.

Procedure followed:

  1. Main Dialog

  2. Opened ModalDialog

  3. Opened
    for selecting file

  4. Exit ModalDialog

  5. Reopen ModalDialog [Background gets erased]

Note : This issue happens only if I select a file.
If I click on Cancel in the
. There is no issue.

PFB, the code snippet of my

//This is the code to Open the DoModal dialog from MainWindow
void CCommonDlg::OnBnClickedButton1()

COSDADlg dlg;
//m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)

else if (nResponse == IDCANCEL)
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel


// This is the code for open CFileDialog from ModalDialog to save file
void COSDADlg::OnBnClickedButton1()

CFileDialog dlgFile(FALSE);

CString fileName;
dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(FILE_LIST_BUFFER_SIZE);
dlgFile.GetOFN().nMaxFile = FILE_LIST_BUFFER_SIZE;

INT_PTR nResult = dlgFile.DoModal();


//This is the code to paint the background image for ModalDialog
void COSDADlg::OnPaint()
CPaintDC dc(this); // device context for painting

Graphics graph(dc.m_hDC);
CRect rt;
graph.DrawImage(m_pImage, (INT)0, (INT)0, (INT)rt.Width() , (INT)rt.Height() );
DefWindowProc(WM_PAINT, (WPARAM)dc.m_hDC, (LPARAM)0);


Answer Source

I have Found the reason behind the issue.

When we save/select the file using CFileDialog, the default behavior is to change the WorkingDirectory of the running process.

Due to this, the background image could not be found in the new location and Hence background getting erased.

In order to ensure that this does not happen, we need to use the OFN_NOCHANGEDIR flag in CFileDialog, which retains the working directory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download