这个目前有点问题,程序自身的开机启动设置不成功,不知道为啥,不确定在别的电脑上会不会这样,也不知道是不是因为杀毒软件从中作祟还是如何。
开机启动设置函数:http://huidong.xyz/?mode=2&id=74
string数组动态添加行函数:http://huidong.xyz/index.php?mode=2&id=204
原理:将自身设置为开机自启,然后根据目录下的文件中存储的要开机自启的程序列表打开所有要自启的程序。
使用方法
第一次运行程序时,确保目录下有bootfiles.dat
在bootfiles.dat中添加要开机自启的程序目录,比如:
D:\Program Files (x86)\Dual Monitor\DualMonitor.exe
如果有多个,那么每行写一个目录。
第一次启动时以管理员模式启动程序即可,程序没有界面,可能可以看到一个cmd窗口一闪而过。
然后重启电脑,看看写进bootfiles.dat里的目录对应的程序是否开机自启了。
huidong 2020.12.19
源码:
#include <Windows.h>
#include <winuser.h>
#include <stdio.h>
#include <wchar.h>
#include <tchar.h>
#include <conio.h>
#include <string>
using namespace std;
// programName 要设置开机自启的程序路径
// 返回值:表示是否设置成功
bool HKRunator(const TCHAR* programName)
{
HKEY hkey = NULL;
DWORD rc;
rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, //创建一个注册表项,如果有则打开该注册表项
_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&hkey,
NULL);
if (rc == ERROR_SUCCESS)
{
rc = RegSetValueEx(hkey,
_T("BootSet"),
0,
REG_SZ,
(const BYTE*)programName,
lstrlen(programName));
if (rc == ERROR_SUCCESS)
{
RegCloseKey(hkey);
}
}
else
{
return false;
}
return true;
}
// 为string数组新增一行的空间
// 新的string数组直接存回原string数组,并返回新的数组指针
//
// p_strSrc 原数组
// p_nOld 原数组行数
string* AddStringRow(string*& p_strSrc, int p_nOld)
{
string* temp;
int num = p_nOld;
// 备份原字符串
temp = new string[num + 1];
for (int i = 0; i < num; i++)
temp[i] = p_strSrc[i];
// 删除原字符串
if (num)
delete[] p_strSrc;
p_strSrc = temp;
return temp;
}
// 读取要开机自启的程序目录
void ReadBootFile(string*& p_strFiles, int* pNum)
{
FILE* fp;
int nFileNum = 0;
string* strFiles = NULL;
fopen_s(&fp, "./bootfiles.dat", "rt+");
while (true)
{
char strPath[1024] = { 0 };
fgets(strPath, 1024, fp);
// 读取已完毕
if (!strlen(strPath))
break;
// 放入string数组
AddStringRow(strFiles, nFileNum);
nFileNum++;
strFiles[nFileNum - 1] = strPath;
}
*pNum = nFileNum;
p_strFiles = strFiles;
fclose(fp);
}
// 加入新的目录到开机自启名单(暂时未用上)
void WriteBootFile(string p_strPath)
{
FILE* fp;
fopen_s(&fp, "./bootfiles.dat", "wt+");
p_strPath += "\n";
fputs(p_strPath.c_str(), fp);
fclose(fp);
}
int main()
{
// 设置程序自身自启动
wchar_t strProgramFile[1024];
GetModuleFileName(NULL, strProgramFile, 1024); //调用win api 获得程序全路径
HKRunator(strProgramFile);
// 得到开机自启目录列表
string* strFiles;
int nFilesNum = 0;
ReadBootFile(strFiles, &nFilesNum);
// 依次启动它们
for (int i = 0; i < nFilesNum; i++)
{
WinExec(strFiles[i].c_str(), SW_SHOW);
}
return 0;
}
程序下载链接: https://pan.baidu.com/s/1eCexn2tKHi-4oCpdEySSFg 提取码: dmcr
很小,就8kb,用百度网盘没问题。