您的位置:首页 > 其它

MFC通过注册表 实现程序开机自动运行

2015-09-15 15:14 537 查看
1.创建一个成员函数:

void CAutoRunByRegistryDlg::SetAutoRun(bool bAutoRun)

{

HKEY hKey;

CString strRegPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";//find the system's startup

if (bAutoRun)

{

if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) //open running item

{

TCHAR szModule[_MAX_PATH];

GetModuleFileName(NULL, szModule, _MAX_PATH);//Get oneself program's name

RegSetValueEx(hKey,"AutoRunByRegistry", 0, REG_SZ, (const BYTE*)(LPCSTR)szModule, strlen(szModule));

//add a child Key,and set a value="AutoRunByRegistry",it is a program name (remove .exe),of course KeyVaule can set anyone.

RegCloseKey(hKey); //close Registry

}

else

{

AfxMessageBox("the system parameters error,AutoRun fail!");

}

}

else

{

if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS)

{

RegDeleteValue (hKey,"AutoRunByRegistry"); //Del KeyVaule="AutoRunByRegistry", so program AutoRunByRegistry.exe will can AutoRun.

RegCloseKey(hKey);

}

}

}

2.增加函数响应:

以下代码,可以放到初始化函数OnInitDialog(),或则按钮响应函数都可以。

SetAutoRun(true); //add registrykey value

//SetAutoRun(false); //remove registrykey value

3.效果可以查看注册表:在运行中输入:regedt32.exe

然后找到路径为:SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run,就可以看到注册的程序。

以上程序实现了开机启动运行自身的程序,如果想开机启动其他的应用程序,只需要在RegSetValueEx函数中把程序的完整路径名字设置OK,就可以了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: