OpenFileDialog class not working properly in c++

553 Views Asked by At

I want to show the file name that is opened by OpenFileDialog but it sends the wrong text into title bar. I hace changed the character set of the project but it did not help. here is my code :

OpenFileDialog .h :

    class OpenFileDialog  
    {
    public:
        OpenFileDialog(){};
        void CreateOpenFileDialog(HWND hWnd, LPCWSTR Title, LPCWSTR InitialDirectory, LPCWSTR Filter, int FilterIndex);
        ~OpenFileDialog(){};
        LPCWSTR result=L"";
    };

OpenFileDialog .cpp :

      void OpenFileDialog::CreateOpenFileDialog(HWND hWnd, LPCWSTR Title, LPCWSTR InitialDirectory, LPCWSTR Filter, int FilterIndex)
       {
    OPENFILENAME ofn;
    TCHAR szFile[MAX_PATH];
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.lpstrFile = szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.hwndOwner = hWnd;
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = Filter;
    ofn.nFilterIndex = FilterIndex;
    ofn.lpstrTitle = Title;
    ofn.lpstrInitialDir = InitialDirectory;
    ofn.lpstrFileTitle = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;


    if (GetOpenFileName(&ofn))
    {
         result = ofn.lpstrFile;
    }
    else
    {
        result = L"Empty";
    }
}

and in windows procedure in WM_COMMAND :

        case WM_COMMAND:
        {
            if (LOWORD(wParam) == ID_FILE_OPEN)
            {
                OpenFileDialog ofd;
                ofd.CreateOpenFileDialog(hwnd, L"Test", L"C:\\", L"All files(*.*)\0*.*\0TextFiles(*.txt)\0*.txt\0", 2);
                SetWindowText(hwnd, ofd.result);
            }
            break;
        }

thanks alot.

1

There are 1 best solutions below

0
On BEST ANSWER

In your function CreateOpenFileDialog(), the buffer for storing the file name is a local array szFile[MAX_PATH]. You initialize the lpstrFile = szFile in the ofn structure, making sure that the GetOpenFileName() puts the result of user entry at the right place.

The problem is that as soon as you return from CreateOpenFileDialog(), its local variables are destroyed, including the buffer containing the file name. Hence, the resultpointer that you've set with result = ofn.lpstrFile; then points to an invalid memory location.

You can solve this by allocating the buffer directly in result in the OpenFileDialog constructor (or making it an array), and using this pointer directly with ofn.lpstrFile = buffer;