VC开机自启动(一)需管理员权限 写入注册表

来源:互联网 发布:金融行业数据挖掘 编辑:程序博客网 时间:2024/04/29 10:59

开机自启动程序:

int checkAutoRun(){HKEY   hKey;char pFileName[MAX_PATH] = { 0 };char pValue[MAX_PATH] = { 0 };DWORD dataType = REG_SZ;DWORD dataSize = MAX_SIZE;;//得到程序自身的全路径 DWORD dwRet = GetModuleFileNameA(NULL, pFileName, MAX_PATH);//找到系统的启动项 LPCSTR lpRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";//打开启动项Key long lRet = RegOpenKeyExA(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_READ, &hKey);if (lRet == ERROR_SUCCESS){lRet = RegQueryValueExA(hKey, "server_pool_auto", NULL, &dataType, (LPBYTE)pValue, &dataSize);if (lRet != ERROR_SUCCESS) {return 0;}RegCloseKey(hKey);}if (strcmp(pFileName, pValue)==0){return 1;}else{return 0;}}int setAutoRun(){HKEY   hKey;char pFileName[MAX_PATH] = { 0 };//得到程序自身的全路径 DWORD dwRet = GetModuleFileNameW(NULL, (LPWCH)pFileName, MAX_PATH);//找到系统的启动项 LPCTSTR lpRun = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run");//打开启动项Key long lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_WRITE, &hKey);if (lRet == ERROR_SUCCESS){//添加注册  checkAutoRun返回1说明已经注册 返回0说明没有注册if ( !checkAutoRun()){//MessageBox(NULL, _T("yes"), NULL, NULL);lRet =  RegSetValueEx(hKey, _T("server_pool_auto"), 0, REG_SZ, (const BYTE*)(LPCSTR)pFileName, MAX_PATH);if (lRet != ERROR_SUCCESS)return 0;}//如果有那就是删除else{//MessageBox(NULL, _T("yes"), NULL, NULL);RegDeleteValue(hKey, _T("server_pool_auto"));if (lRet != ERROR_SUCCESS)return 0;}RegCloseKey(hKey);}return 1;}
获取.exe当前路径

常用方法一:
char szFilePath[MAX_PATH + 1]; GetModuleFileName(NULL, szFilePath, MAX_PATH); (_tcsrchr(szFilePath, _T('\\')))[1] = 0;//删除文件名,只获得路径OutputDebugString((char *)szFilePath);OutputDebugString("GetModuleFileName\r\n\r\n");常用方法二:char pDirBuf[MAX_PATH];GetCurrentDirectory(MAX_PATH,pDirBuf);OutputDebugString((char *)pDirBuf);OutputDebugString("GetCurrentDirectory\r\n\r\n");
//配置文件路径
char *lpPath = "RockeyConfig.ini";OutputDebugString((char *)szFilePath);

方法二注意情况:

使用GetCurrentDirectory函数

假设程序路径为D:\Test\tst.exe,执行GetCurrentDirectory函数

char pBuf[MAX_PATH];GetCurrentDirectory(MAX_PATH,pBuf);

pBuf="D:\Test"

但是如果使用CFileDialog、CFile::Open等函数后,设置不当则会导致再次获取当前路径值改变。所以,如要避免当前路径改变,如果使用CFileDialog,则要把在CFileDialog的dwFlags标志设置为OFN_NOCHANGEDIR。如下:

CFileDialog hFileDlg(false,NULL ,NULL,OFN_FILEMUSTEXIST | OFN_READONLY | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR,TEXT("Text Files (*.txt)|*.txt|All Files(*.*)|*.*|"),NULL);

也可以,先执行GetCurrentDirectory把获取到目录路径保存下来,处理完成后,再次SetCurrentDirectory设置一下。



0 0