- 1 year ago
Default Filename in Save File Dialog with OPENFILENAMEA Class in C++
To set a default filename in the Save File dialog using the OPENFILENAMEA
class in C++, you can initialize the lpstrFile
member of the OPENFILENAMEA
structure with the desired default filename. Here's an example:
cpp#include <windows.h>
int main() {
OPENFILENAMEA ofn;
char szFile[MAX_PATH] = ""; // Buffer to hold the selected file path
// Initialize the OPENFILENAMEA structure
ZeroMemory(&ofn, sizeof(OPENFILENAMEA));
ofn.lStructSize = sizeof(OPENFILENAMEA);
ofn.hwndOwner = NULL; // Handle of the owner window
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
ofn.nFilterIndex = 1;
ofn.lpstrDefExt = "txt";
ofn.lpstrInitialDir = NULL; // Initial directory for the dialog
// Set the default filename
ofn.lpstrFile = "default.txt";
// Display the Save File dialog
if (GetSaveFileNameA(&ofn)) {
// Save the selected file path
// ...
}
return 0;
}
In this example, we're using the GetSaveFileNameA
function to display the Save File dialog. Before calling this function, we initialize the OPENFILENAMEA
structure and set the necessary members.
To set the default filename, we assign the desired filename (e.g., "default.txt") to the lpstrFile
member of the OPENFILENAMEA
structure. Note that this member is initially set to szFile
, which is a buffer to hold the selected file path. We override it with the default filename before displaying the dialog.
After the user selects a file or cancels the dialog, you can access the selected file path from the szFile
buffer.
Adjust the other members of the OPENFILENAMEA
structure as per your requirements, such as the owner window handle, file filters, initial directory, and default file extension.
Remember to link against the comdlg32.lib
library when building your project to resolve the GetSaveFileNameA
function.