代码运行显示 设置成功 ,但依旧无法开机自启动
// 进程开机自启动.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
void ComputerStart(char *pathName)
{
//找到系统的启动项
char *szSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
HKEY hKey;
//打开注册表启动项
int k = RegOpenKeyExA(HKEY_LOCAL_MACHINE, szSubKey, 0, KEY_ALL_ACCESS, &hKey);
if (k == ERROR_SUCCESS)
{
//添加一个子Key,并设置值,MyStart为启动项名称,自定义设置;
RegSetValueExA(hKey, "MyStart", 0, REG_SZ, (BYTE *)pathName, strlen(pathName));
//关闭注册表
RegCloseKey(hKey);
printf("设置成功\n");
}
else
{
printf("设置失败 error:%d\n", k);
}
}
int main()
{
char pathName[MAX_PATH];//文件名字最大260个字符 MAX_PATH 260
GetCurrentDirectoryA(MAX_PATH, pathName);//设置字符集为多字节字符集 获取当前文件路径
sprintf(pathName, "%s\\", pathName);
strcat(pathName, "C://ProgramData//BoleanGuard//zhenghe.exe");//找到需要开机自启动的程序
ComputerStart(pathName);
system("pause");
return 0;
}
strcat(pathName, "C://ProgramData//BoleanGuard//zhenghe.exe");
这一句有问题。strcat是连接字符串。pathName里已经是获取的路径+\了,后面再连接一个全路径,导致文件路径错误
修改成这样,strcat(pathName, "zhenghe.exe");
如果只是要在注册表条件程序自己,使用命令行参数argv[0]。
int main(int argc, char**argv)
{
if(strchr(argv[0],'\\')==NULL)
{
strcat(pathName, argv[0]);
ComputerStart(pathName);
}else
ComputerStart(argv[0]);
}
第一个命令行参数是启动程序的路径。