github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/osext/winsvc/registry/registry.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package registry provides access to Windows registry.
     6  //
     7  package registry
     8  
     9  import (
    10  	"chai2010.gopkg/osext/winsvc/winapi"
    11  	"syscall"
    12  	"unsafe"
    13  )
    14  
    15  type Key struct {
    16  	Handle syscall.Handle
    17  }
    18  
    19  func OpenKey(parent syscall.Handle, path string) (*Key, error) {
    20  	var h syscall.Handle
    21  	e := syscall.RegOpenKeyEx(
    22  		parent, syscall.StringToUTF16Ptr(path),
    23  		0, syscall.KEY_ALL_ACCESS, &h)
    24  	if e != nil {
    25  		return nil, e
    26  	}
    27  	return &Key{Handle: h}, nil
    28  }
    29  
    30  func (k *Key) Close() error {
    31  	return syscall.RegCloseKey(k.Handle)
    32  }
    33  
    34  func (k *Key) CreateSubKey(name string) (nk *Key, openedExisting bool, err error) {
    35  	var h syscall.Handle
    36  	var d uint32
    37  	e := winapi.RegCreateKeyEx(
    38  		k.Handle, syscall.StringToUTF16Ptr(name),
    39  		0, nil, winapi.REG_OPTION_NON_VOLATILE,
    40  		syscall.KEY_ALL_ACCESS, nil, &h, &d)
    41  	if e != nil {
    42  		return nil, false, e
    43  	}
    44  	return &Key{Handle: h}, d == winapi.REG_OPENED_EXISTING_KEY, nil
    45  }
    46  
    47  func (k *Key) DeleteSubKey(name string) error {
    48  	return winapi.RegDeleteKey(k.Handle, syscall.StringToUTF16Ptr(name))
    49  }
    50  
    51  func (k *Key) SetUInt32(name string, value uint32) error {
    52  	return winapi.RegSetValueEx(
    53  		k.Handle, syscall.StringToUTF16Ptr(name),
    54  		0, syscall.REG_DWORD,
    55  		(*byte)(unsafe.Pointer(&value)), uint32(unsafe.Sizeof(value)))
    56  }
    57  
    58  func (k *Key) SetString(name string, value string) error {
    59  	buf := syscall.StringToUTF16(value)
    60  	return winapi.RegSetValueEx(
    61  		k.Handle, syscall.StringToUTF16Ptr(name),
    62  		0, syscall.REG_SZ,
    63  		(*byte)(unsafe.Pointer(&buf[0])), uint32(len(buf)*2))
    64  }