[英]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.