Dave's Brain

Browse - programming tips - win32 convert getopenfilename multiselect

Date: 2008jul10
Language: C++
Platform: win32

Q.  How can I convert the result of an GetOpenFileName() with OFN_ALLOWMULTISELECT into something useful?

A.  Here is a function that does just that.

#include <vector>
#include <algorithm>

typedef std:vector<std::string> STRING_ARRAY;

void ConvertMultiToArray(LPCSTR big, STRING_ARRAY &a)
{
	char	szDir[MAX_PATH+1] = "";
	char	szFile[MAX_PATH+1];
	LPCSTR	p;

#ifdef __BORLANDC__
	a.erase(a.begin(), a.end());
#else
	a.clear();
#endif

	for (p = big; *p; p += lstrlen(p) + 1)
	{
		if (szDir[0] == '\0')
		{
			lstrcpyn(szDir, p, sizeof(szDir));
		}
		else
		{
			_snprintf(szFile, sizeof(szFile), "%s\\%s", szDir, p);
			a.push_back(szFile);
		}
	}

	// If there is only one file its here
	if (a.size() == 0 && szDir[0] != '\0')
	{
		a.push_back(szDir);
	}

	// The file names come back in an unpredictable order (not reversed) so sorting is the best we can do - thanks Microsoft
	std::sort(a.begin(), a.end());
}

ExampleUse()
{
	OPENFILENAME		ofn;
	char			big[50000];

	ofn.lpstrFile = big;
	ofn.nMaxFile = sizeof(big);
	ofn.Flags = /* ... flags you want ... */ | OFN_ALLOWMULTISELECT;
	// ... Fill other stuff in ofn ...

	if (GetOpenFileName(&ofn))
	{
		STRING_ARRAY		a;

		ConvertMultiToArray(big, a);

		for (STRING_ARRAY::const_iterator it = a.begin(); it != a.end(); it++)
		{
			printf("file=%s\n", it->c_str());
		}
	}
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: