Windows自动启动程序代码
时间: 2023-03-31 14:03:53 浏览: 119
以下是 Windows 自动启动程序代码的示例:
1. 在注册表中添加启动项
在注册表中添加启动项是一种常见的方法,可以让程序在 Windows 启动时自动运行。以下是一个示例代码:
```c
#include <Windows.h>
int main()
{
HKEY hKey;
DWORD dwDisposition;
// 打开注册表项
RegCreateKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", , NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition);
// 设置键值
RegSetValueEx(hKey, "MyProgram", , REG_SZ, (BYTE*)"C:\\MyProgram.exe", strlen("C:\\MyProgram.exe"));
// 关闭注册表项
RegCloseKey(hKey);
return ;
}
```
2. 在启动文件夹中添加快捷方式
另一种常见的方法是在启动文件夹中添加快捷方式,以下是一个示例代码:
```c
#include <Windows.h>
#include <ShlObj.h>
int main()
{
TCHAR szPath[MAX_PATH];
// 获取启动文件夹路径
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_STARTUP, NULL, , szPath)))
{
// 创建快捷方式
TCHAR szShortcutPath[MAX_PATH];
PathCombine(szShortcutPath, szPath, "MyProgram.lnk");
CoInitialize(NULL);
IShellLink* pShellLink;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&pShellLink);
if (SUCCEEDED(hr))
{
pShellLink->SetPath("C:\\MyProgram.exe");
IPersistFile* pPersistFile;
hr = pShellLink->QueryInterface(IID_IPersistFile, (LPVOID*)&pPersistFile);
if (SUCCEEDED(hr))
{
pPersistFile->Save(szShortcutPath, TRUE);
pPersistFile->Release();
}
pShellLink->Release();
}
CoUninitialize();
}
return ;
}
```
希望这些代码能够帮助你实现 Windows 自动启动程序的功能。