Search code examples
javaregistryjna

Unable to correctly write REG_DWORD into registry


The problem is with writing REG_DWORD param value using JNA lib.

My code is:

public static int setKeyValue(WinReg.HKEY hkey, String path, String name, String value) {

    int code;
    int type = getKeyType(hkey, path, name);
    char[] data = value.toCharArray();

    WinReg.HKEYByReference readKey = new WinReg.HKEYByReference();
    code = Advapi32.INSTANCE.RegOpenKeyEx(hkey, path, 0, WinNT.KEY_READ | WinNT.KEY_WRITE, readKey);

    if (code != WinError.ERROR_SUCCESS) {
        throw new Win32Exception(code);
    }

    if (!valueExists(hkey, path, name)) {
        return -2;
    }

    try {
        code = Advapi32.INSTANCE.RegSetValueEx(readKey.getValue(), name, 0, type, data, data.length * 2);
        if (code == WinNT.ERROR_SUCCESS) return 0;
    } finally {
        code = Advapi32.INSTANCE.RegCloseKey(readKey.getValue());
        if (code != W32Errors.ERROR_SUCCESS) throw new Win32Exception(code);
    }

    return -1;
}

So, there are no problems with REG_SZ variables, but when I'm trying to write into REG_DWORD the msg in regedit.exe is: Invalid parameter DWORD(32 bit)

I'm using Java 8, JNA 4.2.1 lib. Any help pls.


Solution

  • Length for REG_DWORD must be fixed = 4;

    switch (type) {
            case WinNT.REG_DWORD :
                data = Character.toChars(Integer.parseInt(value));
                dataLength = 4;
                break;
    
            case WinNT.REG_SZ :
                dataLength *= 2;
                break;
    
            default: break;
        }