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

来源:互联网 发布:手机通话记录软件大全 编辑:程序博客网 时间:2024/06/06 03:38

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,就可以了。

   

 

 

0 0
原创粉丝点击