添加启动目录
由于启动目录不固定,需要先通过SHGetSpecialFolderPath获取启动路径,再CopyFile把要自启动的程序复制过去
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <iostream> #include <Windows.h> #include <shlobj_core.h>
int main() { wchar_t StartupFolder[MAX_PATH] = {0}; wchar_t Path[MAX_PATH] = { 0 };
BOOL bRet= SHGetSpecialFolderPath(NULL, StartupFolder, CSIDL_STARTUP, FALSE); if (!bRet) { return -1; }
GetModuleFileName(NULL, (LPWSTR)&Path, MAX_PATH); wcscat_s(StartupFolder, L"\\Persistance.exe"); MessageBox(NULL, StartupFolder, L"StartupFolder", MB_OK); if (CopyFile(Path, StartupFolder, FALSE)) { MessageBox(NULL, L"succeed", L"succeed", MB_OK); } return 0; }
|
修改注册表
无需管理员权限即可修改HKEY_CURRENT_USER
在HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run中写入程序路径即可实现开机自启动
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| BOOL Regpersist() { HKEY hKey; LPCTSTR szRun = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"); if (RegOpenKeyEx(HKEY_CURRENT_USER, szRun, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) { TCHAR szFileName[MAX_PATH] = { 0 }; DWORD dwRet = GetModuleFileName(NULL, szFileName, MAX_PATH); AfxMessageBox(szFileName); long lRet = RegSetValueEx(hKey, _T("Login"), 0, REG_SZ, (BYTE*)szFileName, dwRet); RegCloseKey(hKey); if (lRet != ERROR_SUCCESS) return FALSE; } else { MessageBox(_T("打开注册表失败")); return FALSE; } MessageBox(_T("添加成功")); return TRUE; }
|
相关API函数
SHGetSpecialFolderPath
该api用来获取指定的系统路径
1 2 3 4 5 6
| BOOL SHGetSpecialFolderPathA( HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate );
|
RegOpenKey
打开注册表,成功返回ERROR_SUCCESS
1 2 3 4 5
| LSTATUS RegOpenKeyA( HKEY hKey, LPCSTR lpSubKey, PHKEY phkResult );
|
RegCloseKey
关闭注册表,成功返回ERROR_SUCCESS
1 2 3
| LSTATUS RegCloseKey( HKEY hKey );
|
RegQueryValueEx
注册表键值的查询
成功返回 ERROR_SUCCESS.
1 2 3 4 5 6 7 8
| LSTATUS RegQueryValueExA( HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData );
|
RegSetValueEx
注册表键值的写入
成功返回 ERROR_SUCCESS.
1 2 3 4 5 6 7 8
| LSTATUS RegSetValueExA( HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE *lpData, DWORD cbData );
|
RegEnumValue
注册表键值的枚举
成功返回 ERROR_SUCCESS.
1 2 3 4 5 6 7 8 9 10
| LSTATUS RegEnumValueA( HKEY hKey, DWORD dwIndex, LPSTR lpValueName, LPDWORD lpcchValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData );
|
RegDeleteValue
注册表键值的删除
成功返回 ERROR_SUCCESS.
1 2 3 4
| LSTATUS RegDeleteValueA( HKEY hKey, LPCSTR lpValueName );
|
GetModuleFileName
在开发过程中经常需要获得程序当前的运行目录,这时就可以使用GetModuleFileName
1 2 3 4 5
| DWORD WINAPI GetModuleFileName( HMODULE hModule, LPTSTR lpFileName, DWORD nSize );
|