gpt4 book ai didi

c++ - ShellExecuteEx 工作不稳定

转载 作者:行者123 更新时间:2023-11-28 02:00:43 31 4
gpt4 key购买 nike

我正在尝试使用 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com