微软vb 读写注册表
时间: 2023-11-25 20:51:05 浏览: 47
使用微软提供的CReg类可以方便地读写注册表,具体用法如下:
```cpp
#include <creg.hxx>
// 读取注册表
CRegKey reg;
if (reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion"), KEY_READ) == ERROR_SUCCESS)
{
DWORD dwType = REG_SZ;
TCHAR szValue[1024] = { 0 };
ULONG ulCount = 1024;
if (reg.QueryStringValue(_T("ProgramFilesDir"), szValue, &ulCount) == ERROR_SUCCESS)
{
// 读取成功
// szValue中存储了ProgramFilesDir的值
}
reg.Close();
}
// 写入注册表
CRegKey reg;
if (reg.Create(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\MyCompany\\MyApp")) == ERROR_SUCCESS)
{
if (reg.SetStringValue(_T("MyValue"), _T("Hello, World!")) == ERROR_SUCCESS)
{
// 写入成功
}
reg.Close();
}
```
另外,在VB中,可以使用自身的SaveSetting、GetSetting函数读写注册表,也可以使用API函数来实现注册表任意读写。具体用法可以参考以下代码:
```vb
' 读取注册表
Dim hKey As Long
Dim dwType As Long
Dim dwSize As Long
Dim sValue As String
hKey = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion", KEY_READ)
If hKey <> 0 Then
dwType = REG_SZ
sValue = String$(1024, 0)
dwSize = Len(sValue)
If QueryValueEx(hKey, "ProgramFilesDir", 0, dwType, ByVal sValue, dwSize) = ERROR_SUCCESS Then
' 读取成功
' sValue中存储了ProgramFilesDir的值
End If
RegCloseKey hKey
End If
' 写入注册表
hKey = CreateKey(HKEY_LOCAL_MACHINE, "SOFTWARE\MyCompany\MyApp")
If hKey <> 0 Then
If SetValueEx(hKey, "MyValue", 0, REG_SZ, "Hello, World!", Len("Hello, World!")) = ERROR_SUCCESS Then
' 写入成功
End If
RegCloseKey hKey
End If
```