天天看点

关于用VS实现开机自启动功能(win7/winXp)

void OnBnClickedCheckAutorun(bool _bAutoStart)

{

    char cFilePath[255] = {0};     

    HMODULE hFilePath = GetModuleHandle(NULL); 

    //得到当前执行文件的全路径

    GetModuleFileName(hFilePath, cFilePath, sizeof(cFilePath));

    if (_bAutoStart) 

    {

        //设置开机启动

        //打开注册表

        HKEY hKey;  

        iRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,

        "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey );

        if (iRet != ERROR_SUCCESS)

        {

          return ;

        }

        //写入注册表 

        iRet = RegSetValueEx(hKey, "文件名", 0, REG_SZ, (BYTE*)(LPCSTR)cFilePath, sizeof       (cFilePath));

        //关闭注册表   

       RegCloseKey(hKey);                

   }

       else

       {

           //取消设置开机启动

           //打开注册表

           HKEY hKey;  

           iRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,

          "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &hKey );

          if (iRet != ERROR_SUCCESS)

          {

              return ;

          }

           //删除注册表中内容 

           iRet = RegDeleteValue(hKey, "文件名");

           if (iRet != ERROR_SUCCESS)

           {

               return ;

           }

            //关闭注册表

            RegCloseKey(hKey);      

        } 

}

本文转自 我不会抽烟 51CTO博客,原文链接:http://blog.51cto.com/zhouhongyu1989/1179627,如需转载请自行联系原作者