Usage and common examples of ShellExecuteEx

The ShellExecuteEx function is a function in the Windows API that can open an external program or file, and allows for specifying parameters to control how it is opened. Below are the usage and common examples of the ShellExecuteEx function.

How to use:

  1. You first need to include the windows.h header file.
  2. Declare a variable of type SHELLEXECUTEINFO structure, and initialize the cbSize member to the size of the structure.
  3. Set the other members of the SHELLEXECUTEINFO structure, including lpVerb, lpFile, lpParameters, lpDirectory, and nShow.
  4. Call the ShellExecuteEx function and pass the address of the SHELLEXECUTEINFO structure as a parameter to the function.
  5. Check the return value of the ShellExecuteEx function; if it is TRUE, then the execution was successful, but if it is FALSE, then the execution failed.

Common examples:

  1. Open an external program:
#include <windows.h>

int main()
{
    SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
    sei.lpFile = L"notepad.exe";
    sei.nShow = SW_SHOW;
    
    if (ShellExecuteEx(&sei))
    {
        // 执行成功
    }
    else
    {
        // 执行失败
    }
    
    return 0;
}

The above code will open the Notepad program.

  1. Open a file:
#include <windows.h>

int main()
{
    SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
    sei.lpFile = L"C:\\path\\to\\file.txt";
    sei.nShow = SW_SHOW;
    
    if (ShellExecuteEx(&sei))
    {
        // 执行成功
    }
    else
    {
        // 执行失败
    }
    
    return 0;
}

The above code will open the file located at the path C:\path\to\file.txt.

Please note that when using the ShellExecuteEx function to open a file, the lpFile parameter should be passed the full path of the file.

  1. Open a URL link:
#include <windows.h>

int main()
{
    SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
    sei.lpFile = L"https://www.example.com";
    sei.nShow = SW_SHOW;
    
    if (ShellExecuteEx(&sei))
    {
        // 执行成功
    }
    else
    {
        // 执行失败
    }
    
    return 0;
}

The above code will open a link to https://www.example.com.

Note: When using the ShellExecuteEx function to open a URL link, the lpFile parameter needs to be passed the full URL link address.

The above are the usage methods and common examples of the ShellExecuteEx function, I hope it helps you.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds