c++ - ShellExecuteEx 工作不稳定

标签 c++ winapi access-violation c++builder-6

我正在尝试使用 ShellExecuteEx 安装 Windows 服务(使用 CBuilder 6 构建)

这是我的安装函数。

int WinServiceInstall(WideString ServicePath)
{
 int result = 0;
 LPCWSTR filename = L"MyService.exe";
 LPCWSTR params = L"/install /silent";
 LPCWSTR dir = ServicePath;

 WideString fullPath = ServicePath+"\\"+filename;
 if (!PathFileExistsW(fullPath.c_bstr())) return -1;

 SHELLEXECUTEINFOW *lpExecInfo = new SHELLEXECUTEINFOW();
 try
 {
     lpExecInfo->cbSize = sizeof(SHELLEXECUTEINFOW);
     lpExecInfo->hwnd = 0;
     lpExecInfo->lpVerb = NULL;
     lpExecInfo->lpFile = filename;
     lpExecInfo->lpDirectory = dir;
     lpExecInfo->lpParameters = params;
     lpExecInfo->nShow = SW_HIDE;
     lpExecInfo->hInstApp = NULL;
     BOOL bResult = ShellExecuteExW(lpExecInfo);
     WaitForSingleObject(lpExecInfo->hProcess,INFINITE);
     if (!bResult)
     {
       int ErrorCode = GetLastError();
       WideString message = GetLastErrorMessage(ErrorCode);
       message +="\n"+IntToStr(ErrorCode);
       MessageBoxW(0,message,L"GetLastError",0);
       PrintError(ErrorCode);
       result = -1;
     }
 }
 catch(Exception &e)
 {
   printf("Hata: %s",e.Message);
   result = -1;

   WideString message = e.Message;
   MessageBoxW(0,message,L"Exception",0);
 }
 delete lpExecInfo;
 return result;
}

但是 ShellExecuteEx 函数工作不稳定。

有时会抛出 EAccessViolation 异常。

如何调试问题?我的错误在哪里?

谢谢。

最佳答案

这里是 CreateProcess。

bool WinServiceInstall(WideString ServicePath)
{
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi = {};

    WideString lpCommandLine=L"\""+ServicePath+"\\MyService.exe"+"\" /install /silent";

    if(CreateProcessW(NULL,
        lpCommandLine,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi )
    )
    {
        WaitForSingleObject( pi.hProcess, INFINITE );
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
        return true;
    }
    else
    {
        wchar_t buf[256];
        long errorCode = GetLastError();
        FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errorCode,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
        MessageBoxW(0,buf,L"Error",0);
        return false;
    }
}

关于c++ - ShellExecuteEx 工作不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39747714/

相关文章:

c++ - 将文本从文件加载到二维数组中 (C++)

c++ - 访问冲突是什么意思?

匿名 c 类型的 c++ 别名

python - "WindowsError: exception: access violation..."- ctypes 问题

c++ - 以编程方式在 IE 中设置页面缩放和文本大小

c++ - 在哪里可以找到构建 DirectShow BaseClasses 的项目?

windows - ruby win32api & 结构 (VerQueryValue)

c++ - 如何获取 EFI 系统分区的卷名?

c++ - 为什么这个 C++ 程序的输出会在 cmd 中产生一个巨大的困惑?

c++ - C++ 中的内置类型 bool 或 C 中的 stdbool.h 类型将 TRUE 和 FALSE 定义为不是机器字的大小?