[英]How to set a C++ program to start automatically when windows starts up?(By windows service solution)
我想让我的C ++程序在Windows启动并在后台运行时自动启动。 我搜索了一下内容,发现可以使用将C ++程序注册为Windows服务,以便Windows启动时该程序可以自动运行。 因此,我将此代码复制到“ 将应用程序添加到启动(注册表)”中并运行该代码,但在计算机管理->服务中看不到任何记录。 这是代码:
#include "stdafx.h"
#include<Windows.h>
#include <Winbase.h>
BOOL RegisterMyProgramForStartup(PCWSTR pszAppName, PCWSTR pathToExe, PCWSTR args)
{
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwSize;
const size_t count = MAX_PATH * 2;
wchar_t szValue[count] = {};
wcscpy_s(szValue, count, L"\"");
wcscat_s(szValue, count, pathToExe);
wcscat_s(szValue, count, L"\" ");
if (args != NULL)
{
wcscat_s(szValue, count, args);
}
lResult = RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &hKey, NULL);
fSuccess = (lResult == 0);
if (fSuccess)
{
dwSize = (wcslen(szValue) + 1) * 2;
lResult = RegSetValueExW(hKey, pszAppName, 0, REG_SZ, (BYTE*)szValue, dwSize);
fSuccess = (lResult == 0);
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}
return fSuccess;
}
void RegisterProgram()
{
wchar_t szPathToExe[MAX_PATH];
GetModuleFileNameW(NULL, szPathToExe, MAX_PATH);
RegisterMyProgramForStartup(L"ConsoleApplication7", szPathToExe, L"-foobar");
}
int _tmain(int argc, _TCHAR* argv[])
{
RegisterProgram();
return 0;
}
正如评论中已经提到的那样,您不是在注册服务,而是创建一个自动运行条目。 您的应用程序必须实现各种条件才能成为服务。
有上code.msdn.microsoft.com一个示例项目在这里应该帮助你编写自己的服务启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.