下面列出了怎么用com.sun.jna.WString的API类实例代码及写法,或者点击链接到github查看源代码。
public static int getWin32FileAttributes (File file)
throws IOException
{
// allow lookup of paths longer than MAX_PATH
// http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx
String canonicalPath = file.getCanonicalPath();
String path;
if (canonicalPath.length() < 260) {
// path is short, use as-is
path = canonicalPath;
} else if (canonicalPath.startsWith("\\\\")) {
// network share
// \\server\share --> \\?\UNC\server\share
path = "\\\\?\\UNC\\" + canonicalPath.substring(2);
} else {
// prefix, canonical path should be normalized and absolute so this should work.
path = "\\\\?\\" + canonicalPath;
}
return Kernel32.INSTANCE.GetFileAttributesW(new WString(path));
}
public byte[] encode(File file) {
byte[] path = new byte[file.getAbsolutePath().length() * 3 + 1];
int pathLength = libC.wcstombs(path, new WString(file.getAbsolutePath()), path.length);
if (pathLength < 0) {
throw new RuntimeException(String.format("Could not encode file path '%s'.", file.getAbsolutePath()));
}
byte[] zeroTerminatedByteArray = new byte[pathLength + 1];
System.arraycopy(path, 0, zeroTerminatedByteArray, 0, pathLength);
zeroTerminatedByteArray[pathLength] = 0;
return zeroTerminatedByteArray;
}
/** @see <a href="http://msdn.microsoft.com/en-us/library/aa380261(VS.85,printer).aspx">Reference</a> */
boolean CryptProtectData(
CryptIntegerBlob pDataIn,
WString szDataDescr,
CryptIntegerBlob pOptionalEntropy,
Pointer pvReserved,
Pointer pPromptStruct,
int dwFlags,
CryptIntegerBlob pDataOut
)/* throws LastErrorException*/;
/** @see <a href="http://msdn.microsoft.com/en-us/library/aa380882(VS.85,printer).aspx">Reference</a> */
boolean CryptUnprotectData(
CryptIntegerBlob pDataIn,
WString[] ppszDataDescr,
CryptIntegerBlob pOptionalEntropy,
Pointer pvReserved,
Pointer pPromptStruct,
int dwFlags,
CryptIntegerBlob pDataOut
)/* throws LastErrorException*/;
@Override
public void setString(long offset, WString value) {
if (m_sealed)
throw new UnsupportedOperationException();
super.setString(offset, value);
}
@Override
public void setString(long offset, WString value) {
if (m_sealed)
throw new UnsupportedOperationException();
super.setString(offset, value);
}
public SecureStorageStatus setCredential(String host, String user, String token)
{
if (Strings.isNullOrEmpty(token))
{
logger.info("No token provided");
return SecureStorageStatus.SUCCESS;
}
byte[] credBlob = token.getBytes(StandardCharsets.UTF_16LE);
Memory credBlobMem = new Memory(credBlob.length);
credBlobMem.write(0, credBlob, 0, credBlob.length);
String target = SecureStorageManager.convertTarget(host, user);
SecureStorageWindowsCredential cred = new SecureStorageWindowsCredential();
cred.Type = SecureStorageWindowsCredentialType.CRED_TYPE_GENERIC.getType();
cred.TargetName = new WString(target);
cred.CredentialBlobSize = (int) credBlobMem.size();
cred.CredentialBlob = credBlobMem;
cred.Persist = SecureStorageWindowsCredentialPersistType.CRED_PERSIST_LOCAL_MACHINE.getType();
cred.UserName = new WString(user.toUpperCase());
boolean ret = false;
synchronized (advapi32Lib)
{
ret = advapi32Lib.CredWriteW(cred, 0);
}
if (!ret)
{
logger.info(String.format("Failed to write to Windows Credential Manager. Error code = %d", Native.getLastError()));
return SecureStorageStatus.FAILURE;
}
logger.info("Wrote to Windows Credential Manager successfully");
return SecureStorageStatus.SUCCESS;
}
public byte[] encode(File file) {
byte[] path = new byte[file.getAbsolutePath().length() * 3 + 1];
int pathLength = libC.wcstombs(path, new WString(file.getAbsolutePath()), path.length);
if (pathLength < 0) {
throw new RuntimeException(String.format("Could not encode file path '%s'.", file.getAbsolutePath()));
}
byte[] zeroTerminatedByteArray = new byte[pathLength + 1];
System.arraycopy(path, 0, zeroTerminatedByteArray, 0, pathLength);
zeroTerminatedByteArray[pathLength] = 0;
return zeroTerminatedByteArray;
}
/**
* @param target
* If relative, resolved against the location of the symlink.
* If absolute, it's absolute.
*/
public static void createSymbolicLink (File symlink,
String target,
boolean dirLink)
throws IOException
{
if (!Kernel32.INSTANCE.CreateSymbolicLinkW(
new WString(symlink.getPath()),
new WString(target),
dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) {
throw new WinIOException(
"Failed to create a symlink " + symlink + " to " + target);
}
}
public static void onWindows() {
// Windows taskbar fix: provideAppUserModelID
try {
NativeLibrary lib = NativeLibrary.getInstance("shell32");
Function function = lib.getFunction("SetCurrentProcessExplicitAppUserModelID");
Object[] args = {new WString(APPID)};
function.invokeInt(args);
} catch (Error e) {
return;
} catch (Exception x) {
return;
}
}
public WinLockListener() {
// define new window class
final WString windowClass = new WString("MyWindowClass");
final WinDef.HMODULE hInst = Kernel32.INSTANCE.GetModuleHandle("");
WinUser.WNDCLASSEX wClass = new WinUser.WNDCLASSEX();
wClass.hInstance = hInst;
wClass.lpfnWndProc = WinLockListener.this;
wClass.lpszClassName = windowClass.toString();
// register window class
User32.INSTANCE.RegisterClassEx(wClass);
getLastError();
// create new window
final WinDef.HWND hWnd = User32.INSTANCE.CreateWindowEx(User32.WS_EX_TOPMOST, windowClass.toString(), "'hidden helper window to catch Windows events", 0, 0, 0, 0, 0, null, // WM_DEVICECHANGE contradicts parent=WinUser.HWND_MESSAGE
null, hInst, null);
getLastError();
Log.debug("window sucessfully created! window hwnd: " + hWnd.getPointer().toString());
Wtsapi32.INSTANCE.WTSRegisterSessionNotification(hWnd, Wtsapi32.NOTIFY_FOR_THIS_SESSION);
WinUser.MSG msg = new WinUser.MSG();
while (User32.INSTANCE.GetMessage(msg, hWnd, 0, 0) != 0) {
User32.INSTANCE.TranslateMessage(msg);
User32.INSTANCE.DispatchMessage(msg);
}
/// This code is to clean at the end. You can attach it to your custom application shutdown listener
Wtsapi32.INSTANCE.WTSUnRegisterSessionNotification(hWnd);
User32.INSTANCE.UnregisterClass(windowClass.toString(), hInst);
User32.INSTANCE.DestroyWindow(hWnd);
Log.debug("program exit!");
}
@Override
public void setString(long offset, WString value) {
throw new AbstractMethodError();
}
/**
* Start the KeyStore Explorer application. Takes one optional argument -
* the location of a KeyStore file to open upon startup.
*
* @param args
* the command line arguments
*/
public static void main(String args[]) {
try {
// To take affect these must be set before the splash screen is instantiated
if (OperatingSystem.isMacOs()) {
setAppleSystemProperties();
} else if (OperatingSystem.isWindows7() || OperatingSystem.isWindows8() || OperatingSystem.isWindows10()) {
String appId = props.getString("KSE.AppUserModelId");
Shell32 shell32 = Native.loadLibrary("shell32", Shell32.class);
shell32.SetCurrentProcessExplicitAppUserModelID(new WString(appId)).longValue();
} else if (OperatingSystem.isLinux()) {
fixAppClassName();
}
setInstallDirProperty();
SplashScreen splash = SplashScreen.getSplashScreen();
updateSplashMessage(splash, res.getString("KSE.LoadingApplicationSettings.splash.message"));
ApplicationSettings applicationSettings = ApplicationSettings.getInstance();
setCurrentDirectory(applicationSettings);
String languageCode = applicationSettings.getLanguage();
if (!ApplicationSettings.SYSTEM_LANGUAGE.equals(languageCode)) {
Locale.setDefault(new Locale(languageCode));
}
updateSplashMessage(splash, res.getString("KSE.InitializingSecurity.splash.message"));
initialiseSecurity();
// list of files to open after start
List<File> parameterFiles = new ArrayList<>();
for (String arg : args) {
File parameterFile = new File(arg);
if (parameterFile.exists()) {
parameterFiles.add(parameterFile);
}
}
// Create application GUI on the event handler thread
updateSplashMessage(splash, res.getString("KSE.CreatingApplicationGui.splash.message"));
SwingUtilities.invokeLater(new CreateApplicationGui(applicationSettings, splash, parameterFiles));
} catch (Throwable t) {
DError dError = new DError(new JFrame(), t);
dError.setLocationRelativeTo(null);
dError.setVisible(true);
System.exit(1);
}
}
public synchronized boolean open(File file) {
return file.isFile()
&& MediaInfoLibrary.INSTANCE.Open(handle, new WString(file.getAbsolutePath())) > 0;
}
public synchronized String get(StreamKind streamKind, int streamNumber, String parameter,
InfoKind infoKind, InfoKind searchKind) {
return MediaInfoLibrary.INSTANCE.Get(handle, streamKind.ordinal(), streamNumber,
new WString(parameter), infoKind.ordinal(), searchKind.ordinal()).toString();
}
public static String staticOption(String option, String value) {
return MediaInfoLibrary.INSTANCE.Option(null, new WString(option), new WString(value))
.toString();
}
/** HB */
WString GetCommandLineW();
/**
* Open a file and collect information about it (technical information and tags).
*
* @param handle
* @param file
* full name of the file to open
* @return 1 if file was opened, 0 if file was not not opened
*/
int Open(Pointer handle, WString file);
/**
* Configure or get information about MediaInfo.
*
* @param handle
* @param option
* The name of option
* @param value
* The value of option
* @return Depends on the option: by default "" (nothing) means No, other means Yes
*/
WString Option(Pointer handle, WString option, WString value);
/**
* Get all details about a file.
*
* @param handle
* @return All details about a file in one string
*/
WString Inform(Pointer handle);
/**
* Get a piece of information about a file (parameter is a string).
*
* @param handle
* @param streamKind
* Kind of stream (general, video, audio...)
* @param streamNumber
* Stream number in Kind of stream (first, second...)
* @param parameter
* Parameter you are looking for in the stream (Codec, width, bitrate...), in string
* format ("Codec", "Width"...)
* @param infoKind
* Kind of information you want about the parameter (the text, the measure, the help...)
* @param searchKind
* Where to look for the parameter
* @return a string about information you search, an empty string if there is a problem
*/
WString Get(Pointer handle, int streamKind, int streamNumber, WString parameter, int infoKind,
int searchKind);
/**
* Get a piece of information about a file (parameter is an integer).
*
* @param handle
* @param streamKind
* Kind of stream (general, video, audio...)
* @param streamNumber
* Stream number in Kind of stream (first, second...)
* @param parameter
* Parameter you are looking for in the stream (Codec, width, bitrate...), in integer
* format (first parameter, second parameter...)
* @param infoKind
* Kind of information you want about the parameter (the text, the measure, the help...)
* @return a string about information you search, an empty string if there is a problem
*/
WString GetI(Pointer handle, int streamKind, int streamNumber, int parameterIndex, int infoKind);
/**
* Unregisters a window class, freeing the memory required for the class.
*
* @param lpClassName [in] Type: LPCTSTR
*
* A null-terminated string or a class atom. If lpClassName is a string, it
* specifies the window class name. This class name must have been
* registered by a previous call to the RegisterClass or RegisterClassEx
* function. System classes, such as dialog box controls, cannot be
* unregistered. If this parameter is an atom, it must be a class atom
* created by a previous call to the RegisterClass or RegisterClassEx
* function. The atom must be in the low-order word of lpClassName; the
* high-order word must be zero.
*
* @param hInstance [in,optional] Type: HINSTANCE A handle to the instance
* of the module that created the class. *
*
* @return Type: BOOL If the function succeeds, the return value is nonzero.
*
* If the function fails, the return value is zero. To get extended error
* information, call {@link Kernel32#GetLastError}.
*/
public boolean UnregisterClass(WString lpClassName, HINSTANCE hInstance);
/**
* Retrieves information about a window class, including a handle to the
* small icon associated with the window class. The GetClassInfo function
* does not retrieve a handle to the small icon.
*
* @param hinst [in, optional] Type: HINSTANCE
*
* A handle to the instance of the application that created the class. To
* retrieve information about classes defined by the system (such as buttons
* or list boxes), set this parameter to NULL.
*
* @param lpszClass [in] Type: LPCTSTR
*
* The class name. The name must be that of a preregistered class or a class
* registered by a previous call to the RegisterClass or RegisterClassEx
* function. Alternatively, this parameter can be a class atom created by a
* previous call to RegisterClass or RegisterClassEx. The atom must be in
* the low-order word of lpszClass; the high-order word must be zero.
*
* @param lpwcx [out] Type: LPWNDCLASSEX
*
* A pointer to a WNDCLASSEX structure that receives the information about
* the class.
*
* @return Type: BOOL If the function finds a matching class and
* successfully copies the data, the return value is nonzero.
*
* If the function fails, the return value is zero. To get extended error
* information, call {@link Kernel32#GetLastError} .
*/
public boolean GetClassInfoEx(HINSTANCE hinst, WString lpszClass,
WNDCLASSEX lpwcx);
/**
* Creates a symbolic link.
*
* Windows Vista+, Windows Server 2008+
*
* @param lpSymlinkFileName
* Symbolic link to be created
* @param lpTargetFileName
* Target of the link.
* @param dwFlags
* 0 or {@link #SYMBOLIC_LINK_FLAG_DIRECTORY}
* @see <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363866(v=vs.85).aspx">MSDN</a>
*/
boolean CreateSymbolicLinkW (WString lpSymlinkFileName,
WString lpTargetFileName,
int dwFlags);
/**
* Retrieves the short path form of the specified path. See
* <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364989.aspx">{@code GetShortPathName}</a>.
*
* @param lpszLongPath the path string
* @param lpszShortPath a buffer to receive the short name
* @param cchBuffer the size of the buffer
* @return the length of the string copied into {@code lpszShortPath}, otherwise zero for failure
*/
@SuppressWarnings("checkstyle:methodname")
native int GetShortPathNameW(WString lpszLongPath, char[] lpszShortPath, int cchBuffer);
public int wcstombs(byte[] dest, WString source, int size) throws LastErrorException;
WString GetCommandLineW();
Pointer CommandLineToArgvW(WString command_line, IntByReference argc);
NativeLong SetCurrentProcessExplicitAppUserModelID(WString appID);