简体   繁体   中英

How to set a C++ program to start automatically when windows starts up?(By windows service solution)

I want to make my C++ program to start up automatically when the windows start up and run at the background. I searched something about it and find we can use register the C++ program to be a windows service so that when the windows start up, the program can automatically run. So I copy this code in Add Application to Startup (Registry) , and run the code, but I cannot see any records in my computer management->services. Here is the code:

#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;
}

As already mentioned in the comments you are not registering a service but create an auto run entry. Your application has to implement various things to qualify as service.

There is a sample project on code.msdn.microsoft.com here that should help you get started on writing your own service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM