Java wrapper for Windows registry API RegDeleteKey() - Java Native OS

Java examples for Native OS:Windows

Description

Java wrapper for Windows registry API RegDeleteKey()

Demo Code


//package com.java2s;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.prefs.Preferences;

public class Main {
    /**// w  ww. ja  va  2  s.  co  m
     * Error because acces to the specified key was denied
     */
    public static final int ERROR_ACCESS_DENIED = 5;
    private static final Preferences systemRoot = Preferences.systemRoot();
    private static Method windowsRegDeleteKey = null;

    /**
     * Java wrapper for Windows registry API RegDeleteKey()
     * 
     * @param hKey
     *            The Native Handle to a Key
     * @param subKey
     *            The sub key to be deleted as a byte array
     * @return The Error Code
     */
    public static int RegDeleteKey(int hKey, byte[] subKey) {
        try {
            return ((Integer) windowsRegDeleteKey.invoke(systemRoot,
                    new Object[] { new Integer(hKey), subKey })).intValue();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ERROR_ACCESS_DENIED;
    }

    /**
     * Java wrapper for Windows registry API RegDeleteKey()
     * 
     * @param hKey
     *            The Native Handle to a Key
     * @param subKey
     *            The sub key to be deleted
     * @return The Error Code
     */
    public static int RegDeleteKey(int hKey, String subKey) {
        return RegDeleteKey(hKey, stringToByteArray(subKey));

    }

    /**
     * Returns this java string as a null-terminated byte array
     */
    public static byte[] stringToByteArray(String str) {
        byte[] result = new byte[str.length() + 1];
        for (int i = 0; i < str.length(); i++) {
            result[i] = (byte) str.charAt(i);
        }
        result[str.length()] = 0;
        return result;
    }
}

Related Tutorials