[Win32API] Select Folder

is there struct and fucntion similiar to OPENFILENAME and GetOpenFileName just to select folder instead of a file? or how do I have to use OPENFILENAMe and GetOpenFileName to locate and select folder? which filter?

also is this totally correct or I should improve this code somehow?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
						OPENFILENAME ofn;
						char szFileName[MAX_PATH] = "";
						ZeroMemory(&ofn, sizeof(ofn));

						ofn.lStructSize = sizeof(ofn);
						ofn.hwndOwner = hWnd;
						ofn.lpstrFilter = "Targa File (*.tga)\0*.tga\0";
						ofn.lpstrFile = szFileName;
						ofn.nMaxFile = MAX_PATH;
						ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
						ofn.lpstrDefExt = "txt";

						if(GetOpenFileName(&ofn))
						{
							string buffer = ofn.lpstrFile;
							LoadAndDisplayTGA(buffer, hWnd);
						}
Last edited on
I think the function for selecting a folder is SHBrowseForFolder, but it's been forever since I've used it:

http://msdn.microsoft.com/en-us/library/bb762115%28VS.85%29.aspx

As for your code snippit, it assumes a TCHAR==char which may not be the case depending on your compiler settings. If you're using char strings, you should use the char version of WinAPI functions.

Recommended changes below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
OPENFILENAMEA ofn;  // <- OPENFILENAMEA, not OPENFILENAME
char szFileName[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));

ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFilter = "Targa File (*.tga)\0*.tga\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = "txt";

if(GetOpenFileNameA(&ofn)) // <- GetOpenFileNameA, not GetOpenFileName
{
    string buffer = ofn.lpstrFile;
    LoadAndDisplayTGA(buffer, hWnd);
}


All WinAPI structs/functions that accept strings come in 3 forms:

TCHAR / LPCTSTR / LPTSTR form (no suffix, ie: GetOpenFileName, MessageBox, etc)
char / LPCSTR / LPSTR form ('A' suffix: GetOpenFileNameA, MessageBoxA, etc)
wchar_t / LPCWSTR / LPWSTR form ('W' suffix: GetOpenFileNameW, MessageBoxW, etc)

Don't try to mix and match different char types with different forms. If using char strings, use the char form. Or if using TCHARs, use the TCHAR form, etc.
i'm using multibyte character set, and I've been using everything without A and chars/strings all the time without any problems in several apps O_o

btw thanjs for browseforfolder, going to try that
Last edited on
i'm using multibyte character set, and I've been using everything without A and chars/strings all the time without any problems in several apps


Well like I said it depends on your compiler settings.

TCHAR->normal
char->A
wchar_t->W

Sticking with that pattern will work everywhere, 100% of the time. Deviating and mix-and-matching will only work if your compiler settings are just so. (Or if you explicitly tweak the UNICODE macro)
Topic archived. No new replies allowed.