Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.56/41: Рейтинг темы: голосов - 41, средняя оценка - 4.56
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26

Экспорт реестра в reg файл

22.02.2015, 15:38. Показов 8405. Ответов 44
Метки нет (Все метки)

Помогите пожалуйста написать код для экспорта настроек игрушки в reg файл

Cleaner.reg это для удаления записей из реестра после того как был сделан экспорт
save.reg - Это куда экспортируются настройки самой игрушки

Здесь смотрел нету ничего про экспорт Работа с реестром в C++ Builder

P.S
Не знаю как написать,я новичок в программировании!
В архиве batch скрипты для экспорта настроек и reg файлы
Вложения
Тип файла: rar archive.rar (1.4 Кб, 20 просмотров)
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
22.02.2015, 15:38
Ответы с готовыми решениями:

Как программно экспортировать ветку реестра в файл?
Причем не какой-то отдельный параметр, а ветку целиком. Пробовал запустить reg.exe с параметрами, но нужная ветка слишком глубоко, он...

Экспорт данных из Memo в txt файл через диалог сохранения
Здравствуйте, как сделать, чтоб при нажатии кнопки можно было выбрать файл, в который бы сохранялись данные из memo поля или же задать...

Экспорт веток реестра в REG файл
Нужно перед внесением изменений в реестр с помощью REG файла, сохранить изменяемые ключи в другой REG файл. Экспорт ключей с помощью...

44
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 13:02  [ТС]
C++
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
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
 
#include "Unit1.h"
#include <memory>
#include "Registry.hpp"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
 
// ---------------------------------------------------------------------------
namespace Regutils {
 
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
}
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    //Импорт настроек из reg файла в реестр
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "App\\reg\\save.reg", NULL); //Импорт в папку которая находиться в папке вместе с exe  : App\\reg\\save.reg
}
    //Экспорт в папку которая находиться в папке вместе с exe  : App\\reg\\save.reg
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", AnsiString path = ExtractFilePath(Application->ExeName)+"App\\reg\\save.reg", HKEY_CURRENT_USER);
 
 
    //Удаление ключей
    TRegistry *reg=new TRegistry();
    reg->RootKey=HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
 
    TRegistry *reg=new TRegistry();
    reg->RootKey=HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
 
    TRegistry *reg=new TRegistry();
    reg->RootKey=HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}

Checking project dependencies...
Compiling Project1.cbproj (Debug, Win32)
bcc32 command line for "Unit1.cpp"
c:\program files (x86)\embarcadero\studio\15.0\bin\bcc32. exe -D_DEBUG -DUSEPACKAGES -n.\Win32\Debug -I"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"C:\Program Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39\boost\tr1\tr1";"C:\Program
Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39";"c:\program files (x86)\embarcadero\studio\15.0\include";" c:\program files
(x86)\embarcadero\studio\15.0\include\di nkumware";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\crtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\sdk";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\rtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\fmx";"C:\Program Files
(x86)\FastReports\LibD21";"C:\Program Files (x86)\Raize\CS5\Lib\RS-XE7\Win32";C:\Users\Public\Documents\Emb arcadero\Studio\15.0\hpp\Win32 -y -Q -k
-r- -c -tR -tM -tU -tW -C8 -o.\Win32\Debug\Unit1.obj -w-par -Od -v -vi- -H=.\Win32\Debug\Project1.pch -H Unit1.cpp
[bcc32 Error] Unit1.cpp(127): E2268 Call to undefined function 'SetPrivilege'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
[bcc32 Error] Unit1.cpp(132): E2108 Improper use of typedef 'AnsiString'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
[bcc32 Error] Unit1.cpp(132): E2121 Function call missing )
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
[bcc32 Error] Unit1.cpp(142): E2238 Multiple declaration for 'reg'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
[bcc32 Error] Unit1.cpp(136): E2344 Earlier declaration of 'reg'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
[bcc32 Error] Unit1.cpp(148): E2238 Multiple declaration for 'reg'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
[bcc32 Error] Unit1.cpp(142): E2344 Earlier declaration of 'reg'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
Failed
Elapsed time: 00:00:00.2

Как ошибки исправить ?
0
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33446 / 21546 / 8248
Регистрация: 22.10.2011
Сообщений: 36,996
Записей в блоге: 12
23.02.2015, 13:16
Начиная со 131 строки:
C++
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    // Экспорт в папку которая находиться в папке вместе с exe  : App\\reg\\save.reg
    AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
А функцию SetPrivilege (которой у тебя в коде НЕТ) можно взять здесь: Enabling and Disabling Privileges in C++

 Комментарий модератора 
И перестань дублировать темы, в конце концов. Одним и тем же заполонил весь раздел уже. Правила вообще что-ли не читал? Так почитай, чтоб потом не пожалеть.
0
 Аватар для BRcr
4043 / 2333 / 292
Регистрация: 03.02.2011
Сообщений: 5,066
Записей в блоге: 10
23.02.2015, 13:39
Цитата Сообщение от Ciumrdimat Посмотреть сообщение
Как ошибки исправить ?
Начать с чтения книг - Путеводитель по книжкам про C++ Builder
И закончить торжественным ритуалом прощания с копипастой, бессмысленной и беспощадной; усекновением переменной path, объявленной от балды там, где не положено, и вообще нафиг не нужной; удалением переобъявлений переменной reg.

Если решишь пропустить пункты номер раз и номер два, то не бывать тебе кулхацкером ни-ко-гда.
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 13:56  [ТС]
C++
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
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
 
#include "Unit1.h"
#include <memory>
#include "Registry.hpp"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
 
// ---------------------------------------------------------------------------
namespace Regutils {
 
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
}
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    //Импорт настроек из reg файла в реестр
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "App\\reg\\save.reg", NULL); //Импорт в папку которая находиться в папке вместе с exe  : App\\reg\\save.reg
}
    AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}
Checking project dependencies...
Compiling Project1.cbproj (Debug, Win32)
bcc32 command line for "Unit1.cpp"
c:\program files (x86)\embarcadero\studio\15.0\bin\bcc32. exe -D_DEBUG -DUSEPACKAGES -n.\Win32\Debug -I"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"C:\Program Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39\boost\tr1\tr1";"C:\Program
Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39";"c:\program files (x86)\embarcadero\studio\15.0\include";" c:\program files
(x86)\embarcadero\studio\15.0\include\di nkumware";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\crtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\sdk";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\rtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\fmx";"C:\Program Files
(x86)\FastReports\LibD21";"C:\Program Files (x86)\Raize\CS5\Lib\RS-XE7\Win32";C:\Users\Public\Documents\Emb arcadero\Studio\15.0\hpp\Win32 -y -Q -k
-r- -c -tR -tM -tU -tW -C8 -o.\Win32\Debug\Unit1.obj -w-par -Od -v -vi- -H=.\Win32\Debug\Project1.pch -H Unit1.cpp
[bcc32 Error] Unit1.cpp(127): E2268 Call to undefined function 'SetPrivilege'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
Failed
Elapsed time: 00:00:00.2


Цитата Сообщение от volvo Посмотреть сообщение
А функцию SetPrivilege (которой у тебя в коде НЕТ) можно взять здесь: Enabling and Disabling Privileges in C++
Помогите доделать ничего не понимаю
0
Практикантроп
 Аватар для nick42
4841 / 2726 / 534
Регистрация: 23.09.2011
Сообщений: 5,798
23.02.2015, 14:04
Ciumrdimat, просто добавь перед Button1Click определение функции SetPrivilege...
C++
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
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
}
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
 
    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }
 
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
 
    // Enable the privilege or disable all privileges.
 
    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }
 
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
 
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }
 
    return TRUE;
}
 
void __fastcall TForm1::Button1Click(TObject *Sender) . . .
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 14:41  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
Ciumrdimat, просто добавь перед Button1Click определение функции SetPrivilege...
Код компилирует без ошибок, но не работает!

C++
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <memory>
#include "Registry.hpp"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
namespace Regutils {
 
    // экспорт ветки реестра с подавлением запроса на перезапись
    // генерирует исключение, если не найден ключ в реестре,
    // не может запустить программу "REG" или, если она возвратила ошибку
 
    // пример: допустим необходимо экспортировать [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Winsock]
    // в файл [g:\\Test\\test.reg]
    // листинг: Regutils::ExportKey("SYSTEM\\CurrentControlSet\\services\\Winsock", "g:\\Test\\test.reg", HKEY_LOCAL_MACHINE);
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
 
//----------nick42
 
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
 
    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }
 
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
 
    // Enable the privilege or disable all privileges.
 
    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }
 
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
 
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }
 
    return TRUE;
}
 
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
 
    AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}

На всякий случай лог компиляции


Checking project dependencies...
Compiling Project1.cbproj (Debug, Win32)
bcc32 command line for "Unit1.cpp"
c:\program files (x86)\embarcadero\studio\15.0\bin\bcc32. exe -D_DEBUG -DUSEPACKAGES -n.\Win32\Debug -I"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"C:\Program Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39\boost\tr1\tr1";"C:\Program
Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39";"c:\program files (x86)\embarcadero\studio\15.0\include";" c:\program files
(x86)\embarcadero\studio\15.0\include\di nkumware";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\crtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\sdk";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\rtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\fmx";"C:\Program Files
(x86)\FastReports\LibD21";"C:\Program Files (x86)\Raize\CS5\Lib\RS-XE7\Win32";C:\Users\Public\Documents\Emb arcadero\Studio\15.0\hpp\Win32 -y -Q -k
-r- -c -tR -tM -tU -tW -C8 -o.\Win32\Debug\Unit1.obj -w-par -Od -v -vi- -H=.\Win32\Debug\Project1.pch -H Unit1.cpp
ilink32 command line
c:\program files (x86)\embarcadero\studio\15.0\bin\ilink3 2.exe -G8 -L.\Win32\Debug;"c:\program files (x86)\embarcadero\studio\15.0\lib\win32\ release";
"c:\program files (x86)\embarcadero\studio\15.0\lib\Win32\ debug";"c:\program files (x86)\embarcadero\studio\15.0\lib\win32\ release";"c:\program files
(x86)\embarcadero\studio\15.0\lib\win32\ release\psdk";"C:\Program Files (x86)\FastReports\LibD21";"C:\Program Files (x86)\Raize\CS5\Lib\RS-XE7\Win32";
C:\Users\Public\Documents\Embarcadero\St udio\15.0\DCP -j.\Win32\Debug;"c:\program files (x86)\embarcadero\studio\15.0\lib\win32\ release";"c:\program
files (x86)\embarcadero\studio\15.0\lib\Win32\ debug";"c:\program files (x86)\embarcadero\studio\15.0\lib\win32\ release";"c:\program files
(x86)\embarcadero\studio\15.0\lib\win32\ release\psdk";"C:\Program Files (x86)\FastReports\LibD21";"C:\Program Files (x86)\Raize\CS5\Lib\RS-XE7\Win32";
C:\Users\Public\Documents\Embarcadero\St udio\15.0\DCP -l.\Win32\Debug -v -GA"C:\Users\1\AppData\Local\Temp\vfs9C30 .tmp"="C:\Users\1\Desktop\Новая
папка (3)\Unit1.dfm" -aa -V5.0 -Tpe c0w32w rtl.bpi vcl.bpi memmgr.lib sysinit.obj .\Win32\Debug\Project1.obj .\Win32\Debug\Unit1.obj ,
.\Win32\Debug\Project1.exe , .\Win32\Debug\Project1.map , import32.lib cp32mti.lib , , Project1.res
Success
Elapsed time: 00:00:00.3

C++
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
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
//---------------------------------------------------------------------------
USEFORM("Unit1.cpp", Form1);
//---------------------------------------------------------------------------
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
    try
    {
        Application->Initialize();
        Application->MainFormOnTaskBar = true;
        Application->CreateForm(__classid(TForm1), &Form1);
        Application->Run();
    }
    catch (Exception &exception)
    {
        Application->ShowException(&exception);
    }
    catch (...)
    {
        try
        {
            throw Exception("");
        }
        catch (Exception &exception)
        {
            Application->ShowException(&exception);
        }
    }
    return 0;
}
//---------------------------------------------------------------------------

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//---------------------------------------------------------------------------
 
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE-managed Components
    TButton *Button1;
    void __fastcall Button1Click(TObject *Sender);
private:    // User declarations
public:     // User declarations
    __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
Миниатюры
Экспорт реестра в reg файл   Экспорт реестра в reg файл  
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 14:49  [ТС]
C++
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <memory>
#include "Registry.hpp"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
namespace Regutils {
 
    // экспорт ветки реестра с подавлением запроса на перезапись
    // генерирует исключение, если не найден ключ в реестре,
    // не может запустить программу "REG" или, если она возвратила ошибку
 
    // пример: допустим необходимо экспортировать [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Winsock]
    // в файл [g:\\Test\\test.reg]
    // листинг: Regutils::ExportKey("SYSTEM\\CurrentControlSet\\services\\Winsock", "g:\\Test\\test.reg", HKEY_LOCAL_MACHINE);
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
 
//----------nick42
 
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
 
    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }
 
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
 
    // Enable the privilege or disable all privileges.
 
    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }
 
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
 
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }
 
    return TRUE;
}
 
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "c:\\saved1.reg", NULL);
}
 
    AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}
Так тоже самое! Что делать ?
0
Практикантроп
 Аватар для nick42
4841 / 2726 / 534
Регистрация: 23.09.2011
Сообщений: 5,798
23.02.2015, 15:08
Цитата Сообщение от Ciumrdimat Посмотреть сообщение
Что делать ?
не шарахаться и не паниковать прежде всего. Проверь regedit`ом соотв. ключи в реестре; попробуй сохранять в "простой" (англоязычной) папке на диске D (если есть) или С ( но не системной)
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 15:16  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
не шарахаться и не паниковать прежде всего. Проверь regedit`ом соотв. ключи в реестре; попробуй сохранять в "простой" (англоязычной) папке на диске D (если есть) или С ( но не системной)
Проверял всё работает, на С++ нет


Это батник всё делает как надо

@echo off
regedit /S "%cd%\App\reg\save.reg"
hl.exe -game cstrike
regedit /S /E "%cd%\App\reg\save.reg" "HKEY_CURRENT_USER\Software\Valve\Ha lf-Life\Settings"
regedit /S "%cd%\App\reg\Cleaner.reg"
exit

Почему на C++ не работает ?
0
Практикантроп
 Аватар для nick42
4841 / 2726 / 534
Регистрация: 23.09.2011
Сообщений: 5,798
23.02.2015, 15:24
А почему у меня работает? (если в реестре ключи правильные, существуют, и путь для сохранения указан реальный. Если нет таких папок: ... .\Win32\Debug\App\reg\ то и будет ошибка, как на твоих скриншотах)
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 15:37  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
А почему у меня работает? (если в реестре ключи правильные, существуют, и путь для сохранения указан реальный. Если нет таких папок: ... .\Win32\Debug\App\reg\ то и будет ошибка, как на твоих скриншотах)
в реестре существует такой ключ,когда прописывал полный в ручную всё работало даже папка сама создавалась

C++
1
2
AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
Миниатюры
Экспорт реестра в reg файл   Экспорт реестра в reg файл  
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 15:57  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
App\reg\
Я папки не создавал сейчас

Добавлено через 18 минут
C++
1
if(TDirectory::Exists(L"App\\reg")) TDirectory::CreateDirectory(L"App\\reg", true);
Как сделать чтобы папки создались в где exe проекта лежит ?

C++
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <memory>
#include "Registry.hpp"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
namespace Regutils {
 
    // экспорт ветки реестра с подавлением запроса на перезапись
    // генерирует исключение, если не найден ключ в реестре,
    // не может запустить программу "REG" или, если она возвратила ошибку
 
    // пример: допустим необходимо экспортировать [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Winsock]
    // в файл [g:\\Test\\test.reg]
    // листинг: Regutils::ExportKey("SYSTEM\\CurrentControlSet\\services\\Winsock", "g:\\Test\\test.reg", HKEY_LOCAL_MACHINE);
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
 
//----------nick42
 
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
 
    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }
 
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
 
    // Enable the privilege or disable all privileges.
 
    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }
 
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
 
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }
 
    return TRUE;
}
 
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "c:\\saved1.reg", NULL);
}
 
    AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}
0
Практикантроп
 Аватар для nick42
4841 / 2726 / 534
Регистрация: 23.09.2011
Сообщений: 5,798
23.02.2015, 16:13
C++
1
2
3
    UnicodeString path = ExtractFilePath(Application->ExeName)+"App\\reg\\";
    CreateDirectory(path.c_str() ,NULL);
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path+"save.reg", HKEY_CURRENT_USER);
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 16:21  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
UnicodeString path = ExtractFilePath(Application->ExeName)+"App\\reg\\";
* * CreateDirectory(path.c_str() ,NULL);
* * Regutils::ExportKey("Software\\Valve\\Ha lf-Life\\Settings", path+"save.reg", HKEY_CURRENT_USER);
C++
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
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
 
#include "Unit1.h"
#include <memory>
#include "Registry.hpp"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
 
// ---------------------------------------------------------------------------
namespace Regutils {
 
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
}
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    //Импорт настроек из reg файла в реестр
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "App\\reg\\save.reg", NULL); //Импорт в папку которая находиться в папке вместе с exe  : App\\reg\\save.reg
}
    UnicodeString path = ExtractFilePath(Application->ExeName)+"App\\reg\\";
    CreateDirectory(path.c_str() ,NULL);
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path+"save.reg", HKEY_CURRENT_USER);
 
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}

Checking project dependencies...
Compiling Project1.cbproj (Debug, Win32)
bcc32 command line for "Unit1.cpp"
c:\program files (x86)\embarcadero\studio\15.0\bin\bcc32. exe -D_DEBUG -DUSEPACKAGES -n.\Win32\Debug -I"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"C:\Program Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39\boost\tr1\tr1";"C:\Program
Files (x86)\Embarcadero\Studio\15.0\include\bo ost_1_39";"c:\program files (x86)\embarcadero\studio\15.0\include";" c:\program files
(x86)\embarcadero\studio\15.0\include\di nkumware";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\crtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\sdk";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\rtl";"c:\program files
(x86)\embarcadero\studio\15.0\include\wi ndows\vcl";"c:\program files (x86)\embarcadero\studio\15.0\include\wi ndows\fmx";"C:\Program Files
(x86)\FastReports\LibD21";"C:\Program Files (x86)\Raize\CS5\Lib\RS-XE7\Win32";C:\Users\Public\Documents\Emb arcadero\Studio\15.0\hpp\Win32 -y -Q -k
-r- -c -tR -tM -tU -tW -C8 -o.\Win32\Debug\Unit1.obj -w-par -Od -v -vi- -H=.\Win32\Debug\Project1.pch -H Unit1.cpp
[bcc32 Error] Unit1.cpp(127): E2268 Call to undefined function 'SetPrivilege'
Full parser context
Unit1.cpp(122): parsing: void _fastcall TForm1::Button1Click(TObject *)
Failed
Elapsed time: 00:00:00.2
0
Практикантроп
 Аватар для nick42
4841 / 2726 / 534
Регистрация: 23.09.2011
Сообщений: 5,798
23.02.2015, 16:33
И шо!? По новой всё объяснять? (где определение SetPrivilege делось?). Пора начинать понимать, что вам пишет компилятор...
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 16:40  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
И шо!? По новой всё объяснять? (где определение SetPrivilege делось?). Пора начинать понимать, что вам пишет компилятор...
Не тот код скопировал...
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 16:43  [ТС]
C++
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <memory>
#include "Registry.hpp"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
namespace Regutils {
 
    // экспорт ветки реестра с подавлением запроса на перезапись
    // генерирует исключение, если не найден ключ в реестре,
    // не может запустить программу "REG" или, если она возвратила ошибку
 
    // пример: допустим необходимо экспортировать [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Winsock]
    // в файл [g:\\Test\\test.reg]
    // листинг: Regutils::ExportKey("SYSTEM\\CurrentControlSet\\services\\Winsock", "g:\\Test\\test.reg", HKEY_LOCAL_MACHINE);
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
 
//----------nick42
 
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
 
    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }
 
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
 
    // Enable the privilege or disable all privileges.
 
    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }
 
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
 
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }
 
    return TRUE;
}
 
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "c:\\saved1.reg", NULL);
}
 
    UnicodeString path = ExtractFilePath(Application->ExeName)+"App\\reg\\";
    CreateDirectory(path.c_str() ,NULL);
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path+"save.reg", HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}
Опять эта же самая ошибка...
Миниатюры
Экспорт реестра в reg файл  
0
Практикантроп
 Аватар для nick42
4841 / 2726 / 534
Регистрация: 23.09.2011
Сообщений: 5,798
23.02.2015, 17:39
В папке, откуда запускаешь программу (Debug) какие еще папки есть (с вложенными)?

Добавлено через 18 минут
Короче говоря, если нужно создать целый ряд папок, то применяешь такую функцию__
C++
1
ForceDirectories( ".\\111\\222\\333\\444" );
из текущей папки (откуда запускаешь - .\) создается папка 111, в ней папка 222, в ней папка 333 и т.д. Что касается твоего случая, то мне кажется, что папка App лишняя. Достаточно же в папке с программой иметь подкаталог reg для сохранения содержимого реестра. Впрочем, решать тебе.
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 18:07  [ТС]
Цитата Сообщение от nick42 Посмотреть сообщение
Короче говоря, если нужно создать целый ряд папок, то применяешь такую функцию
C++
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
#include <memory>
#include "Registry.hpp"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
namespace Regutils {
 
    // экспорт ветки реестра с подавлением запроса на перезапись
    // генерирует исключение, если не найден ключ в реестре,
    // не может запустить программу "REG" или, если она возвратила ошибку
 
    // пример: допустим необходимо экспортировать [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Winsock]
    // в файл [g:\\Test\\test.reg]
    // листинг: Regutils::ExportKey("SYSTEM\\CurrentControlSet\\services\\Winsock", "g:\\Test\\test.reg", HKEY_LOCAL_MACHINE);
 
    void ExportKey(const UnicodeString & sRegistryPath, const UnicodeString &sFileName, HKEY hRootKey = HKEY_CURRENT_USER) {
 
        UnicodeString /* out */ sRootKey = "HKCU";
 
        switch((int)hRootKey) {
        case HKEY_LOCAL_MACHINE: {
                sRootKey = "HKLM";
            }break;
        case HKEY_CLASSES_ROOT: {
                sRootKey = "HKCR";
            }break;
        case HKEY_USERS: {
                sRootKey = "HKU";
            }break;
        case HKEY_CURRENT_CONFIG: {
                sRootKey = "HKCC";
            }break;
        }
 
        std::auto_ptr<TRegistry>ARegistry(new TRegistry(KEY_ALL_ACCESS));
        // ----корневым каталогом будет hRootKey, который по умолчанию HKEY_CURRENT_USER
        ARegistry->RootKey = hRootKey;
        // ----если ключ существует
        if (ARegistry->KeyExists(sRegistryPath)) {
 
            const UnicodeString sQuotedRegPath = AnsiQuotedStr(IncludeTrailingBackslash(sRootKey) + sRegistryPath, L'"');
            const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
            const UnicodeString sCmdLine = "reg export " + sQuotedRegPath + " " + sQuotedFileName + " /y";
 
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
 
            ZeroMemory(&si, sizeof(si));
            si.cb = sizeof(si);
            si.wShowWindow = SW_HIDE;
            si.dwFlags = STARTF_USESHOWWINDOW;
            ZeroMemory(&pi, sizeof(pi));
 
            // Start the child process.
            if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
                throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
            }
 
            // Wait until child process exits.
            WaitForSingleObject(pi.hProcess, INFINITE);
 
            ULONG uExitCode;
            GetExitCodeProcess(pi.hProcess, &uExitCode);
 
            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
 
            if (uExitCode)
                throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
        }
        else {
            throw Exception("ERROR> Key path <" + sRegistryPath + "> does not exist in root <" + sRootKey + ">");
        }
    }
 
    // импортирует ветку реестра из указанного файла в формате [Windows Registry Editor]
    void ImportKey(const UnicodeString &sFileName) {
 
        const UnicodeString sQuotedFileName = AnsiQuotedStr(sFileName, L'"');
        const UnicodeString sCmdLine = "reg import " + sQuotedFileName;
 
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
 
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);
        si.wShowWindow = SW_HIDE;
        si.dwFlags = STARTF_USESHOWWINDOW;
        ZeroMemory(&pi, sizeof(pi));
 
        // Start the child process.
        if (!CreateProcessW(NULL, sCmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
            throw Exception("ERROR> CreateProcess failed with message <" + SysErrorMessage(GetLastError()) + ">");
 
        }
 
        // Wait until child process exits.
        WaitForSingleObject(pi.hProcess, INFINITE);
 
        ULONG uExitCode;
        GetExitCodeProcess(pi.hProcess, &uExitCode);
 
        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
 
        if (uExitCode)
            throw Exception("ERROR> Failed to execute <" + sCmdLine + ">");
 
    }
};
 
 
//----------nick42
 
BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
 
    if ( !LookupPrivilegeValue(
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() );
        return FALSE;
    }
 
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
 
    // Enable the privilege or disable all privileges.
 
    if ( !AdjustTokenPrivileges(
           hToken,
           FALSE,
           &tp,
           sizeof(TOKEN_PRIVILEGES),
           (PTOKEN_PRIVILEGES) NULL,
           (PDWORD) NULL) )
    {
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
          return FALSE;
    }
 
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
 
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    }
 
    return TRUE;
}
 
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    HANDLE Process;
     if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Process))
     {
         SetPrivilege(Process, SE_RESTORE_NAME, TRUE);
         HKEY key=HKEY_CURRENT_USER;
         RegRestoreKeyA(key, "c:\\saved1.reg", NULL);
}
    ForceDirectories( ".\\App\\reg" );
    AnsiString path = ExtractFilePath(Application->ExeName) + "App\\reg\\save.reg";
    Regutils::ExportKey("Software\\Valve\\Half-Life\\Settings", path, HKEY_CURRENT_USER);
 
    // Удаление ключей
    TRegistry *reg = new TRegistry();
    reg->RootKey = HKEY_CURRENT_USER;
    reg->DeleteKey("Software\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Valve");
    delete reg;
 
    reg = new TRegistry();
    reg->RootKey = HKEY_LOCAL_MACHINE;
    reg->DeleteKey("SOFTWARE\\Wow6432Node\\Valve");
    delete reg;
}
Выдает ошибку при таком условии

Код рабочий но при нажатии на кнопку выдает ошибку или перестает работать когда нет ключа реестра (смотреть скриншот) то есть ошибка

Если нет папки и reg файла выдает ошибку
Если есть папка и reg тоже выдает ошибку


Это можно убрать, чтобы вообще никакого сообщения или ошибки не выдавало ?

P.S При компиляции ошибок нет
Миниатюры
Экспорт реестра в reg файл  
0
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 26
23.02.2015, 18:15  [ТС]
И импорт реестра не работает (Применение reg файла в реестр)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
23.02.2015, 18:15

Изменение ветки реестра (написать reg-файл)
необходимо написать .reg файл, который сможет изменить права у ветки реестра и удалить ветку реестра помогите

Как программно экспортировать ветку реестра в reg файл?
Как программно экспортировать эту ветку реестра в reg файл? HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionProfileList с...

Как программно экспортировать раздел реестра в reg файл?
Программа лезет в реестр в определенное место, читает от туда данные. Если находит лишнее, тогда она экспортирует эту ветку реестра. И...

Экспорт раздела реестра в текстовом формате в файл
Приветствую, бразеры! Кто сталкивался с необходимостью экспортировать раздел реестра в *.txt- файл (по аналогии, если делать...

Экспорт каждого из определённых разделов реестра в отдельный файл
Можно ли средствами cmd экспортировать ключи из ветки &quot;HKEY_CURRENT_USER\Software&quot; при этом каждый подключ поместить в отдельный reg файл? ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
40
Ответ Создать тему
Новые блоги и статьи
[golang] Конкурентный fetcher с ограничением максимального количества одновременных HTTP запросов.
alhaos 10.06.2026
Задача Реализовать конкурентный fetcher с ограничением максимального количества одновременных HTTP запросов. Сигнатура func Fetch(urls string, maxConcurrent int) Result Пример urls :=. . .
[golang] Состояние гонки (race condition)
alhaos 10.06.2026
Состояние гонки (race condition) Состояние гонки (Race Condition) — это ошибка, возникающая при одновременном доступе нескольких горутин к одним и тем же данным без должной синхронизации. При этом. . .
Взрослые отношения, и почему они не получаются
kumehtar 09.06.2026
Когда в детстве ребёнок не получает от родителей чего-то важного, он лишается не просто приятных переживаний, а основы для формирования определённых внутренних качеств и навыков. Если ребёнок не. . .
[golang] Worker Pool
alhaos 09.06.2026
Worker Pool Worker Pool — паттерн конкурентной обработки задач в Go. Суть: фиксированное количество горутин-воркеров читают задачи из общего канала и пишут результаты в общий канал результатов. . . .
[golang] Pipeline
alhaos 08.06.2026
Pipeline Pipeline — паттерн конкурентной обработки данных в Go. Суть: данные проходят через цепочку независимых стадий, каждая из которых работает в своей горутине и общается с соседями через. . .
Свет внутри себя
kumehtar 07.06.2026
Пусть это будет здесь lIs4oanZS9Y
Программа для com-порта
Uhbif79 05.06.2026
Всем привет, давно хотел изучить Qt, начинал, бросал, потом снова начинал. И сейчас вот смог написать свою первую программу. До этого имел опыт программирования микроконтроллеров, писал прошивки на. . .
Транскрипция 55-минутного видео через Whisper: WhisperDesktop облажался, спас Google Colab[
anaschu 01.06.2026
Понадобилось получить текст из свежезагруженного видео на YouTube. Казалось бы, задача на пять минут. Заняла полтора часа. Делюсь опытом — может кому пригодится последовательность решений. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru