com.sun.jna.platform.win32

## Class Kernel32Util

- java.lang.Object
- - com.sun.jna.platform.win32.Kernel32Util

- All Implemented Interfaces:
    WinDef

      public abstract class Kernel32Util
      extends java.lang.Object
      implements WinDef

  Kernel32 utility API.
  Author:
    dblock[at]dblock.org, markus[at]headcrashing[dot]eu, Andreas "PAX" Lück, onkelpax-git[at]yahoo.de

- - ### Nested Class Summary

    - ### Nested classes/interfaces inherited from interface com.sun.jna.platform.win32.WinDef

      `WinDef.ATOM, WinDef.BOOL, WinDef.BOOLByReference, WinDef.BYTE, WinDef.CHAR, WinDef.CHARByReference, WinDef.DWORD, WinDef.DWORDByReference, WinDef.DWORDLONG, WinDef.HBITMAP, WinDef.HBRUSH, WinDef.HCURSOR, WinDef.HDC, WinDef.HFONT, WinDef.HGLRC, WinDef.HGLRCByReference, WinDef.HICON, WinDef.HINSTANCE, WinDef.HMENU, WinDef.HMODULE, WinDef.HPALETTE, WinDef.HPEN, WinDef.HRGN, WinDef.HRSRC, WinDef.HWND, WinDef.INT_PTR, WinDef.LCID, WinDef.LONG, WinDef.LONGByReference, WinDef.LONGLONG, WinDef.LONGLONGByReference, WinDef.LPARAM, WinDef.LPVOID, WinDef.LRESULT, WinDef.POINT, WinDef.PVOID, WinDef.RECT, WinDef.SCODE, WinDef.SCODEByReference, WinDef.SHORT, WinDef.UCHAR, WinDef.UINT, WinDef.UINT_PTR, WinDef.UINTByReference, WinDef.ULONG, WinDef.ULONGByReference, WinDef.ULONGLONG, WinDef.ULONGLONGByReference, WinDef.USHORT, WinDef.USHORTByReference, WinDef.WORD, WinDef.WORDByReference, WinDef.WPARAM`

  - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `static java.lang.String` | `VOLUME_GUID_PATH_PREFIX`
    `static java.lang.String` | `VOLUME_GUID_PATH_SUFFIX`

    - ### Fields inherited from interface com.sun.jna.platform.win32.WinDef

      `MAX_PATH`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `Kernel32Util()`

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `static void` | `closeHandle(WinNT.HANDLE h)` Invokes `Kernel32.CloseHandle(WinNT.HANDLE)` and checks the success code.
    `static void` | `closeHandleRef(WinNT.HANDLEByReference ref)` Closes the handle in the reference
    `static void` | `closeHandleRefs(WinNT.HANDLEByReference... refs)` Closes all referenced handles.
    `static void` | `closeHandles(WinNT.HANDLE... handles)` Invokes `closeHandle(WinNT.HANDLE)` on each handle.
    `static void` | `deleteFile(java.lang.String filename)`
    `static java.lang.String` | `extractVolumeGUID(java.lang.String volumeGUIDPath)` Parses and returns the pure GUID value of a volume name obtained from `Kernel32.FindFirstVolume(char[], int)` or `Kernel32.FindNextVolume(com.sun.jna.platform.win32.WinNT.HANDLE, char[], int)` calls
    `static long` | `findEnvironmentStringBlockEntryEnd(Pointer lpszEnvironmentBlock, long offset, boolean asWideChars)`
    `static java.lang.String` | `formatMessage(int code)` Format a message from the value obtained from `Kernel32.GetLastError()` or `Native.getLastError()`.
    `static java.lang.String` | `formatMessage(WinNT.HRESULT code)` Format a message from an HRESULT.
    `static java.lang.String` | `formatMessageFromHR(WinNT.HRESULT code)` Deprecated. use `formatMessage(WinNT.HRESULT)` instead.
    `static java.lang.String` | `formatMessageFromLastErrorCode(int code)` Format a system message from an error code.
    `static void` | `freeGlobalMemory(Pointer ptr)` Invokes `Kernel32.GlobalFree(Pointer)` and checks if it succeeded.
    `static void` | `freeLocalMemory(Pointer ptr)` Invokes `Kernel32.LocalFree(Pointer)` and checks if it succeeded.
    `static java.lang.String` | `getComputerName()` Get current computer NetBIOS name.
    `static int` | `getDriveType(java.lang.String rootName)`
    `static java.lang.String` | `getEnvironmentVariable(java.lang.String name)` Get the value of an environment variable.
    `static java.util.Map<java.lang.String,java.lang.String>` | `getEnvironmentVariables()` Uses the `Kernel32.GetEnvironmentStrings()` to retrieve and parse the current process environment
    `static java.util.Map<java.lang.String,java.lang.String>` | `getEnvironmentVariables(Pointer lpszEnvironmentBlock, long offset)`
    `static int` | `getFileAttributes(java.lang.String fileName)` Retrieves file system attributes for a specified file or directory.
    `static int` | `getFileType(java.lang.String fileName)` Retrieves the result of GetFileType, provided the file exists.
    `static java.lang.String` | `getLastErrorMessage()`
    `static java.util.List<java.lang.String>` | `getLogicalDriveStrings()` Returns valid drives in the system.
    `static WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION[]` | `getLogicalProcessorInformation()` Convenience method to get the processor information.
    `static java.util.List<Tlhelp32.MODULEENTRY32W>` | `getModules(int processID)` Returns all the executable modules for a given process ID.
    `static int` | `getPrivateProfileInt(java.lang.String appName, java.lang.String keyName, int defaultValue, java.lang.String fileName)` Retrieves an integer associated with a key in the specified section of an initialization file.
    `static java.lang.String[]` | `getPrivateProfileSection(java.lang.String appName, java.lang.String fileName)` Retrieves all the keys and values for the specified section of an initialization file.
    `static java.lang.String[]` | `getPrivateProfileSectionNames(java.lang.String fileName)` Retrieves the names of all sections in an initialization file.
    `static java.lang.String` | `getPrivateProfileString(java.lang.String lpAppName, java.lang.String lpKeyName, java.lang.String lpDefault, java.lang.String lpFileName)` Retrieves a string from the specified section in an initialization file.
    `static byte[]` | `getResource(java.lang.String path, java.lang.String type, java.lang.String name)` Gets the specified resource out of the specified executable file
    `static java.util.Map<java.lang.String,java.util.List<java.lang.String>>` | `getResourceNames(java.lang.String path)` Gets a list of all resources from the specified executable file
    `static java.lang.String` | `getTempPath()` Return the path designated for temporary files.
    `static java.util.List<java.lang.String>` | `getVolumePathNamesForVolumeName(java.lang.String lpszVolumeName)` Invokes and parses the result of `Kernel32.GetVolumePathNamesForVolumeName(String, char[], int, IntByReference)`
    `static boolean` | `isWideCharEnvironmentStringBlock(Pointer lpszEnvironmentBlock, long offset)` Attempts to determine whether the data block uses `wchar_t` instead of "plain old" `char`s.
    `static java.util.List<java.lang.String>` | `queryDosDevice(java.lang.String lpszDeviceName, int maxTargetSize)` Invokes the `Kernel32.QueryDosDevice(String, char[], int)` method and parses the result
    `static java.lang.String` | `QueryFullProcessImageName(WinNT.HANDLE hProcess, int dwFlags)` This function retrieves the full path of the executable file of a given process.
    `static java.lang.String` | `readEnvironmentStringBlockEntry(Pointer lpszEnvironmentBlock, long offset, boolean asWideChars)`
    `static void` | `writePrivateProfileSection(java.lang.String appName, java.lang.String[] strings, java.lang.String fileName)`
    `static void` | `writePrivateProfileString(java.lang.String appName, java.lang.String keyName, java.lang.String string, java.lang.String fileName)`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### VOLUME_GUID_PATH_PREFIX

          public static final java.lang.String VOLUME_GUID_PATH_PREFIX

      See Also:
        Constant Field Values

    - #### VOLUME_GUID_PATH_SUFFIX

          public static final java.lang.String VOLUME_GUID_PATH_SUFFIX

      See Also:
        Constant Field Values

  - ### Constructor Detail

    - #### Kernel32Util

          public Kernel32Util()

  - ### Method Detail

    - #### getComputerName

          public static java.lang.String getComputerName()

      Get current computer NetBIOS name.
      Returns:
        Netbios name.

    - #### freeLocalMemory

          public static void freeLocalMemory(Pointer ptr)

      Invokes `Kernel32.LocalFree(Pointer)` and checks if it succeeded.
      Parameters:
        `ptr` - The `Pointer` to the memory to be released - ignored if NULL
      Throws:
        `Win32Exception` - if non-`ERROR_SUCCESS` code reported

    - #### freeGlobalMemory

          public static void freeGlobalMemory(Pointer ptr)

      Invokes `Kernel32.GlobalFree(Pointer)` and checks if it succeeded.
      Parameters:
        `ptr` - The `Pointer` to the memory to be released - ignored if NULL
      Throws:
        `Win32Exception` - if non-`ERROR_SUCCESS` code reported

    - #### closeHandleRefs

          public static void closeHandleRefs(WinNT.HANDLEByReference... refs)

      Closes all referenced handles. If an exception is thrown for a specific handle, then it is accumulated until all handles have been closed. If more than one exception occurs, then it is added as a suppressed exception to the first one. Once closed all handles, the accumulated exception (if any) is thrown
      Parameters:
        `refs` - The references to close
      See Also:
        `closeHandleRef(WinNT.HANDLEByReference)`

    - #### closeHandleRef

          public static void closeHandleRef(WinNT.HANDLEByReference ref)

      Closes the handle in the reference
      Parameters:
        `ref` - The handle reference - ignored if `null`
      See Also:
        `closeHandle(WinNT.HANDLE)`

    - #### closeHandles

          public static void closeHandles(WinNT.HANDLE... handles)

      Invokes `closeHandle(WinNT.HANDLE)` on each handle. If an exception is thrown for a specific handle, then it is accumulated until all handles have been closed. If more than one exception occurs, then it is added as a suppressed exception to the first one. Once closed all handles, the accumulated exception (if any) is thrown
      Parameters:
        `handles` - The handles to be closed
      See Also:
        `Throwable.getSuppressed()`

    - #### closeHandle

          public static void closeHandle(WinNT.HANDLE h)

      Invokes `Kernel32.CloseHandle(WinNT.HANDLE)` and checks the success code. If not successful, then throws a `Win32Exception` with the `GetLastError` value
      Parameters:
        `h` - The handle to be closed - ignored if `null`

    - #### formatMessage

          public static java.lang.String formatMessage(int code)

      Format a message from the value obtained from `Kernel32.GetLastError()` or `Native.getLastError()`.
      Parameters:
        `code` - The error code
      Returns:
        Formatted message.

    - #### formatMessage

          public static java.lang.String formatMessage(WinNT.HRESULT code)

      Format a message from an HRESULT.
      Parameters:
        `code` - HRESULT
      Returns:
        Formatted message.

    - #### formatMessageFromHR

          @Deprecated
          public static java.lang.String formatMessageFromHR(WinNT.HRESULT code)

      Deprecated. use `formatMessage(WinNT.HRESULT)` instead.
      Parameters:
        `code` - error code
      Returns:
        formatted message

    - #### formatMessageFromLastErrorCode

          public static java.lang.String formatMessageFromLastErrorCode(int code)

      Format a system message from an error code.
      Parameters:
        `code` - Error code, typically a result of GetLastError.
      Returns:
        Formatted message.

    - #### getLastErrorMessage

          public static java.lang.String getLastErrorMessage()

      Returns:
        Obtains the human-readable error message text from the last error that occurred by invocating `Kernel32.GetLastError()`.

    - #### getTempPath

          public static java.lang.String getTempPath()

      Return the path designated for temporary files.
      Returns:
        Path.

    - #### deleteFile

          public static void deleteFile(java.lang.String filename)

    - #### getLogicalDriveStrings

          public static java.util.List<java.lang.String> getLogicalDriveStrings()

      Returns valid drives in the system.
      Returns:
        A `List` of valid drives.

    - #### getFileAttributes

          public static int getFileAttributes(java.lang.String fileName)

      Retrieves file system attributes for a specified file or directory.
      Parameters:
        `fileName` - The name of the file or directory.
      Returns:
        The attributes of the specified file or directory.

    - #### getFileType

          public static int getFileType(java.lang.String fileName)
                                 throws java.io.FileNotFoundException

      Retrieves the result of GetFileType, provided the file exists.
      Parameters:
        `fileName` - file name
      Returns:
        file type
      Throws:
        `java.io.FileNotFoundException` - if file not found

    - #### getDriveType

          public static int getDriveType(java.lang.String rootName)

      Parameters:
        `rootName` - name of root drive
      Returns:
        One of the WinBase.DRIVE_* constants.

    - #### getEnvironmentVariable

          public static java.lang.String getEnvironmentVariable(java.lang.String name)

      Get the value of an environment variable.
      Parameters:
        `name` - Name of the environment variable.
      Returns:
        Value of an environment variable.

    - #### getEnvironmentVariables

          public static java.util.Map<java.lang.String,java.lang.String> getEnvironmentVariables()

      Uses the `Kernel32.GetEnvironmentStrings()` to retrieve and parse the current process environment
      Returns:
        The current process environment as a `Map`.
      Throws:
        `LastErrorException` - if failed to get or free the environment data block
      See Also:
        `getEnvironmentVariables(Pointer, long)`

    - #### getEnvironmentVariables

          public static java.util.Map<java.lang.String,java.lang.String> getEnvironmentVariables(Pointer lpszEnvironmentBlock,
                                                                                 long offset)

      Parameters:
        `lpszEnvironmentBlock` - The environment block as received from the GetEnvironmentStrings function
        `offset` - Offset within the block to parse the data
      Returns:
        A `Map` of the parsed `name=value` pairs. Note: if the environment block is `null` then `null` is returned instead of an empty map since we want to distinguish between the case that the data block is `null` and when there are no environment variables (as unlikely as it may be)

    - #### readEnvironmentStringBlockEntry

          public static java.lang.String readEnvironmentStringBlockEntry(Pointer lpszEnvironmentBlock,
                                                         long offset,
                                                         boolean asWideChars)

      Parameters:
        `lpszEnvironmentBlock` - The environment block as received from the GetEnvironmentStrings function
        `offset` - Offset within the block to look for the entry
        `asWideChars` - If `true` then the block contains `wchar_t` instead of "plain old" `char`s
      Returns:
        A `String` containing the `name=value` pair or empty if reached end of block
      See Also:
        `isWideCharEnvironmentStringBlock(com.sun.jna.Pointer, long)`, `findEnvironmentStringBlockEntryEnd(com.sun.jna.Pointer, long, boolean)`

    - #### findEnvironmentStringBlockEntryEnd

          public static long findEnvironmentStringBlockEntryEnd(Pointer lpszEnvironmentBlock,
                                                long offset,
                                                boolean asWideChars)

      Parameters:
        `lpszEnvironmentBlock` - The environment block as received from the GetEnvironmentStrings function
        `offset` - Offset within the block to look for the entry
        `asWideChars` - If `true` then the block contains `wchar_t` instead of "plain old" `char`s
      Returns:
        The offset of the first `'\0'` in the data block starting at the specified offset - can be the start offset itself if empty string.
      See Also:
        `isWideCharEnvironmentStringBlock(com.sun.jna.Pointer, long)`

    - #### isWideCharEnvironmentStringBlock

          public static boolean isWideCharEnvironmentStringBlock(Pointer lpszEnvironmentBlock,
                                                 long offset)

      Attempts to determine whether the data block uses `wchar_t` instead of "plain old" `char`s. It does that by reading 2 bytes from the specified offset - the character value and its charset indicator - and examining them as follows:

      - If the charset indicator is non-zero then it is assumed to be a "plain old" `char`s data block. Note: the assumption is that the environment variable name (at least) is ASCII.
      - Otherwise (i.e., zero charset indicator), it is assumed to be a `wchar_t`
      Note: the code takes into account the `ByteOrder` even though only `ByteOrder.LITTLE_ENDIAN` is the likely one
      Parameters:
        `lpszEnvironmentBlock` - The environment block as received from the GetEnvironmentStrings function
        `offset` - offset
      Returns:
        `true` if the block contains `wchar_t` instead of "plain old" `char`s

    - #### getPrivateProfileInt

          public static final int getPrivateProfileInt(java.lang.String appName,
                                 java.lang.String keyName,
                                 int defaultValue,
                                 java.lang.String fileName)

      Retrieves an integer associated with a key in the specified section of an initialization file.
      Parameters:
        `appName` - The name of the section in the initialization file.
        `keyName` - The name of the key whose value is to be retrieved. This value is in the form of a string; the `Kernel32.GetPrivateProfileInt(java.lang.String, java.lang.String, int, java.lang.String)` function converts the string into an integer and returns the integer.
        `defaultValue` - The default value to return if the key name cannot be found in the initialization file.
        `fileName` - The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
      Returns:
        The retrieved integer, or the default if not found.

    - #### getPrivateProfileString

          public static final java.lang.String getPrivateProfileString(java.lang.String lpAppName,
                                                 java.lang.String lpKeyName,
                                                 java.lang.String lpDefault,
                                                 java.lang.String lpFileName)

      Retrieves a string from the specified section in an initialization file.
      Parameters:
        `lpAppName` - The name of the section containing the key name. If this parameter is `null`, the `Kernel32.GetPrivateProfileString(java.lang.String, java.lang.String, java.lang.String, char[], com.sun.jna.platform.win32.WinDef.DWORD, java.lang.String)` function copies all section names in the file to the supplied buffer.
        `lpKeyName` - The name of the key whose associated string is to be retrieved. If this parameter is `null`, all key names in the section specified by the `lpAppName` parameter are returned.
        `lpDefault` - A default string. If the `lpKeyName` key cannot be found in the initialization file, `Kernel32.GetPrivateProfileString(java.lang.String, java.lang.String, java.lang.String, char[], com.sun.jna.platform.win32.WinDef.DWORD, java.lang.String)` returns the default. If this parameter is `null`, the default is an empty string, `""`.

        Avoid specifying a default string with trailing blank characters. The function inserts a `null` character in the `lpReturnedString` buffer to strip any trailing blanks.

        `lpFileName` - The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
      Returns:

        If neither `lpAppName` nor `lpKeyName` is `null` and the destination buffer is too small to hold the requested string, the string is truncated.

        If either `lpAppName` or `lpKeyName` is `null` and the destination buffer is too small to hold all the strings, the last string is truncated and followed by two `null` characters.

        In the event the initialization file specified by `lpFileName` is not found, or contains invalid values, this function will set errorno with a value of '0x2' (File Not Found). To retrieve extended error information, call `Kernel32.GetLastError()`.

    - #### writePrivateProfileString

          public static final void writePrivateProfileString(java.lang.String appName,
                                       java.lang.String keyName,
                                       java.lang.String string,
                                       java.lang.String fileName)

    - #### getLogicalProcessorInformation

          public static final WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION[] getLogicalProcessorInformation()

      Convenience method to get the processor information. Takes care of auto-growing the array.
      Returns:
        the array of processor information.

    - #### getPrivateProfileSection

          public static final java.lang.String[] getPrivateProfileSection(java.lang.String appName,
                                                    java.lang.String fileName)

      Retrieves all the keys and values for the specified section of an initialization file.

      Each string has the following format: `key=string`.

      This operation is atomic; no updates to the specified initialization file are allowed while this method is executed.

      Parameters:
        `appName` - The name of the section in the initialization file.
        `fileName` - The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
      Returns:
        The key name and value pairs associated with the named section.

    - #### getPrivateProfileSectionNames

          public static final java.lang.String[] getPrivateProfileSectionNames(java.lang.String fileName)

      Retrieves the names of all sections in an initialization file.

      This operation is atomic; no updates to the initialization file are allowed while this method is executed.

      Parameters:
        `fileName` - The name of the initialization file. If this parameter is `NULL`, the function searches the Win.ini file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
      Returns:
        the section names associated with the named file.

    - #### writePrivateProfileSection

          public static final void writePrivateProfileSection(java.lang.String appName,
                                        java.lang.String[] strings,
                                        java.lang.String fileName)

      Parameters:
        `appName` - The name of the section in which data is written. This section name is typically the name of the calling application.
        `strings` - The new key names and associated values that are to be written to the named section. Each entry must be of the form `key=value`.
        `fileName` - The name of the initialization file. If this parameter does not contain a full path for the file, the function searches the Windows directory for the file. If the file does not exist and lpFileName does not contain a full path, the function creates the file in the Windows directory.

    - #### queryDosDevice

          public static final java.util.List<java.lang.String> queryDosDevice(java.lang.String lpszDeviceName,
                                                        int maxTargetSize)

      Invokes the `Kernel32.QueryDosDevice(String, char[], int)` method and parses the result
      Parameters:
        `lpszDeviceName` - The device name
        `maxTargetSize` - The work buffer size to use for the query
      Returns:
        The parsed result

    - #### getVolumePathNamesForVolumeName

          public static final java.util.List<java.lang.String> getVolumePathNamesForVolumeName(java.lang.String lpszVolumeName)

      Invokes and parses the result of `Kernel32.GetVolumePathNamesForVolumeName(String, char[], int, IntByReference)`
      Parameters:
        `lpszVolumeName` - The volume name
      Returns:
        The parsed result
      Throws:
        `Win32Exception` - If failed to retrieve the required information

    - #### extractVolumeGUID

          public static final java.lang.String extractVolumeGUID(java.lang.String volumeGUIDPath)

      Parses and returns the pure GUID value of a volume name obtained from `Kernel32.FindFirstVolume(char[], int)` or `Kernel32.FindNextVolume(com.sun.jna.platform.win32.WinNT.HANDLE, char[], int)` calls
      Parameters:
        `volumeGUIDPath` - The volume GUID path as returned by one of the above mentioned calls
      Returns:
        The pure GUID value after stripping the "\\?\" prefix and removing the trailing backslash.
      Throws:
        `java.lang.IllegalArgumentException` - if bad format encountered
      See Also:
        Naming a Volume

    - #### QueryFullProcessImageName

          public static final java.lang.String QueryFullProcessImageName(WinNT.HANDLE hProcess,
                                                   int dwFlags)

      This function retrieves the full path of the executable file of a given process.
      Parameters:
        `hProcess` - Handle for the running process
        `dwFlags` - 0 - The name should use the Win32 path format. 1(WinNT.PROCESS_NAME_NATIVE) - The name should use the native system path format.
      Returns:
        the full path of the process's executable file of null if failed. To get extended error information, call GetLastError.

    - #### getResource

          public static byte[] getResource(java.lang.String path,
                           java.lang.String type,
                           java.lang.String name)

      Gets the specified resource out of the specified executable file
      Parameters:
        `path` - The path to the executable file
        `type` - The type of the resource (either a type name or type ID is allowed)
        `name` - The name or ID of the resource
      Returns:
        The resource bytes, or null if no such resource exists.
      Throws:
        `java.lang.IllegalStateException` - if the call to LockResource fails

    - #### getResourceNames

          public static java.util.Map<java.lang.String,java.util.List<java.lang.String>> getResourceNames(java.lang.String path)

      Gets a list of all resources from the specified executable file
      Parameters:
        `path` - The path to the executable file
      Returns:
        A map of resource type name/ID => resources.
        A map key + a single list item + the path to the executable can be handed off to getResource() to actually get the resource.

    - #### getModules

          public static java.util.List<Tlhelp32.MODULEENTRY32W> getModules(int processID)

      Returns all the executable modules for a given process ID.
      Parameters:
        `processID` - The process ID to get executable modules for
      Returns:
        All the modules in the process.

Copyright © 2007-2016 Timothy Wall. All Rights Reserved.