Last active
April 14, 2018 21:55
-
-
Save AlexTMjugador/933ed1bc8767073d45d8657a72444bd5 to your computer and use it in GitHub Desktop.
Retrieves the number of files that the user has selected in a window opened by the GetOpenFileName Win32 C API function. It assumes that the OFN_EXPLORER and OFN_ALLOWMULTISELECT flags are set.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
size_t FilesSelected(OPENFILENAME ofn, size_t bufferSize) | |
{ | |
// ofn.lpstrFile format: | |
// - If the user picks one file: folder\file\0\0 | |
// - If the user picks several files: folder\0file1\0file2\0fileN\0\0 | |
// This function assumes that input parameters are valid and is used just after GetOpenFileName returns with success. | |
size_t toret = 0; | |
BOOL bBufferEnd = FALSE; | |
BOOL bFoundNullPreviously = FALSE; | |
for (size_t i = 0; i < bufferSize - 2 && !bBufferEnd; i += 2) | |
{ | |
TCHAR cur = ofn.lpstrFile[i]; | |
TCHAR next = ofn.lpstrFile[i + 1]; | |
TCHAR nextNext = ofn.lpstrFile[i + 2]; | |
BOOL bFoundNull = cur == '\0' || next == '\0'; | |
bBufferEnd = cur == '\0' && next == '\0' || next == '\0' && nextNext == '\0'; | |
if (bFoundNull && (!bBufferEnd || !bFoundNullPreviously)) | |
{ | |
// We found another file if we find a null character, and one of the following conditions applies: | |
// 1. The buffer doesn't end (i.e., a null character is followed by another null character). | |
// E.g., a buffer with two files would have two \0, including the one which separates the folder from the first file. | |
// We don't want to count the last null on the buffer, followed by another null, because it signals the buffer end. | |
// 2. It's the first null character we find. This would count a first null no matter where it is. | |
// It allows to handle the case where the user only selects one file correctly. | |
++toret; | |
} | |
bFoundNullPreviously = bFoundNullPreviously || bFoundNull; | |
} | |
return toret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment