c++dialoglpstrcomdlg32lpwstr

Dialog wIndow does not open


So i want to make a sort of texteditor and want to use a dialogwindow to get the filepath/file from the user. Now here is the problem. I get an error in one project that i does not get in another even though i have not changed a setting that would let me conclude that there might be an issue.

#include <Windows.h>
#include <fstream>
#include <Windows.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <commdlg.h>

using std::cout;



void getfile() {

    OPENFILENAME NameOfFile;
    ZeroMemory(&NameOfFile, sizeof(NameOfFile));
    NameOfFile.lStructSize = sizeof(NameOfFile);   
    LPWSTR szFile{};
    NameOfFile.lpstrFile = szFile;                 
    NameOfFile.nMaxFile = sizeof(szFile);          
    NameOfFile.Flags = OFN_ALLOWMULTISELECT;
    if (GetOpenFileName(&NameOfFile))
    {
        std::cout << szFile;
    }

}
int main() {

    getfile();

}

When i do this in one project the error "Severity Code Description Project File Line Suppression state Error (active) E0513 A value of type ""LPWSTR"" cannot be assigned to an entity of type ""LPSTR"""

Picture of the working project

Picture of the working project

Here the settings of the project its not working

Here the settings of the project its not working

That is kinda understandable and i tried multiple workarounds with LPTSTR or triying .c_str() to convert but it wont work. And as i said the literally completly same code compiles and runs fine in another project


Solution

  • LPWSTR FILE{};
    OPENFILENAME NameOfFile;
    ZeroMemory(&NameOfFile, sizeof(NameOfFile));
    NameOfFile.lStructSize = sizeof(NameOfFile);
    TCHAR szFile[MAX_PATH];
    NameOfFile.lpstrFile = szFile;
    NameOfFile.nMaxFile = sizeof(szFile);
    NameOfFile.Flags = OFN_ALLOWMULTISELECT;
    if (GetOpenFileName(&NameOfFile))
    {
        FILE = (LPWSTR)szFile;
    }
    

    This code will open a dialog window with the purpose to "open" a file. It will save the name of the file and the path int the variable FILE.

    The answer to my problem was the variable szFile that can't be an LPWSTR but needed to be for the dialog window to work. In the end the process does this (I skipped some steps):

    1. I make a "buffer" variable szfile (array with 260 characters bc MAX_PATH resolves to that)

    2. It makes a sort of reference (similar to a pointer) that points to the array [that is the "NameOfFile.lpstrFile"]

    3. Its calls the function in the if statement and opens the dialog window

    4. After choosing the function "GetOpenFileName" saves the file name and the path in szFile (the TCHAR - array) and converts that one back to LPWSTR [the code writen in the if statement]

    5. You got your stuff and can continue

    thanks for everyone's help