C++/C++ 코드 기록

레지스트리 값 구하는 방법

lwj789 2022. 11. 4. 13:56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <Windows.h>
 
char *FindStringInString(const char *ap_str, const char *ap_find_str, int a_count);
 
int main()
{
    { // <-- Read registry value
        LONG lResult;
        HKEY hKey;
        DWORD dwType;
        DWORD dwBytes = 0;
        char regValue[] = "PendingFileRenameOperations";
 
 
        // open Regstry Key
        lResult = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager"0, KEY_READ, &hKey);
        if (lResult != ERROR_SUCCESS)
        {
            printf("Register Open Error (0x%x)\n", GetLastError());
            return -1;
        }
 
        // Get buffer size 
        if (RegQueryValueExA(hKey, regValue, NULLNULLNULL&dwBytes) == ERROR_SUCCESS)
        {
            char *pBuf = new char[dwBytes + 1];
 
            // Read Registry Key
            lResult = RegQueryValueExA(hKey, regValue, 0&dwType, (LPBYTE)pBuf, &dwBytes);
            if (lResult == ERROR_SUCCESS) {
                pBuf[dwBytes] = '\0';
 
                printf("dwBytes : %d\n\n", dwBytes);
 
                char *pFind_JRSDK24_ren = FindStringInString(pBuf, "51bbb6b.rbf", dwBytes);
                if (pFind_JRSDK24_ren == NULL)
                    printf("없음\n");
                else
                    printf("존재함 : %s\n", pFind_JRSDK24_ren);
            }
            else
                printf("Register Read Error\n\n");
            
 
            // to avoid leakage
            delete[] pBuf;
 
            RegCloseKey(hKey);
        }
 
 
    } // Read registry value -->
    return 0;
}
 
char *FindStringInString(const char *ap_str, const char *ap_find_str, int a_count)
{
    // 세부 비교를 위해 사용할 포인터 변수 선언
    const char *p_pos, *p_find_pos;
 
    // 찾을 문자열이 ""와 같이 비어있는 경우에는 ap_str의 시작 주소를 반환한다.
    if (*ap_find_str == 0return (char *)ap_str;
 
    // ap_str가 가리키는 문자열의 마지막 문자까지 체크한다.
    // 제일 처음에는 ap_str이 문자열의 시작 위치를 가리키고 있었지만
    // 반복이 진행되면 ap_str은 한 문자씩 뒤쪽으로 위치를 이동한다.
    int count = 0;
    while (/**ap_str != 0*/count != a_count) {
        // 문자가 서로 같은지 체크한다.
        if (*ap_str == *ap_find_str) {
            // 문자가 서로 일치한다면 그 다음에 있는 위치의 문자부터 시작해서
            // ap_find_str 문자열의 끝까지 일치하는지 반복해서 비교한다.
            p_pos = ap_str + 1;
            p_find_pos = ap_find_str + 1;
            while (*p_find_pos != 0 && *p_pos != 0 && *p_pos == *p_find_pos) {
                p_pos++;
                p_find_pos++;
            }
            // p_find_pos의 마지막까지 비교해서 나온것이라면ap_str에서 
            // ap_find_str 문자열 패턴을 찾았다는 뜻이기 때문에
            // 최초에 일치했던 ap_str의 주소를 반환한다.
            if (*p_find_pos == 0return (char *)ap_str;
            // p_pos가 NULL 문자를 만났다면 남은 ap_str의 길이가
            // ap_find_str의 문자열 길이보다 작다는 뜻이기 때문에
            // ap_str이 가리키는 문자열에서는 ap_find_str이 가리키는 
            // 문자열을 찾을수 없다는 뜻이다.
            if (*p_pos == 0break;
        }
        // 다음 문자로 이동한다.
        ap_str++;
        count++;
    }
    // ap_str에서 ap_find_str 패턴을 찾는데 실패함!
    return (char *)NULL;
}
cs

 

 

 

 

 

 

 

 

 

 

+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Registry에서 string value 쓰는 함수.
///
///        @param[in]    hKey        쓸 값이 존재하는 키, { HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, ...} 등의 값 사용.
///        @param[in]    lpSubKey    쓸 값이 존재하는 subkey path
///        @param[in]    lpValueKey    쓸 값의 이름
///        @param[in]    lpValue        쓸 값
///
///        \return        BOOL; 성공적으로 썼으면 TRUE 실패했으면 FALSE
///
/// \author JaeHyun Baek
BOOL MiscUtils::WriteStringValueInRegistry( HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueKey, LPCTSTR lpValue )
{
    CString strValue = _T("");
    HKEY hSubKey = NULL;
 
    // open the key
    if ( ::RegOpenKeyEx( hKey, lpSubKey, 0, KEY_ALL_ACCESS, &hSubKey ) == ERROR_SUCCESS )
    {
 
        DWORD cbSize = (DWORD)strlen(lpValue) + 1;
        BYTE *pBuf = new BYTE [ cbSize ];
        ::ZeroMemory( pBuf, cbSize );
        ::CopyMemory( pBuf, lpValue, cbSize - 1 );
        ::RegSetValueEx( hSubKey, lpValueKey, NULL, REG_SZ, pBuf, cbSize ); 
 
        // 키 닫기
        ::RegCloseKey( hSubKey );
 
        delete [] pBuf;
 
        return TRUE;
    }
 
    return FALSE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Registry에서 DWORD value 쓰는 함수.
///
///        @param[in]    hKey        쓸 값이 존재하는 키, { HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, ...} 등의 값 사용.
///        @param[in]    lpSubKey    쓸 값이 존재하는 subkey path
///        @param[in]    lpValueKey    쓸 값의 이름
///        @param[in]    dwValue        쓸 값
///
///        \return        BOOL; 성공적으로 썼으면 TRUE 실패했으면 FALSE
///
/// \author JaeHyun Baek
BOOL MiscUtils::WriteDWORDValueInRegistry( HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueKey, DWORD dwValue )
{
    CString strValue = _T("");
    HKEY hSubKey = NULL;
 
    // open the key
    if ( ::RegOpenKeyEx( hKey, lpSubKey, 0, KEY_ALL_ACCESS, &hSubKey ) == ERROR_SUCCESS )
    {
        ::RegSetValueEx( hSubKey, lpValueKey, NULL, REG_DWORD, (LPBYTE)&dwValue, sizeof(DWORD) ); 
 
 
        // 키 닫기
        ::RegCloseKey( hSubKey );
 
 
        return TRUE;
    }
 
    return FALSE;
}
그리고 읽기.
 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Registry에서 string value 읽어오는 함수.
/// CWinApp::GetProfileString(..) 함수와 다른 점은, 임의의 key 에 존재하는 값을 모두 읽을 수 있다는 점이 다름.
 
 
 
 
/// 키가 존재하지 않으면 empty string을 리턴함.
///
///        @param[in]    hKey        읽을 값이 존재하는 키, { HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, ...} 등의 값 사용.
///        @param[in]    lpSubKey    읽을 값이 존재하는 subkey path
///        @param[in]    lpValueKey    읽을 값의 이름
///
///        \return        CString; 해당 레지스트리 위치에서 읽은 값. Can be null string
///
///
CString MiscUtils::ReadStringValueInRegistry( HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueKey )
{
    CString strValue = _T("");
    HKEY hSubKey = NULL;
 
    // open the key
    if ( ::RegOpenKeyEx( hKey, lpSubKey, 0, KEY_READ, &hSubKey ) == ERROR_SUCCESS )
    {
        DWORD buf_size = 0;
 
        // 문자열의 크기를 먼저 읽어온다.
        if ( ::RegQueryValueEx( hSubKey, lpValueKey, NULLNULLNULL&buf_size ) == ERROR_SUCCESS )
        {
            // 메모리 할당하고...,
            TCHAR *pBuf = new TCHAR [ buf_size + 1 ];
 
            // 실제 값을 읽어온다.
            if ( ::RegQueryValueEx( hSubKey, lpValueKey, NULLNULL, (LPBYTE)pBuf, &buf_size ) == ERROR_SUCCESS )
            {
                pBuf[ buf_size ] = _T('\0');
                strValue = CString( pBuf );
            }
 
            // to avoid leakage
            delete [] pBuf;
        }
 
        // 키 닫기
        ::RegCloseKey( hSubKey );
    }
 
    return strValue;
}
 
 
 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// 임의의 레지스트리 키 위치에서 DWORD 값을 읽어오기 위한 함수.
/// CWinApp::GetProfileInt(..) 함수와 다른 점은, 임의의 key 에 존재하는 값을 모두 읽을 수 있다는 점이 다름.
 
 
 
 
/// 키가 존재하지 않으면 \a dwDefault 를 리턴함.
///
///        @param[in]    hKey        읽을 값이 존재하는 키, { HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, ...} 등의 값 사용.
///        @param[in]    lpSubKey    읽을 값이 존재하는 subkey path
///        @param[in]    lpValueKey    읽을 값의 이름
///        @param[in]    dwDefault    값이 존재하지 않는 경우에 리턴할 값
///
///        \return        DWORD; 해당 레지스트리 위치에서 읽은 값
///
DWORD MiscUtils::ReadDWORDValueInRegistry( HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueKey, DWORD dwDefault /*= -1*/ )
{
    DWORD dwValue = (DWORD)dwDefault;
    HKEY hSubKey = NULL;
 
    // 키 열기
    if ( ::RegOpenKeyEx( hKey, lpSubKey, 0, KEY_READ, &hSubKey ) == ERROR_SUCCESS )
    {
        DWORD buf_size = sizeof(DWORD);    
 
        // DWORD 값 읽어오기
        if ( ::RegQueryValueEx( hSubKey, lpValueKey, NULLNULL, (LPBYTE)&dwValue, &buf_size ) == ERROR_SUCCESS )
        {
            ASSERT( buf_size == sizeof(DWORD) );
        }
 
        // 키 닫기
        ::RegCloseKey( hSubKey );
    }
 
    return dwValue;
}
이제 실제 사용 하는 것은 다음과 같은 식으로 해주면 된다.
const CString strKey = _T("SOFTWARE\RoterSoft\ExampleApp\Settings");
    MiscUtils::WriteStringValueInRegistry( HKEY_LOCAL_MACHINE, (LPCTSTR) strKey, _T("strTest"), _T("roterpekr"));
    MiscUtils::WriteDWORDValueInRegistry( HKEY_LOCAL_MACHINE, (LPCTSTR) strKey, _T("dwTest"), 123456);
첫 번째 인자인 hKey는 다음을 알아서 넣어 주면 된다.
 
#define HKEY_CLASSES_ROOT           (( HKEY ) (ULONG_PTR)((LONG)0x80000000) )
#define HKEY_CURRENT_USER           (( HKEY ) (ULONG_PTR)((LONG)0x80000001) )
#define HKEY_LOCAL_MACHINE          (( HKEY ) (ULONG_PTR)((LONG)0x80000002) )
#define HKEY_USERS                  (( HKEY ) (ULONG_PTR)((LONG)0x80000003) )
출처: https://jhb.kr/228 [JHB의 삽질 이야기:티스토리]
cs