如何从服务启动外部程序

How to start an external program from service

本文关键字:外部 程序 启动 服务      更新时间:2023-10-16

我正在尝试从服务程序调用二进制文件。二进制文件的路径是从注册表项中提取的。当我将缓冲区分配给字符串时,路径仅包含"C"。我在哪里犯了错误。我正在使用Visual Studio 2010这是代码:

std::string path;
getPathFromKey(path);
path = path+"\myapp.exe";
argument = "start "" ""+path+""";
system(argument.c_str());

/* 检索密钥 */

void getPathFromKey(std::string &path)
{
HKEY hKey = 0;
char buf[512];
DWORD dwType = 0;
DWORD dwBufSize = sizeof(buf);

if( RegOpenKey(HKEY_LOCAL_MACHINE,L"SOFTWARE\MYAPP\MyApp",&hKey) == ERROR_SUCCESS)
{
    dwType = REG_SZ;
    if( RegQueryValueEx(hKey,L"InstallPath",0, &dwType, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS)
    {
        for(int i=0;buf[i];i++)
            path[i]=buf[i];
        return;
    }
    else
    {
        RegCloseKey(hKey);
        return;
    }
}
else if( RegOpenKey(HKEY_LOCAL_MACHINE,L"Software\Wow6432Node\MYAPP\MyApp",&hKey) == ERROR_SUCCESS)
{
    dwType = REG_SZ;
    if( RegQueryValueEx(hKey,L"InstallPath",0, &dwType, (BYTE*)buf, &dwBufSize) == ERROR_SUCCESS)
    {
        for(int i=0;buf[i];i++)
            path[i]=buf[i];
        return;
    }
    else
    {
        RegCloseKey(hKey);
        return;
    }
}
}

我收到以下错误: Windows cannot find "C"

如果你得到字母C,这意味着你的代码部分工作。但是,这:

for(int i=0;buf[i];i++)
    path[i]=buf[i];
没有意义,

至少对我来说没有意义,因为我什至无法想象这个循环将如何工作(鉴于你得到字母 C 可能意味着它运行一次)。一个简单的解决方案是使用它:

path = std::string(buf);

如果我错了,请在调试时在返回之前检查 buf 值。