MCPcopy Create free account
hub / github.com/AutoHotkey/AutoHotkey / RegWrite

Function RegWrite

source/script_registry.cpp:351–489  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

349
350
351void RegWrite(ResultToken &aResultToken, ExprTokenType &aValue, DWORD aValueType, HKEY aRootKey, LPTSTR aRegSubkey, LPTSTR aValueName)
352// If aValueName is the empty string, the key's default value is used.
353{
354 HKEY hRegKey;
355 DWORD dwRes, dwBuf;
356
357 TCHAR nbuf[MAX_NUMBER_SIZE];
358 LPTSTR value;
359 size_t length;
360
361 LONG result;
362
363 if (aValueType == REG_NONE)
364 _f_throw_value(ERR_PARAM2_MUST_NOT_BE_BLANK);
365
366 if (aValueType != REG_DWORD)
367 value = TokenToString(aValue, nbuf, &length);
368
369 // Open/Create the registry key
370 // The following works even on root keys (i.e. blank subkey), although values can't be created/written to
371 // HKCU's root level, perhaps because it's an alias for a subkey inside HKEY_USERS. Even when RegOpenKeyEx()
372 // is used on HKCU (which is probably redundant since it's a pre-opened key?), the API can't create values
373 // there even though RegEdit can.
374 result = RegCreateKeyEx(aRootKey, aRegSubkey, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_WRITE | g->RegView, NULL, &hRegKey, &dwRes);
375 if (result != ERROR_SUCCESS)
376 goto finish;
377
378 // Write the registry differently depending on type of variable we are writing
379 switch (aValueType)
380 {
381 case REG_SZ:
382 result = RegSetValueEx(hRegKey, aValueName, 0, REG_SZ, (CONST BYTE *)value, (DWORD)(length+1) * sizeof(TCHAR));
383 break;
384
385 case REG_EXPAND_SZ:
386 result = RegSetValueEx(hRegKey, aValueName, 0, REG_EXPAND_SZ, (CONST BYTE *)value, (DWORD)(length+1) * sizeof(TCHAR));
387 break;
388
389 case REG_MULTI_SZ:
390 {
391 // Allocate some temporary memory because aValue might not be a writable string,
392 // and we would need to write to it to temporarily change the newline delimiters into
393 // zero-delimiters. Even if we were to require callers to give us a modifiable string,
394 // its capacity may be 1 byte too small to handle the double termination that's needed
395 // (i.e. if the last item in the list happens to not end in a newline):
396 LPTSTR buf = tmalloc(length + 2);
397 if (!buf)
398 {
399 result = ERROR_OUTOFMEMORY;
400 break;
401 }
402 tcslcpy(buf, value, length + 1);
403 // Double-terminate:
404 buf[length + 1] = '\0';
405
406 // Remove any final newline the user may have provided since we don't want the length
407 // to include it when calling RegSetValueEx() -- it would be too large by 1:
408 if (length > 0 && buf[length - 1] == '\n')

Callers 1

BIF_DECLFunction · 0.85

Calls 2

TokenToStringFunction · 0.85
TokenToInt64Function · 0.85

Tested by

no test coverage detected