0

I'm creating a Windows application in C++ (actually, C++ coding in Unreal Engine 4 being packaged for Windows) that allows the user to save a file to their desktop. I am using the OPENFILENAMEA structure to handle this (see here). I am wanting to set the default filename that appears in the dialog box, but nothing I have tried works.

Specifically, I'm wanting there to be a default value set here, such as "MySavedFile.txt":

Example Picture

Is it possible to set the default filename for the file to be saved as when using the OPENFILENAMEA structure? If so, can you provide an example? I've been unable to figure it out so far and an example would really help.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Spishbert
  • 1
  • 2
  • 1
    Note that `GetSaveFileName()` has been deprecated since Windows Vista. Use [`IFileSaveDialog`](https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifilesavedialog) instead, which has a [`SetFileName()`](https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfilename) method: “*Sets the file name that appears in the File name edit box when that dialog box is opened.*” – Remy Lebeau Dec 25 '20 at 07:18

1 Answers1

1

The initial filename is set through lpstrFile in OPENFILENAME, following is a minimal example.

#include <windows.h>
#include <stdio.h>

int main()
{
    OPENFILENAME ofn = { sizeof(OPENFILENAME) };

    char szFile[_MAX_PATH] = "name";
    const char szExt[] = "ext\0"; // extra '\0' for lpstrFilter

    ofn.hwndOwner = GetConsoleWindow();
    ofn.lpstrFile = szFile; // <--------------------- initial file name
    ofn.nMaxFile = sizeof(szFile) / sizeof(szFile[0]);
    ofn.lpstrFilter = ofn.lpstrDefExt = szExt;
    ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT;

    if (GetSaveFileName(&ofn))
    {
        printf("save-as  '%s'\n", ofn.lpstrFile);
        printf("filename '%s'\n", ofn.lpstrFile + ofn.nFileOffset);
    }
}
dxiv
  • 16,984
  • 2
  • 27
  • 49
  • What would this look like using OPENFILENAMEW? OPENFILENAMEA does not work with unicode characters, which I need to use, but I couldn't figure out how to get OPENFILENAMEW to have an initial file name in the bar. It seems like it has to be done differently than for OPENFILENAMEA. – Spishbert Dec 27 '20 at 03:51
  • @Spishbert The question was about OPENFILENAMEA specifically, which is why the answer assumed an `A` ANSI build. For the Unicode `W` version of it, just replace `char` with `wchar_t` (or the `WCHAR` typedef) and prefix string literals with `L` for "wide", for example `WCHAR wszFile[_MAX_PATH] = L"name";`. Or, to compile for either ANSI or Unicode depending on the `UNICODE`, `_UNICODE` macros use `TCHAR tszFile[_MAX_PATH] = TEXT("name");` as described in [Working with Strings](https://learn.microsoft.com/en-us/windows/win32/learnwin32/working-with-strings). – dxiv Dec 27 '20 at 04:17