下面列出了怎么用com.sun.jna.platform.win32.WinDef的API类实例代码及写法,或者点击链接到github查看源代码。
private void doKeyRelease(int keyCode) {
logRobot(stdAutoDelay, "KeyRelease: WaitForIdle: %s - Delay: %d");
setAutoDelay(stdAutoDelay);
// on Windows we detect the current layout in KeyboardLayout.
// Since this layout is not compatible to AWT Robot, we have to use
// the User32 API to simulate the key release
if (Settings.AutoDetectKeyboardLayout && Settings.isWindows()) {
int scanCode = SXUser32.INSTANCE.MapVirtualKeyW(keyCode, 0);
SXUser32.INSTANCE.keybd_event((byte)keyCode, (byte)scanCode, new WinDef.DWORD(WinUser.KEYBDINPUT.KEYEVENTF_KEYUP), new BaseTSD.ULONG_PTR(0));
}else{
keyRelease(keyCode);
}
if (stdAutoDelay == 0) {
delay(stdDelay);
}
logRobot("KeyRelease: extended delay: %d", stdMaxElapsed);
}
@Test
public void testScheduleError() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
evtSubscribe = new ConsumeWindowsEventLog(wEvtApi, kernel32);
when(wEvtApi.EvtSubscribe(isNull(WinNT.HANDLE.class), isNull(WinNT.HANDLE.class), eq(ConsumeWindowsEventLog.DEFAULT_CHANNEL), eq(ConsumeWindowsEventLog.DEFAULT_XPATH),
isNull(WinNT.HANDLE.class), isNull(WinDef.PVOID.class), isA(EventSubscribeXmlRenderingCallback.class),
eq(WEvtApi.EvtSubscribeFlags.SUBSCRIBE_TO_FUTURE | WEvtApi.EvtSubscribeFlags.EVT_SUBSCRIBE_STRICT)))
.thenReturn(null);
when(kernel32.GetLastError()).thenReturn(WinError.ERROR_ACCESS_DENIED);
testRunner = TestRunners.newTestRunner(evtSubscribe);
testRunner.run(1);
assertEquals(0, getCreatedSessions(testRunner).size());
verify(wEvtApi, never()).EvtClose(any(WinNT.HANDLE.class));
}
/**
* Forcibly set focus to the given component
*
*/
public static void requestForeground(Frame frame)
{
// SetForegroundWindow can't set iconified windows to foreground, so set the
// frame state to normal first
frame.setState(Frame.NORMAL);
User32 user32 = User32.INSTANCE;
// Windows does not allow any process to set the foreground window, but it will if
// the process received the last input event. So we send a F22 key event to the process.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow
WinUser.INPUT input = new WinUser.INPUT();
input.type = new WinDef.DWORD(WinUser.INPUT.INPUT_KEYBOARD);
input.input.ki.wVk = new WinDef.WORD(0x85); // VK_F22
user32.SendInput(new WinDef.DWORD(1), (WinUser.INPUT[]) input.toArray(1), input.size());
// Now we may set the foreground window
WinDef.HWND hwnd = new WinDef.HWND(Native.getComponentPointer(frame));
user32.SetForegroundWindow(hwnd);
}
public static void main(String[] args) {
final User32 user32 = User32.INSTANCE;
user32.EnumWindows(new WinUser.WNDENUMPROC() {
int count = 0;
@Override
public boolean callback(WinDef.HWND hwnd, Pointer pointer) {
byte[] windowText = new byte[512];
byte[] className = new byte[512];
user32.GetWindowTextA(hwnd, windowText, 512);
user32.GetClassNameA(hwnd, className, 512);
String title = Native.toString(windowText);
String classN = Native.toString(className);
// get rid of this if block if you want all windows regardless of whether
// or not they have text
if (title.isEmpty()) {
return true;
}
System.out.println("Title: " + title + " Class name: " + classN);
return true;
}
},null);
}
public void pressKeys(final List<KeyboardKey> keys) {
if (keys.isEmpty()) {
return;
}
final WinUser.INPUT input = new WinUser.INPUT();
final WinUser.INPUT[] inputs = (WinUser.INPUT[]) input.toArray(keys.size() * 2);
final ListIterator<KeyboardKey> iterator = keys.listIterator();
int index = 0;
while (iterator.hasNext()) {
setKeyDown(inputs[index], iterator.next());
index++;
}
while (iterator.hasPrevious()) {
setKeyUp(inputs[index], iterator.previous());
index++;
}
user32.SendInput(new WinDef.DWORD(inputs.length), inputs, inputs[0].size());
}
private void setHasFrame(JFrame frame, boolean hasFrame) {
if (!this.frameless) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println(windowName + " hasFrame=" + hasFrame);
WinDef.HWND hWnd = new WinDef.HWND();
hWnd.setPointer(Native.getComponentPointer(frame));
LayoutFrame.this.externalWindowObserver.setHasFrame(hWnd, hasFrame);
frame.setResizable(hasFrame);
frame.invalidate();
frame.validate();
frame.repaint();
SwingUtilities.updateComponentTreeUI(frame);
}
});
}
}
public static BufferedImage extractExeIcon(String fullExeFile, int index, boolean large) {
PointerByReference iconsLargeRef = new PointerByReference();
PointerByReference iconsSmallRef = new PointerByReference();
int cnt = Shell32.INSTANCE.ExtractIconEx(fullExeFile, index, iconsLargeRef, iconsSmallRef, new WinDef.UINT(1)).intValue();
if (cnt == 0) {
return null;
}
Pointer iconsLarge = iconsLargeRef.getPointer();
Pointer iconsSmall = iconsSmallRef.getPointer();
WinDef.HICON icon;
if (large) {
icon = new WinDef.HICON(iconsLarge.getPointer(0));
} else {
icon = new WinDef.HICON(iconsSmall.getPointer(0));
}
BufferedImage ic = iconToImage(icon);
User32.INSTANCE.DestroyIcon(icon);
return ic;
}
private void doKeyPress(int keyCode) {
Highlight fakeHighlight = null;
if (RunTime.get().needsRobotFake()) {
fakeHighlight = Highlight.fakeHighlight();
}
logRobot(stdAutoDelay, "KeyPress: WaitForIdle: %s - Delay: %d");
setAutoDelay(stdAutoDelay);
if (null != fakeHighlight) {
delay(20);
fakeHighlight.close();
delay(20);
}
// on Windows we detect the current layout in KeyboardLayout.
// Since this layout is not compatible to AWT Robot, we have to use
// the User32 API to simulate the key press
if (Settings.AutoDetectKeyboardLayout && Settings.isWindows()) {
int scanCode = SXUser32.INSTANCE.MapVirtualKeyW(keyCode, 0);
SXUser32.INSTANCE.keybd_event((byte)keyCode, (byte)scanCode, new WinDef.DWORD(0), new BaseTSD.ULONG_PTR(0));
}else{
keyPress(keyCode);
}
if (stdAutoDelay == 0) {
delay(stdDelay);
}
logRobot("KeyPress: extended delay: %d", stdMaxElapsed);
}
@Before
public void setup() {
evtSubscribe = new ConsumeWindowsEventLog(wEvtApi, kernel32);
when(subscriptionHandle.getPointer()).thenReturn(subscriptionPointer);
when(wEvtApi.EvtSubscribe(isNull(WinNT.HANDLE.class), isNull(WinNT.HANDLE.class), eq(ConsumeWindowsEventLog.DEFAULT_CHANNEL), eq(ConsumeWindowsEventLog.DEFAULT_XPATH),
isNull(WinNT.HANDLE.class), isNull(WinDef.PVOID.class), isA(EventSubscribeXmlRenderingCallback.class),
eq(WEvtApi.EvtSubscribeFlags.SUBSCRIBE_TO_FUTURE | WEvtApi.EvtSubscribeFlags.EVT_SUBSCRIBE_STRICT)))
.thenReturn(subscriptionHandle);
testRunner = TestRunners.newTestRunner(evtSubscribe);
}
public List<EventSubscribeXmlRenderingCallback> getRenderingCallbacks(int times) {
ArgumentCaptor<EventSubscribeXmlRenderingCallback> callbackArgumentCaptor = ArgumentCaptor.forClass(EventSubscribeXmlRenderingCallback.class);
verify(wEvtApi, times(times)).EvtSubscribe(isNull(WinNT.HANDLE.class), isNull(WinNT.HANDLE.class), eq(ConsumeWindowsEventLog.DEFAULT_CHANNEL), eq(ConsumeWindowsEventLog.DEFAULT_XPATH),
isNull(WinNT.HANDLE.class), isNull(WinDef.PVOID.class), callbackArgumentCaptor.capture(),
eq(WEvtApi.EvtSubscribeFlags.SUBSCRIBE_TO_FUTURE | WEvtApi.EvtSubscribeFlags.EVT_SUBSCRIBE_STRICT));
return callbackArgumentCaptor.getAllValues();
}
public static void updateStageStyle(Stage stage) {
if (Platform.isWindows()) {
Pointer pointer = getWindowPointer(stage);
WinDef.HWND hwnd = new WinDef.HWND(pointer);
final User32 user32 = User32.INSTANCE;
int oldStyle = user32.GetWindowLong(hwnd, WinUser.GWL_STYLE);
int newStyle = oldStyle | 0x00020000; // WS_MINIMIZEBOX
user32.SetWindowLong(hwnd, WinUser.GWL_STYLE, newStyle);
}
}
@Override
public void run() {
WinDef.HMODULE handle = Kernel32.INSTANCE.GetModuleHandle(null);
this.hhk = User32.INSTANCE.SetWindowsHookEx(hookType, eventReceiver, handle, 0);
int result;
while ((result = getMessage()) != 0) {
if (result == -1) {
onFail();
break;
} else {
dispatchEvent();
}
}
unhook();
}
private static void setTransparent(Component w) {
WinDef.HWND hwnd = getHWnd(w);
int wl = User32.INSTANCE.GetWindowLong(hwnd, WinUser.GWL_EXSTYLE);
// wl = wl | WinUser.WS_EX_LAYERED | WinUser.WS_EX_TRANSPARENT;
wl = wl | WinUser.WS_EX_LAYERED | WinUser.WS_EX_TRANSPARENT;
User32.INSTANCE.SetWindowLong(hwnd, WinUser.GWL_EXSTYLE, wl);
}
public static Rectangle getWindowArea(Pointer hWnd)
{
if(!isKernelAvailable() || hWnd == null)return null;
WinDef.RECT rect = new WinDef.RECT();
user32.GetWindowRect(hWnd, rect);
return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
}
public List<Integer> getCoord()
{
if(!available || libuser32 == null)
return null;
WinDef.POINT point = new WinDef.POINT(0,0);
if(libuser32.ClientToScreen(libuser32.FindWindowW(null, name.toCharArray()), point))
{
List<Integer> coord = new ArrayList<>();
coord.add(point.x);
coord.add(point.y);
return coord;
}
else
return null;
}
/**
* Create keyboard input event.
*
* @param character character to print
* @param flags flags
* @return keyboard input event
*/
private static WinUser.INPUT createKeyboardInput(char character, long flags) {
WinUser.INPUT input = new WinUser.INPUT();
input.type = new WinDef.DWORD(WinUser.INPUT.INPUT_KEYBOARD);
input.input.setType("ki");
input.input.ki = new WinUser.KEYBDINPUT();
input.input.ki.wVk = new WinDef.WORD(0);
input.input.ki.wScan = new WinDef.WORD(character);
input.input.ki.time = new WinDef.DWORD(0);
input.input.ki.dwFlags = new WinDef.DWORD(flags);
input.input.ki.dwExtraInfo = new BaseTSD.ULONG_PTR();
return input;
}
boolean InitiateSystemShutdown(
String lpMachineName,
String lpMessage,
WinDef.DWORD dwTimeout,
boolean bForceAppsClosed,
boolean bRebootAfterShutdown
);
public void setDisplaySleep(final boolean sleep) {
user32.DefWindowProc(
getForegroundWindow().get(),
WinUser.WM_SYSCOMMAND,
new WinDef.WPARAM(SC_MONITORPOWER),
new WinDef.LPARAM(sleep ? 2 : -1)
);
}
public void shutdown() throws SystemException {
final boolean success = advapi32.InitiateSystemShutdown(
null,
null,
new WinDef.DWORD(0),
true,
false
);
if (!success) {
throw new SystemException(Kernel32Util.formatMessage(kernel32.GetLastError()));
}
}
public void reboot() throws SystemException {
final boolean success = advapi32.InitiateSystemShutdown(
null,
null,
new WinDef.DWORD(0),
true,
true
);
if (!success) {
throw new SystemException(Kernel32Util.formatMessage(kernel32.GetLastError()));
}
}
public void run(final String command, final String parameters, final String workingDirectory)
throws SystemException {
final WinDef.INT_PTR result = shell32.ShellExecute(
null,
"open",
Objects.requireNonNull(command),
Objects.requireNonNull(parameters),
workingDirectory,
WinUser.SW_SHOWNORMAL
);
if (result.intValue() <= 32) {
throw new SystemException("Could not run command: " + command + " " + parameters);
}
}
public void open(final String uri) throws SystemException {
final WinDef.INT_PTR result = shell32.ShellExecute(
null,
"open",
Objects.requireNonNull(uri),
null,
null,
WinUser.SW_SHOWNORMAL
);
if (result.intValue() <= 32) {
throw new SystemException("Cannot open URI: " + uri);
}
}
private long getWindowHandle(Stage stage) {
long handle = -1;
try {
WinDef.HWND hWnd = User32.INSTANCE.FindWindow(null, WINDOW_TITLE);
handle = Pointer.nativeValue(hWnd.getPointer());
} catch (Throwable e) {
logger.error("Error getting Window Pointer", e);
}
logger.info(String.format("Stage hwnd %d", handle));
return handle;
}
private void activateFrame(@Nullable Project openedProject, @Nonnull UnityOpenFilePostHandlerRequest body)
{
if(openedProject == null)
{
return;
}
IdeFrame ideFrame = WindowManager.getInstance().getIdeFrame(openedProject);
if(ideFrame == null || !ideFrame.getWindow().isVisible())
{
return;
}
if(SystemInfo.isMac)
{
RequestFocusHttpRequestHandler.activateFrame(ideFrame);
ID id = MacUtil.findWindowFromJavaWindow(TargetAWT.to(ideFrame.getWindow()));
if(id != null)
{
Foundation.invoke(id, "makeKeyAndOrderFront:", ID.NIL);
}
}
else if(SystemInfo.isWindows)
{
Pointer windowPointer = Native.getWindowPointer(TargetAWT.to(ideFrame.getWindow()));
User32.INSTANCE.SetForegroundWindow(new WinDef.HWND(windowPointer));
}
else
{
RequestFocusHttpRequestHandler.activateFrame(ideFrame);
}
}
private static boolean unsetGuard(HANDLE hOtherProcess, MEMORY_BASIC_INFORMATION mbi) {
if (!hasGuard(mbi)) {
return true;
}
int oldProt = mbi.protect.intValue();
int newProt = oldProt - WinNT.PAGE_GUARD;
IntByReference oldProtRef = new IntByReference();
boolean ok = Kernel32.INSTANCE.VirtualProtectEx(hOtherProcess, new WinDef.LPVOID(pointerToAddress(mbi.baseAddress)), mbi.regionSize, newProt, oldProtRef);
if (ok) {
mbi.protect = new NativeLong(newProt);
return true;
}
return false;
}
private static boolean setGuard(HANDLE hOtherProcess, MEMORY_BASIC_INFORMATION mbi) {
if (hasGuard(mbi)) {
return true;
}
int oldProt = mbi.protect.intValue();
int newProt = oldProt | WinNT.PAGE_GUARD;
IntByReference oldProtRef = new IntByReference();
boolean ok = Kernel32.INSTANCE.VirtualProtectEx(hOtherProcess, new WinDef.LPVOID(pointerToAddress(mbi.baseAddress)), mbi.regionSize, newProt, oldProtRef);
if (ok) {
mbi.protect = new NativeLong(newProt);
return true;
}
return false;
}
public static boolean adjustPrivileges() {
WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1);
WinNT.TOKEN_PRIVILEGES oldtp = new WinNT.TOKEN_PRIVILEGES(1);
WinNT.LUID luid = new WinNT.LUID();
WinNT.HANDLEByReference hTokenRef = new WinNT.HANDLEByReference();
if (!Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES | WinNT.TOKEN_QUERY, hTokenRef)) {
return false;
}
WinNT.HANDLE hToken = hTokenRef.getValue();
if (!Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid)) {
Kernel32.INSTANCE.CloseHandle(hToken);
return false;
}
tp.PrivilegeCount = new WinDef.DWORD(1);
tp.Privileges = new WinNT.LUID_AND_ATTRIBUTES[1];
tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED));
IntByReference retSize = new IntByReference(0);
if (!Advapi32.INSTANCE.AdjustTokenPrivileges(hToken, false, tp, tp.size(), oldtp, retSize)) {
Kernel32.INSTANCE.CloseHandle(hToken);
return false;
}
Kernel32.INSTANCE.CloseHandle(hToken);
privAdjusted = true;
return true;
}
private static String shortPath(String path) {
if (path.contains(" ")) {
// On the way from Runtime.exec() to CreateProcess(), a command line goes through couple rounds of merging and splitting
// which breaks paths containing a sequence of two or more spaces.
// Conversion to a short format is an ugly hack allowing to open such paths in Explorer.
char[] result = new char[WinDef.MAX_PATH];
if (Kernel32.INSTANCE.GetShortPathName(path, result, result.length) <= result.length) {
return Native.toString(result);
}
}
return path;
}
WinNT.HANDLE EvtSubscribe(WinNT.HANDLE session, WinNT.HANDLE signalEvent, String channelName, String xpathQuery,
WinNT.HANDLE bookmark, WinDef.PVOID context, EVT_SUBSCRIBE_CALLBACK evtSubscribeCallback, int flags);
private static WinDef.HWND getHWnd(Component w) {
WinDef.HWND hwnd = new WinDef.HWND();
hwnd.setPointer(Native.getComponentPointer(w));
return hwnd;
}