使用COM组件执行程序

·

如果将执行这段代码的程序叫做程序A,被执行的程序叫做程序B(这里是notepad.exe)。用这种方法执行程序B的好处是程序B的父进程不是程序A,如果直接用ShellExecute和CreateProcess执行,则A是B的父进程。

// clang-format off
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlobj.h> // For IShellDispatch
#include <stdio.h>  // For printf


#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "shell32.lib")
// clang-format on

int main() {
  HRESULT hr;
  IShellDispatch2 *pShellDispatch2 = NULL;
  BSTR bstrOperation = SysAllocString(L"open");
  BSTR bstrFile = SysAllocString(L"notepad.exe");
  VARIANT vtEmpty;
  VariantInit(&vtEmpty);

  // Initialize COM library
  hr = CoInitialize(NULL);
  if (FAILED(hr)) {
    printf("Failed to initialize COM library. Error code = 0x%lx\n", hr);
    return 1;
  }

  // Create an instance of Shell.Application
  hr = CoCreateInstance(&CLSID_Shell, NULL, CLSCTX_INPROC_SERVER,
                        &IID_IShellDispatch2, (void **)&pShellDispatch2);
  if (FAILED(hr)) {
    printf(
        "Failed to create instance of Shell.Application. Error code = 0x%lx\n",
        hr);
    CoUninitialize();
    return 1;
  }

  // Use ShellExecute method to open Notepad
  hr = pShellDispatch2->lpVtbl->ShellExecute(pShellDispatch2, bstrFile, vtEmpty,
                                             vtEmpty, vtEmpty, vtEmpty);
  if (FAILED(hr)) {
    printf("ShellExecute failed. Error code = 0x%lx\n", hr);
  } else {
    printf("Notepad launched successfully.\n");
  }

  // Clean up
  if (pShellDispatch2) {
    pShellDispatch2->lpVtbl->Release(pShellDispatch2);
  }
  VariantClear(&vtEmpty);
  SysFreeString(bstrFile);
  SysFreeString(bstrOperation);
  CoUninitialize();
  return 0;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注