Class Kernel32Util
- All Implemented Interfaces:
- WinDef
- Author:
- dblock[at]dblock.org, markus[at]headcrashing[dot]eu, Andreas "PAX" Lück, onkelpax-git[at]yahoo.de
- 
Nested Class SummaryNested classes/interfaces inherited from interface com.sun.jna.platform.win32.WinDefWinDef.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.HKL, 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 SummaryFields
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionstatic voidInvokesKernel32.CloseHandle(WinNT.HANDLE)and checks the success code.static voidCloses the handle in the referencestatic voidcloseHandleRefs(WinNT.HANDLEByReference... refs) Closes all referenced handles.static voidcloseHandles(WinNT.HANDLE... handles) InvokescloseHandle(WinNT.HANDLE)on each handle.static voiddeleteFile(String filename) static StringexpandEnvironmentStrings(String input) Expands environment-variable strings and replaces them with the values defined for the current user.static final StringextractVolumeGUID(String volumeGUIDPath) Parses and returns the pure GUID value of a volume name obtained fromKernel32.FindFirstVolume(char[], int)orKernel32.FindNextVolume(com.sun.jna.platform.win32.WinNT.HANDLE, char[], int)callsstatic longfindEnvironmentStringBlockEntryEnd(Pointer lpszEnvironmentBlock, long offset, boolean asWideChars) static StringformatMessage(int code) Format a message from a code.static StringformatMessage(int code, int primaryLangId, int sublangId) Format a message from the value obtained fromKernel32.GetLastError()orNative.getLastError().static StringformatMessage(WinNT.HRESULT code) Format a message from an HRESULT.static StringformatMessage(WinNT.HRESULT code, int primaryLangId, int sublangId) Format a message from an HRESULT.static StringformatMessageFromLastErrorCode(int code) Format a system message from an error code.static StringformatMessageFromLastErrorCode(int code, int primaryLangId, int sublangId) Format a system message from an error code.static voidfreeGlobalMemory(Pointer ptr) InvokesKernel32.GlobalFree(Pointer)and checks if it succeeded.static voidfreeLocalMemory(Pointer ptr) InvokesKernel32.LocalFree(Pointer)and checks if it succeeded.static StringGet current computer NetBIOS name.static intgetDriveType(String rootName) static StringgetEnvironmentVariable(String name) Get the value of an environment variable.Uses theKernel32.GetEnvironmentStrings()to retrieve and parse the current process environmentgetEnvironmentVariables(Pointer lpszEnvironmentBlock, long offset) static intgetFileAttributes(String fileName) Retrieves file system attributes for a specified file or directory.static intgetFileType(String fileName) Retrieves the result of GetFileType, provided the file exists.static Stringstatic StringgetLastErrorMessage(int primaryLangId, int sublangId) Returns valid drives in the system.static final WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION[]Convenience method to get the processor information.static final WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX[]getLogicalProcessorInformationEx(int relationshipType) Convenience method to get the processor information.static List<Tlhelp32.MODULEENTRY32W>getModules(int processID) Returns all the executable modules for a given process ID.static final intgetPrivateProfileInt(String appName, String keyName, int defaultValue, String fileName) Retrieves an integer associated with a key in the specified section of an initialization file.static final String[]getPrivateProfileSection(String appName, String fileName) Retrieves all the keys and values for the specified section of an initialization file.static final String[]getPrivateProfileSectionNames(String fileName) Retrieves the names of all sections in an initialization file.static final StringgetPrivateProfileString(String lpAppName, String lpKeyName, String lpDefault, String lpFileName) Retrieves a string from the specified section in an initialization file.static byte[]getResource(String path, String type, String name) Gets the specified resource out of the specified executable filegetResourceNames(String path) Gets a list of all resources from the specified executable filestatic StringReturn the path designated for temporary files.getVolumePathNamesForVolumeName(String lpszVolumeName) Invokes and parses the result ofKernel32.GetVolumePathNamesForVolumeName(String, char[], int, IntByReference)static booleanisWideCharEnvironmentStringBlock(Pointer lpszEnvironmentBlock, long offset) Attempts to determine whether the data block useswchar_tinstead of "plain old"chars.queryDosDevice(String lpszDeviceName, int maxTargetSize) Invokes theKernel32.QueryDosDevice(String, char[], int)method and parses the resultstatic final StringQueryFullProcessImageName(int pid, int dwFlags) This function retrieves the full path of the executable file of a given process identifier.static final StringQueryFullProcessImageName(WinNT.HANDLE hProcess, int dwFlags) This function retrieves the full path of the executable file of a given process.static StringreadEnvironmentStringBlockEntry(Pointer lpszEnvironmentBlock, long offset, boolean asWideChars) static final voidwritePrivateProfileSection(String appName, String[] strings, String fileName) static final voidwritePrivateProfileString(String appName, String keyName, String string, String fileName) 
- 
Field Details- 
VOLUME_GUID_PATH_PREFIX- See Also:
 
- 
VOLUME_GUID_PATH_SUFFIX- See Also:
 
 
- 
- 
Constructor Details- 
Kernel32Utilpublic Kernel32Util()
 
- 
- 
Method Details- 
getComputerNameGet current computer NetBIOS name.- Returns:
- Netbios name.
 
- 
freeLocalMemoryInvokesKernel32.LocalFree(Pointer)and checks if it succeeded.- Parameters:
- ptr- The- Pointerto the memory to be released - ignored if NULL
- Throws:
- Win32Exception- if non-- ERROR_SUCCESScode reported
 
- 
freeGlobalMemoryInvokesKernel32.GlobalFree(Pointer)and checks if it succeeded.- Parameters:
- ptr- The- Pointerto the memory to be released - ignored if NULL
- Throws:
- Win32Exception- if non-- ERROR_SUCCESScode reported
 
- 
closeHandleRefsCloses 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:
 
- 
closeHandleRefCloses the handle in the reference- Parameters:
- ref- The handle reference - ignored if- null
- See Also:
 
- 
closeHandlesInvokescloseHandle(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:
 
- 
closeHandleInvokesKernel32.CloseHandle(WinNT.HANDLE)and checks the success code. If not successful, then throws aWin32Exceptionwith theGetLastErrorvalue- Parameters:
- h- The handle to be closed - ignored if- null
 
- 
formatMessageFormat a message from a code.- Parameters:
- code- The error code
- Returns:
- Formatted message in the default locale.
 
- 
formatMessageFormat a message from the value obtained fromKernel32.GetLastError()orNative.getLastError().If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: - Language neutral
- Thread LANGID, based on the thread's locale value
- User default LANGID, based on the user's default locale value
- System default LANGID, based on the system default locale value
- US English
 - Parameters:
- code- The error code
- primaryLangId- The primary language identifier
- sublangId- The sublanguage identifier
- Returns:
- Formatted message in the specified locale.
 
- 
formatMessageFormat a message from an HRESULT.- Parameters:
- code- HRESULT
- Returns:
- Formatted message in the default locale.
 
- 
formatMessageFormat a message from an HRESULT.- Parameters:
- code- HRESULT
- primaryLangId- The primary language identifier
- sublangId- The primary language identifier
- Returns:
- Formatted message in the specified locale.
 
- 
formatMessageFromLastErrorCodeFormat a system message from an error code.- Parameters:
- code- Error code, typically a result of GetLastError.
- Returns:
- Formatted message in the default locale.
 
- 
formatMessageFromLastErrorCodeFormat a system message from an error code.- Parameters:
- code- Error code, typically a result of GetLastError.
- primaryLangId- The primary language identifier
- sublangId- The primary language identifier
- Returns:
- Formatted message in the specified locale.
 
- 
getLastErrorMessage- Returns:
- Obtains the human-readable error message text from the last error
         that occurred by invocating Kernel32.GetLastError()in the default locale.
 
- 
getLastErrorMessage- Returns:
- Obtains the human-readable error message text from the last error
         that occurred by invocating Kernel32.GetLastError()in the specified locale.
 
- 
getTempPathReturn the path designated for temporary files.- Returns:
- Path.
 
- 
deleteFile
- 
getLogicalDriveStringsReturns valid drives in the system.- Returns:
- A Listof valid drives.
 
- 
getFileAttributesRetrieves 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.
 
- 
getFileTypeRetrieves the result of GetFileType, provided the file exists.- Parameters:
- fileName- file name
- Returns:
- file type
- Throws:
- FileNotFoundException- if file not found
 
- 
getDriveType- Parameters:
- rootName- name of root drive
- Returns:
- One of the WinBase.DRIVE_* constants.
 
- 
getEnvironmentVariableGet the value of an environment variable.- Parameters:
- name- Name of the environment variable.
- Returns:
- Value of an environment variable.
 
- 
getEnvironmentVariablesUses theKernel32.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- Parameters:
- lpszEnvironmentBlock- The environment block as received from the GetEnvironmentStrings function
- offset- Offset within the block to parse the data
- Returns:
- A Mapof the parsedname=valuepairs. Note: if the environment block isnullthennullis returned instead of an empty map since we want to distinguish between the case that the data block isnulland when there are no environment variables (as unlikely as it may be)
 
- 
readEnvironmentStringBlockEntrypublic static 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- truethen the block contains- wchar_tinstead of "plain old"- chars
- Returns:
- A Stringcontaining thename=valuepair or empty if reached end of block
- See Also:
 
- 
findEnvironmentStringBlockEntryEndpublic 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- truethen the block contains- wchar_tinstead of "plain old"- chars
- 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:
 
- 
isWideCharEnvironmentStringBlockAttempts to determine whether the data block uses wchar_tinstead of "plain old"chars. 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" chars 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
 ByteOrdereven though onlyByteOrder.LITTLE_ENDIANis the likely one- Parameters:
- lpszEnvironmentBlock- The environment block as received from the GetEnvironmentStrings function
- offset- offset
- Returns:
- trueif the block contains- wchar_tinstead of "plain old"- chars
 
- 
      If the charset indicator is non-zero then it is assumed to be
      a "plain old" 
- 
getPrivateProfileIntpublic static final int getPrivateProfileInt(String appName, String keyName, int defaultValue, 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.
 
- 
getPrivateProfileStringpublic static final String getPrivateProfileString(String lpAppName, String lpKeyName, String lpDefault, 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- lpAppNameparameter are returned.
- lpDefault- A default string. If the- lpKeyNamekey 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 - nullcharacter in the- lpReturnedStringbuffer 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 - lpAppNamenor- lpKeyNameis- nulland the destination buffer is too small to hold the requested string, the string is truncated.- If either - lpAppNameor- lpKeyNameis- nulland the destination buffer is too small to hold all the strings, the last string is truncated and followed by two- nullcharacters.- In the event the initialization file specified by - lpFileNameis 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
- 
getLogicalProcessorInformationConvenience method to get the processor information. Takes care of auto-growing the array.- Returns:
- the array of processor information.
 
- 
getLogicalProcessorInformationExpublic static final WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX[] getLogicalProcessorInformationEx(int relationshipType) Convenience method to get the processor information. Takes care of auto-growing the array and populating variable-length arrays in structures.- Parameters:
- relationshipType- The type of relationship to retrieve. This parameter can be one of the following values:- WinNT.LOGICAL_PROCESSOR_RELATIONSHIP.RelationCache,- WinNT.LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup,- WinNT.LOGICAL_PROCESSOR_RELATIONSHIP.RelationNumaNode,- WinNT.LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore,- WinNT.LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorPackage, or- WinNT.LOGICAL_PROCESSOR_RELATIONSHIP.RelationAll
- Returns:
- the array of processor information.
 
- 
getPrivateProfileSectionRetrieves 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.
 
- 
getPrivateProfileSectionNamesRetrieves 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.
 
- 
writePrivateProfileSectionpublic static final void writePrivateProfileSection(String appName, String[] strings, 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.
 
- 
queryDosDeviceInvokes theKernel32.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
 
- 
getVolumePathNamesForVolumeNameInvokes and parses the result ofKernel32.GetVolumePathNamesForVolumeName(String, char[], int, IntByReference)- Parameters:
- lpszVolumeName- The volume name
- Returns:
- The parsed result
- Throws:
- Win32Exception- If failed to retrieve the required information
 
- 
extractVolumeGUIDParses and returns the pure GUID value of a volume name obtained fromKernel32.FindFirstVolume(char[], int)orKernel32.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:
- IllegalArgumentException- if bad format encountered
- See Also:
 
- 
QueryFullProcessImageNameThis function retrieves the full path of the executable file of a given process identifier.- Parameters:
- pid- Identifier 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.
 
- 
QueryFullProcessImageNameThis 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.
 
- 
getResourceGets 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:
- IllegalStateException- if the call to LockResource fails
 
- 
getResourceNamesGets 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.
 
- 
getModulesReturns 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.
 
- 
expandEnvironmentStringsExpands environment-variable strings and replaces them with the values defined for the current user.- Parameters:
- input- A string that contains one or more environment-variable strings in the form: %variableName%. For each such reference, the %variableName% portion is replaced with the current value of that environment variable.- Case is ignored when looking up the environment-variable name. If the name is not found, the %variableName% portion is left unexpanded. - Note that this function does not support all the features that Cmd.exe supports. For example, it does not support %variableName:str1=str2% or %variableName:~offset,length%. 
- Returns:
- the replaced string
- Throws:
- Win32Exception- if an error occurs
 
 
-