Opening and selecting a file in windows explorer

We can use ShellExecute API function to open a file or folder in windows Explorer

ShellExecute function is like

HINSTANCE ShellExecute(
    HWND  hwnd,             // handle to parent window
    LPCTSTR  lpOperation,  // pointer to string that specifies operation to perform
    LPCTSTR  lpFile,       // pointer to filename string
    LPTSTR  lpParameters,  // pointer to string that specifies the arguments
    LPCTSTR  lpDirectory,  // pointer to string that specifies default directory
    INT  nShowCmd          // whether the file is shown when opened(Window style)
   );

Hwnd – could be NULL
lpOperation
  •   open” -  opens the file/folder specified in lpFile
  •   explore” - browse a folder specified in lpFile

lpFile – path of a file or folder to open
lpParameters – Arguments for the executable specified in lpFile
lpDirectory – Set the directory (can be NULL)
nCmdShow – Window Style. Use any of the following

nCmdShow
Value
Description
SW_HIDE
0
Hides the window
SW_MAXIMIZE
3
Maximizes the specified window
SW_MINIMIZE
6
Minimizes the specified window and activates the next top-level window in the Z order.
SW_RESTORE
9
Activates restore window to its original size and position.
SW_SHOW
5
Activates the window and displays it in its current size and position
SW_SHOWDEFAULT
10
Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window
SW_SHOWMINIMIZED    
2
Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE
7
Similar to SW_SHOWMINIMIZED, except the window is not activated.
SW_SHOWNA
8
Similar to SW_SHOW, except that the window is not activated.
SW_SHOWNOACTIVATE
4
Displays a window in its most recent size and position. The window is not activated.
SW_SHOWNORMAL
1
Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

For selecting an item in explorer we need to pass “/select” commandline switch along with the argument
The syntax is like

/select,<file path>
If the path contains spaces the path should be placed between double quotes like below

/select,"<file path>"
An example code is given below

ShellExecute(NULL,"open","explorer","/select,\"c:\\example.jpg\"","",1);


Comments