您的位置:首页 > 编程语言 > C语言/C++

C++程序的自启动写入注册表的代码

2014-08-07 11:02 211 查看
C++程序向注册表中写入和删除自启动的程序

一下的代码都可以运行

// HKEY hKey;

// char path[MAX_PATH];

// ::GetModuleFileName(NULL,path,NULL);//得到当前项目的路径

// CString str;

// str.Format("%s",path);

// MessageBox(str);

// LPCTSTR DATA_SET = "SoftWare\\Microsoft\\Windows\\CurrentVersion\\Run";

// ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,DATA_SET,0,KEY_WRITE,&hKey);

// CButton *P = (CButton*)GetDlgItem(IDC_CHECKWINSTART);

// if (P->GetCheck())

// {

// if(ERROR_SUCCESS == ::RegSetValueEx(hKey,str,0,REG_SZ,(BYTE*)(LPCSTR)str,strlen(str)+1))

// ::AfxMessageBox("系统自启动设置成功!");

// ::RegCloseKey(hKey);

// }

// else

// {

// if (ERROR_SUCCESS == ::RegSetValueEx(hKey,str,0,REG_SZ,NULL,NULL))

// {

// ::AfxMessageBox("取消开机开机自启动!");//没有完全删除注册表

// }

// ::RegCloseKey(hKey);

// }

 

CButton *P = (CButton*)GetDlgItem(IDC_CHECKWINSTART);//是一个复选框的ID
if (P->GetCheck())
{
HKEY hKey;
//找到系统的启动项
LPCTSTR lpRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
//打开启动项Key
long lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_WRITE, &hKey);
if(lRet == ERROR_SUCCESS)   //设置该项开机启动
{
char pFileName[MAX_PATH] = "D:\\workspace\\sql\\debug\\sql.exe";   //得到程序自身的全路径
//DWORD dwRet = GetModuleFileName(NULL, pFileName, MAX_PATH);
//  pFileName = "D:\\workspace\\sql\\debug\\sql.exe";
lRet = RegSetValueEx(hKey, "test", 0, REG_SZ, (BYTE *)pFileName, strlen(pFileName)+1);
//添加一个子Key,并设置值 // 下面的"test"是写入注册表中的名称

//lRet = RegSetValueEx(hKey, "test", 0, REG_SZ, (BYTE *)pFileName, dwRet);

//关闭注册表
RegCloseKey(hKey);
if(lRet != ERROR_SUCCESS)
{
AfxMessageBox("系统参数错误,不能完成开机启动设置");
}
else
{
AfxMessageBox("打开开机启动成功");
}
}
}
else
{
HKEY hKey;
//找到系统的启动项
LPCTSTR lpRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
//打开启动项Key
long lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_WRITE, &hKey);
if(lRet == ERROR_SUCCESS)
{
//删除注册表中的启动项
lRet = RegDeleteValue(hKey, "test");  //test 为注册表中启动项的名称(也就是你写入的名称)
//关闭注册表
RegCloseKey(hKey);
if(lRet != ERROR_SUCCESS)
{
AfxMessageBox("系统参数错误,不能完成取消开机启动设置");
}
else
{
AfxMessageBox("关闭开机启动成功");
}
}
}

执行完上面的代码之后你可以打开注册表HKEY_LOCAL_MACHINE \SoftWare\\Microsoft\\Windows\\CurrentVersion\\Run 查看结果就很清楚了。(运行regedit)

下面是控制台的写入代码

#include <Windows.h> 

#include <tchar.h> 

int main(void) 



    HKEY hKey; 

    HKEY hNewKey; 

    DWORD dwDisposition=0; 

    __try 

    { 

        char binPath[MAX_PATH]="C:\\Users\\Administrator\\Desktop\\test.exe";//在这里设置你要启动的程序的路径 

        if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, 

            _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 

            0,KEY_ALL_ACCESS,&hKey)!=ERROR_SUCCESS) 

            __leave; 

        if(RegSetValueEx(hKey,_T("AutoStart"),0,REG_SZ,(const BYTE*)binPath, strlen(binPath)+1)!=ERROR_SUCCESS) //AutoStart是写入到注册表中的名字

            __leave; 

    } 

    __finally 

    { 

        RegCloseKey(hKey); 

    }     

    system("pause"); 

    return(0); 

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