使用CFileDialog选择文件时出现画图问题

Painting Issue when selecting file using CFileDialog

本文关键字:问题 CFileDialog 选择 文件 使用      更新时间:2023-10-16

我在代码中遇到了使用CFileDialog的问题。

当我从ModalDialog调用CFileDialog时,选择一个文件。一旦当前视图退出并重新打开,我的整个ModalDialog背景将被擦除。

过程遵循:

    <
  1. 主对话框/gh>
  2. 打开ModalDialog
  3. 打开CFileDialog选择文件
  4. 退出ModalDialog
  5. 重新打开ModalDialog[背景被擦除]

注:此问题仅在我选择文件时发生。如果我点击取消在CFileDialog。没有问题。

PFB,我的CFileDialog使用的代码片段:

//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();
        fileName.ReleaseBuffer();   
}
//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;
    GetWindowRect(&rt);
    graph.DrawImage(m_pImage, (INT)0, (INT)0,  (INT)rt.Width() , (INT)rt.Height() );
    DefWindowProc(WM_PAINT, (WPARAM)dc.m_hDC, (LPARAM)0);
}

我已经找到问题背后的原因了。

当我们使用CFileDialog保存/选择文件时,默认的行为是改变正在运行进程的工作目录。

因此,背景图像无法在新位置找到,因此背景被擦除。

为了确保这种情况不会发生,我们需要在CFileDialog中使用OFN_NOCHANGEDIR标志,它保留了工作目录