MFC实现程序开机自启动:
1、ttype.h
#ifndef STL_TTYPE_H_AUTOSTART
#define STL_TTYPE_H_AUTOSTART
template<typename _char_t, typename TA, typename TW>
struct ttype;
template<typename TA, typename TW>
struct ttype<char, TA, TW>
{
typedef TA type;
};
template<typename TA, typename TW>
struct ttype<wchar_t, TA, TW>
{
typedef TW type;
};
//
//tvalue
//
template<typename TA, typename TW>
inline typename ttype<char, TA, TW>::type tvalue(char*, TA a, TW w)
{
return a;
}
template<typename TA, typename TW>
inline typename ttype<wchar_t, TA, TW>::type tvalue(wchar_t*, TA a, TW w)
{
return w;
}
template<typename _char_t, typename TA, typename TW>
inline typename ttype<_char_t, TA, TW>::type tvalue(TA a, TW w)
{
return tvalue<TA, TW>(static_cast<_char_t*>(0), a, w);
}
#define T_TEXT(T, S) tvalue<T>(S, L##S)
#endif
2、测试代码
#include <windows.h>
#include "ttype.h"
//判断软件是否开机运行
template<typename _char_t>
bool is_autorun(const _char_t* appname, const _char_t* strPath)
{
_char_t buf[MAX_PATH] = { 0 };
DWORD n = MAX_PATH;
HKEY hKey;
DWORD type = REG_SZ;
bool autorun = false;
LONG result = tvalue<_char_t>(RegOpenKeyExA, RegOpenKeyExW)(
HKEY_CURRENT_USER,
T_TEXT(_char_t, "Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
0, KEY_READ, &hKey);
if (ERROR_SUCCESS == result)
{
tvalue<_char_t>(RegQueryValueExA, RegQueryValueExW)(hKey, appname, 0, &type, (LPBYTE)buf, &n);
if (n){
if (!strcmp(buf, strPath)){
autorun = true;
}
}
RegCloseKey(hKey);
}
return autorun;
}
//设置是否开机运行,兼容xp
template<typename _char_t>
bool set_autorun(const _char_t* appname, const _char_t* exefile, bool run)
{
HKEY hKey;
bool autorun = false;
LONG result = tvalue<_char_t>(RegOpenKeyExA, RegOpenKeyExW)(
HKEY_CURRENT_USER,
T_TEXT(_char_t, "Software\\Microsoft\\Windows\\CurrentVersion\\Run"),
0, KEY_WRITE, &hKey);
if (ERROR_SUCCESS == result)
{
if (run){
tvalue<_char_t>(RegSetValueExA, RegSetValueExW)(hKey, appname, 0, REG_SZ, (BYTE*)exefile, strlen(exefile)*sizeof(_char_t));
autorun = true;
}
else{
tvalue<_char_t>(RegDeleteValueA, RegDeleteValueW)(hKey, appname);
autorun = false;
}
RegCloseKey(hKey);
}
return autorun;
}
void CAutoStartDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
const char* app_name = "AutoStart";
const char* strPath = "C:\\Users\\Desktop\\AutoStart\\Debug\\AutoStart.exe";
if (!is_autorun(app_name, strPath)){
set_autorun(app_name, strPath, true);
}
CDialogEx::OnOK();
}