|
| 1 | +package winregistry |
| 2 | + |
| 3 | +import ( |
| 4 | + "syscall" |
| 5 | + "unsafe" |
| 6 | + |
| 7 | + "golang.org/x/sys/windows/registry" |
| 8 | +) |
| 9 | + |
| 10 | +var ( |
| 11 | + advapi = syscall.NewLazyDLL("advapi32.dll") |
| 12 | + regCreateKeyExW = advapi.NewProc("RegCreateKeyExW") |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + // Registry key options |
| 17 | + regOptionNonVolatile = 0x0 // Key is preserved when system is rebooted |
| 18 | + regOptionVolatile = 0x1 // Key is not preserved when system is rebooted |
| 19 | + |
| 20 | + // Registry disposition values |
| 21 | + regCreatedNewKey = 0x1 |
| 22 | + regOpenedExistingKey = 0x2 |
| 23 | +) |
| 24 | + |
| 25 | +// CreateVolatileKey creates a volatile registry key named path under open key root. |
| 26 | +// CreateVolatileKey returns the new key and a boolean flag that reports whether the key already existed. |
| 27 | +// The access parameter specifies the access rights for the key to be created. |
| 28 | +// |
| 29 | +// Volatile keys are stored in memory and are automatically deleted when the system is shut down. |
| 30 | +// This provides automatic cleanup without requiring manual registry maintenance. |
| 31 | +func CreateVolatileKey(root registry.Key, path string, access uint32) (registry.Key, bool, error) { |
| 32 | + pathPtr, err := syscall.UTF16PtrFromString(path) |
| 33 | + if err != nil { |
| 34 | + return 0, false, err |
| 35 | + } |
| 36 | + |
| 37 | + var ( |
| 38 | + handle syscall.Handle |
| 39 | + disposition uint32 |
| 40 | + ) |
| 41 | + |
| 42 | + ret, _, _ := regCreateKeyExW.Call( |
| 43 | + uintptr(root), |
| 44 | + uintptr(unsafe.Pointer(pathPtr)), |
| 45 | + 0, // reserved |
| 46 | + 0, // class |
| 47 | + uintptr(regOptionVolatile), // options - volatile key |
| 48 | + uintptr(access), // desired access |
| 49 | + 0, // security attributes |
| 50 | + uintptr(unsafe.Pointer(&handle)), |
| 51 | + uintptr(unsafe.Pointer(&disposition)), |
| 52 | + ) |
| 53 | + |
| 54 | + if ret != 0 { |
| 55 | + return 0, false, syscall.Errno(ret) |
| 56 | + } |
| 57 | + |
| 58 | + return registry.Key(handle), disposition == regOpenedExistingKey, nil |
| 59 | +} |
0 commit comments