如何设置C++程序在windows启动时自动启动?(由windows服务解决)
How to set a C++ program to start automatically when windows starts up?(By windows service solution)
我想让我的 C++ 程序在 windows 启动时自动启动,运行 在后台运行。我搜索了一下,发现我们可以使用将 C++ 程序注册为 windows 服务,这样当 windows 启动时,程序可以自动 运行。
所以我将这段代码复制到 Add Application to Startup (Registry) 中,并将代码复制到 运行 中,但是我在计算机管理->服务中看不到任何记录。
这是代码:
#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 here 上有一个示例项目可以帮助您开始编写自己的服务。
我想让我的 C++ 程序在 windows 启动时自动启动,运行 在后台运行。我搜索了一下,发现我们可以使用将 C++ 程序注册为 windows 服务,这样当 windows 启动时,程序可以自动 运行。 所以我将这段代码复制到 Add Application to Startup (Registry) 中,并将代码复制到 运行 中,但是我在计算机管理->服务中看不到任何记录。 这是代码:
#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 here 上有一个示例项目可以帮助您开始编写自己的服务。