Home > other >  How to Run File Explorer From C Program and Show Only Certain Files on Windows?
How to Run File Explorer From C Program and Show Only Certain Files on Windows?

Time:07-20

I'm sorry if this question sounds a bit vague. I am making a windows 11 application in C , and I am making an editor where I want there to be an option to upload a file of a certain type. Let's say there is a button to upload a file type; I want the file explorer to open with only the files of the chosen type to be showing.

Is it possible to do this directly from my C program, or will I have to make own process for using the file explorer in this way?

CodePudding user response:

The classic open dialog allows you to filter by file extension(s):

WCHAR buffer[MAX_PATH];
OPENFILENAME ofn = {};
ofn.lStructSize = sizeof(ofn);
//ofn.hwndOwner = ...;
ofn.lpstrFilter = TEXT("Only text and log files\0*.TXT;*.LOG\0");
ofn.lpstrFile = buffer, ofn.nMaxFile = MAX_PATH, *buffer = '\0';
ofn.Flags = OFN_EXPLORER|OFN_ENABLESIZING|OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn)) DoSomethingWithFile(ofn.lpstrFile);

Note: An advanced user can type * in the file name field to bypass this filter. You would think OFN_ENABLEINCLUDENOTIFY would give you more control but it does not let you filter filesystem items. MSDN is going to recommend that you use the newer Vista IFileDialog but MSDN also says about IFileDialog::SetFilter:

Deprecated. SetFilter is no longer available for use as of Windows 7

(In my testing it does seem to work however (tested Windows 8 and 10)).

IFileDialog supports the same basic extension filter as GetOpenFileName but unless you need to support non-filesystem items and intend to implement everything in terms of IStream, it is just extra work.

  • Related