c#版本:
private bool SetAutoRun(bool onFlag) { bool bRet = true; try { string path = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; RegistryKey rk2 = rk.CreateSubKey(@"SoftwareMicrosoftWindowsCurrentVersionRun"); if (onFlag) { rk2.SetValue("you app name", path); } else { rk2.DeleteValue("you app name", false); } rk2.Close(); rk.Close(); } catch (System.Exception ex) { bRet = false; lblmsg.Text = "exception:" + ex.Message; MessageBox.Show(ex.Message); } return bRet; }
c++ 版本:
void CAutoDlg::SetAutoRun(BOOL bAutoRun) { HKEY hKey; CString strRegPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Run";//找到系统的启动项 if (bAutoRun) { if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) //打开启动项 { TCHAR szModule[_MAX_PATH]; GetModuleFileName(NULL, szModule, _MAX_PATH);//得到本程序自身的全路径 RegSetValueEx(hKey, "AUTODLG", 0, REG_SZ, (const BYTE*)(LPCSTR)szModule, strlen(szModule)); //添加一个子Key,并设置值,"AUTODLG"是应用程序名字(不加后缀.exe) RegCloseKey(hKey); //关闭注册表 } else { PRINTF(LEVEL_INFO, Logger, LOG_FILE_LINE, "%s", "系统参数错误,不能随系统启动"); } } else { if (RegOpenKeyEx(HKEY_CURRENT_USER, strRegPath, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) { RegDeleteValue(hKey, "AUTODLG"); RegCloseKey(hKey); } } }
相信对需要的你是有用得,好用请说声谢谢。