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

VC 开机自动启动程序代码

2010-03-06 14:53 399 查看
很多监控软件要求软件能够在系统重新启动后不用用户去点击图标启动项目,而是直接能够启动运行,方法是写注册表Software//Microsoft//Windows//CurrentVersion//Run。

参考程序可以见下:(查找程序目录的执行文件,存在则进行添加注册表操作)

//实用代码一

int C***Dlg::CreateRun(void)
{

//添加以下代码
HKEY RegKey;
CString sPath;
GetModuleFileName(NULL,sPath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer();
int nPos;
nPos=sPath.ReverseFind('//');
sPath=sPath.Left(nPos);
CString lpszFile=sPath+"//getip.exe";//这里加上你要查找的执行文件名称
CFileFind fFind;
BOOL bSuccess;
bSuccess=fFind.FindFile(lpszFile);
fFind.Close();

if(bSuccess)
{
CString fullName;
fullName=lpszFile;
RegKey=NULL;
RegOpenKey(HKEY_LOCAL_MACHINE,"Software//Microsoft//Windows//CurrentVersion//Run",&RegKey);
RegSetValueEx(RegKey,"getip",0,REG_SZ,(const unsigned char*)(LPCTSTR)fullName,fullName.GetLength());//这里加上你需要在注册表中注册的内容
this->UpdateData(FALSE);
}
else
{
//theApp.SetMainSkin();
::AfxMessageBox("没找到执行程序,自动运行失败");
exit(0);
}
return 0;
}

//把上面的getip(共2处)替换成自己想启动程序的名字。

————————————————————————————————————————————

————————————————————————————————————————————

实用代码二:

//写入注册表,开机自启动
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] = {0};
//得到程序自身的全路径
DWORD dwRet = GetModuleFileName(NULL, pFileName, MAX_PATH);
//添加一个子Key,并设置值 // 下面的"getip"是应用程序名字(不加后缀.exe)
lRet = RegSetValueEx(hKey, "getip", 0, REG_SZ, (BYTE *)pFileName, dwRet);

//关闭注册表
RegCloseKey(hKey);
if(lRet != ERROR_SUCCESS)
{
AfxMessageBox("系统参数错误,不能随系统启动");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: