user12413058
user12413058

Reputation:

OPENFILENAME: Setting lpstrTitle via converted string doesn't work; outputs lots of 'Ì's and other special characters

I'm currently creating a class for a more comfortable use of GetOpenFileName. And now, I've encountered a problem:

I've included a string to set as the window title as a constructor argument. But when using it, the window just outputs lots of special characters.

This is my code:

OpenFileDialog(HWND hwndOwner = NULL, std::string WindowTitle = "", std::string FilterDescription = "Text Files", std::string FilterExtension = "txt", bool ShowAnyFilesOption = true) {
    ZeroMemory(&filename, sizeof(filename));
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwndOwner;
    setFilter(FilterDescription, FilterExtension, ShowAnyFilesOption);
    ofn.lpstrFile = filename;
    ofn.nMaxFile = MAX_PATH;
    ofn.lpstrTitle = WindowTitle.c_str();
    ofn.Flags = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST;
}


bool setFilter(std::string FormatDescription, std::string FileExtension, bool ShowAnyFilesOption = true) {
    if (FileExtension != "") {
#define NULLstr sFilter.push_back('\0')

        sFilter = FormatDescription + " (*." + FileExtension + ")";
        NULLstr;
        sFilter.append("*." + FileExtension);
        NULLstr;

        if (ShowAnyFilesOption) {
            sFilter.append("Any Files (*.*)");
            NULLstr;
            sFilter.append("*.*");
            NULLstr;
        }
        ofn.lpstrFilter = sFilter.c_str();
        return true;
#undef NULLstr
    }

    else // File extension empty
                return false;
}

I would be very happy if you could help me solve this problem. I'm not very good at using the WinAPI, to be honest 😅

Upvotes: 1

Views: 143

Answers (1)

YellowAfterlife
YellowAfterlife

Reputation: 3202

Since GetOpenFileName call isn't happening inside OpenFileDialog constructor, you want to copy your string into a more persistent location (such as a class field inside OpenFileDialog)- an std::string that you passed as an argument may get freed up later and used for something else, thus causing your c_str to point at unrelated/garbage data.

Upvotes: 2

Related Questions