Skip to content

Instantly share code, notes, and snippets.

@Jimbly
Created June 20, 2022 23:22
Show Gist options
  • Save Jimbly/c859e8505a1961a3b43efd1d8a3b2e3a to your computer and use it in GitHub Desktop.
Save Jimbly/c859e8505a1961a3b43efd1d8a3b2e3a to your computer and use it in GitHub Desktop.
libGLOV exploreTo implementation example
// Path to directory, or file, but not to a "." (e.g. c:/foo/.)
void exploreTo(const char *localfname) {
wchar_t *path = utf8ToWideAlloc(localfname);
for (wchar_t *s = path; *s; ++s)
if (*s == '/')
*s = '\\';
// Remove trailing backslash, FindFirst will fail
if (path[wcslen(path) - 1] == '\\') {
path[wcslen(path) - 1] = '\0';
}
WIN32_FIND_DATAW find_data = {};
HANDLE find_result = FindFirstFileW(path, &find_data);
if (find_result == INVALID_HANDLE_VALUE) {
printf("Failed to explore to file \"%s\": Does not exist\n", localfname);
return;
}
bool is_dir = !!(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
FindClose(find_result);
CoInitializeEx(0, COINIT_MULTITHREADED);
PIDLIST_ABSOLUTE pidl = ILCreateFromPathW(path);
if (pidl) {
int cidl = 0;
LPCITEMIDLIST *apidl = NULL;
if (is_dir) {
// Select 1 NULL element, because if cidl == 0, then it opens the parent and selects the folder
static LPCITEMIDLIST null_carr[1] = { NULL };
cidl = 1;
apidl = &null_carr[0];
}
HRESULT hr = SHOpenFolderAndSelectItems(pidl, cidl, apidl, 0);
if (hr != S_OK) {
printf("Failed to explore to file %s\n", localfname);
// // From Chromium: On some systems, the above call mysteriously fails with "file not
// // found" even though the file is there. In these cases, ShellExecute()
// // seems to work as a fallback (although it won't select the file).
// if (hr == ERROR_FILE_NOT_FOUND) {
// ShellExecuteW(NULL, "open", dirname, NULL, NULL, SW_SHOW);
// }
}
ILFree(pidl);
}
free(path);
}
@Jimbly
Copy link
Author

Jimbly commented Jun 20, 2022

Taken from utilSystem.cpp in libGlov - MIT Licensed, available at: svn://www.dashingstrike.com/src/GLOV/libUtil/utilSystem.cpp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment