Detailed usage of ShellExecute

ShellExecute is a Windows API function that is used to open external applications, open URL links, or execute system commands.

The function prototype for ShellExecute is as follows:

HINSTANCE ShellExecute(
  HWND    hwnd,
  LPCTSTR lpOperation,
  LPCTSTR lpFile,
  LPCTSTR lpParameters,
  LPCTSTR lpDirectory,
  INT     nShowCmd
);

Description of Parameters:

  1. hwnd: Specify the handle of the parent window. If no parent window is needed, NULL can be passed in.
  2. lpOperation: specifies the type of operation, such as “open”, “print”, “explore”, and so on. If no operation type is needed, you can pass in NULL.
  3. lpFile: Specify the name of the file to open, URL link, or system command.
  4. lpParameters: Specifies the parameters to be passed to the file being opened, such as command line parameters. If no parameters are needed, NULL can be passed.
  5. lpDirectory: Specifies the directory where the file to be opened is located. If no directory is specified, NULL can be passed.
  6. nShowCmd: Specifies the way the file is displayed when opened, such as maximized, minimized, etc. Common values include SW_SHOW, SW_HIDE, etc.

return value:

  1. If the function is successful, it will return an HINSTANCE handle greater than 32. If the function fails, the return value depends on the reason for the error.

Here is an example code using ShellExecute to open an external application:

#include <Windows.h>
#include <ShellAPI.h>

int main() {
    ShellExecute(NULL, _T("open"), _T("C:\\Windows\\notepad.exe"), NULL, NULL, SW_SHOW);
    return 0;
}

Sample code using ShellExecute to open a URL link:

#include <Windows.h>
#include <ShellAPI.h>

int main() {
    ShellExecute(NULL, _T("open"), _T("http://www.example.com"), NULL, NULL, SW_SHOW);
    return 0;
}

Example code using ShellExecute to execute system commands:

#include <Windows.h>
#include <ShellAPI.h>

int main() {
    ShellExecute(NULL, _T("open"), _T("cmd.exe"), _T("/c echo Hello World"), NULL, SW_SHOW);
    return 0;
}

It is important to note that the ShellExecute function is an asynchronous function, meaning that the function call will return immediately without waiting for the application to finish executing. If you need to wait for the application to finish executing before proceeding with other operations, you can use the ShellExecuteEx function.

bannerAds