注册表项管理

时间:2022-09-13 20:43:37

ClistCtrl初始化

    void CRegManageDlg::InitRunList()
{
m_RunList.SetExtendedStyle(m_RunList.GetExtendedStyle()
| LVS_EX_GRIDLINES //有网络格
| LVS_EX_FULLROWSELECT); //选择单行
m_RunList.ModifyStyle(0, LVS_REPORT|LVS_SINGLESEL|LVS_SHOWSELALWAYS);

m_RunList.InsertColumn(0, _T("NO."));
m_RunList.InsertColumn(1, _T("键 名"));
m_RunList.InsertColumn(2, _T("键 值"));

m_RunList.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
m_RunList.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
m_RunList.SetColumnWidth(2, LVSCW_AUTOSIZE_USEHEADER);
}

启动项枚举:

#define REG_RUN "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
void CRegManageDlg::ShowRunList()
{
//清空CListCtrl控件中的所有内容
m_RunList.DeleteAllItems();

DWORD dwType = 0;
DWORD dwBufferSize = MAXBYTE;
DWORD dwKeySize = MAXBYTE;
char szValueName[MAXBYTE] = {0};
char szValueKey[MAXBYTE] = {0};

HKEY hKey = NULL;
LONG lRet = RegOpenKey(HKEY_LOCAL_MACHINE, REG_RUN, &hKey);

if(lRet != ERROR_SUCCESS)
return;

int i = 0;
CString strTmp;
while(true)
{
lRet = RegEnumValue(hKey, i, szValueName, &dwBufferSize, NULL, &dwType, (unsigned char *)szValueKey, &dwKeySize);
if(lRet == ERROR_NO_MORE_ITEMS)
break;
strTmp.Format("%d", i);
m_RunList.InsertItem(i, strTmp);
m_RunList.SetItemText(i, 1, szValueName);
m_RunList.SetItemText(i, 2, szValueKey);
i++;
ZeroMemory(szValueName, MAXBYTE);
ZeroMemory(szValueKey, MAXBYTE);
}

RegCloseKey(hKey);
}

添加启动项:

void CRegManageDlg::OnButtonAdd() 
{
// TODO: Add your control notification handler code here
CRegAdd RegAdd;
RegAdd.DoModal();
if(strlen(RegAdd.szKeyName)>0 && strlen(RegAdd.szKeyValue)>0)
{
HKEY hKey = NULL;
LONG lRet = RegOpenKey(HKEY_LOCAL_MACHINE, REG_RUN, &hKey);

if(lRet != ERROR_SUCCESS)
return;

RegSetValueEx(hKey, RegAdd.szKeyValue, NULL, REG_SZ, (const unsigned char *)RegAdd.szKeyValue.GetBuffer(0), strlen(RegAdd.szKeyValue)+sizeof(char));
RegCloseKey(hKey);
ShowRunList();
}
else
AfxMessageBox("请输入完整内容!");
}

删除启动项:

void CRegManageDlg::OnButtonDel() 
{
// TODO: Add your control notification handler code here
POSITION pos = m_RunList.GetFirstSelectedItemPosition();
int nSelected = -1;

while(pos)
{
nSelected = m_RunList.GetNextSelectedItem(pos);
}

if(-1 == nSelected)
{
AfxMessageBox("请选择要删除的启动项!");
}

char szKeyName[MAXBYTE] = {0};
m_RunList.GetItemText(nSelected, 1, szKeyName, MAXBYTE);

AfxMessageBox(szKeyName);

HKEY hKey = NULL;

LONG lRet = RegOpenKey(HKEY_LOCAL_MACHINE, REG_RUN, &hKey);

RegDeleteValue(hKey, szKeyName);

RegCloseKey(hKey);

ShowRunList();
}

注册表项管理