下面列出了org.junit.jupiter.api.condition.EnabledOnOs#com.sun.jna.platform.win32.User32 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Manually focus the PowerPoint Viewer window. Shift focus to PowerPoint
* Viewer to move that window to the top or resume playback.
*/
private static String focusPPTView() {
// Set focus to PowerPoint Viewer
HWND hwnd = User32.INSTANCE.FindWindow(null,
title); // window title
String ret = "";
if (hwnd == null) {
ret = "PowerPoint Viewer is not running";
LOGGER.log(Level.INFO, ret);
} else {
User32.INSTANCE.ShowWindow(hwnd, 9); // SW_RESTORE
User32.INSTANCE.SetForegroundWindow(hwnd); // bring to front
ret = "Successfully focued PPTView";
}
return ret;
}
public static boolean switchToWinOs(Predicate<String> condition) {
final AtomicBoolean found = new AtomicBoolean();
User32.INSTANCE.EnumWindows((HWND hwnd, com.sun.jna.Pointer p) -> {
char[] windowText = new char[512];
User32.INSTANCE.GetWindowText(hwnd, windowText, 512);
String windowName = Native.toString(windowText);
logger.debug("scanning window: {}", windowName);
if (condition.test(windowName)) {
found.set(true);
focusWinOs(hwnd);
return false;
}
return true;
}, null);
return found.get();
}
/**
* Sends an action (flags) at the given x,y coordinates.
*
* @param x
* @param y
* @param flags
*/
public static void mouseAction(int x, int y, int flags) {
INPUT input = new INPUT();
input.type = new DWORD(INPUT.INPUT_MOUSE);
input.input.setType("mi");
if (x != -1) {
input.input.mi.dx = new LONG(x);
}
if (y != -1) {
input.input.mi.dy = new LONG(y);
}
input.input.mi.time = new DWORD(0);
input.input.mi.dwExtraInfo = new ULONG_PTR(0);
input.input.mi.dwFlags = new DWORD(flags);
User32.INSTANCE.SendInput(new DWORD(1), new INPUT[] { input }, input.size());
}
@Override
public LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT info) {
boolean cancel = false;
int code = wParam.intValue();
if (code == WM_MOUSEMOVE) {
cancel = onMouseMove(info.hwnd, info.pt);
} else if (code == WM_MOUSESCROLL) {
boolean down = Pointer.nativeValue(info.hwnd.getPointer()) == 4287102976L;
cancel = onMouseScroll(down, info.hwnd, info.pt);
} else if (code == WM_MOUSELDOWN || code == WM_MOUSERDOWN || code == WM_MOUSEMDOWN) {
onMousePress(MouseButtonType.fromWParam(code), info.hwnd, info.pt);
} else if (code == WM_MOUSELUP || code == WM_MOUSERUP || code == WM_MOUSEMUP) {
onMouseRelease(MouseButtonType.fromWParam(code), info.hwnd, info.pt);
}
if (cancel) {
return new LRESULT(1);
}
Pointer ptr = info.getPointer();
long peer = Pointer.nativeValue(ptr);
return User32.INSTANCE.CallNextHookEx(getHookManager().getHhk(this), nCode, wParam, new LPARAM(peer));
}
/**
* 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);
}
private void gameToFront() {
User32.INSTANCE.EnumWindows((hWnd, arg1) -> {
char[] className = new char[512];
User32.INSTANCE.GetClassName(hWnd, className, 512);
String wText = Native.toString(className);
if (wText.isEmpty()) {
return true;
}
if (wText.equals("POEWindowClass")) {
User32.INSTANCE.SetForegroundWindow(hWnd);
return false;
}
return true;
}, null);
}
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 updateState() {
if (!myFailureDetected) {
try {
// This might not work in all cases, but hopefully is a more reliable method than the current one (checking for font smoothing)
// see https://msdn.microsoft.com/en-us/library/aa380798%28v=vs.85%29.aspx
boolean newValue = User32.INSTANCE.GetSystemMetrics(0x1000) != 0; // 0x1000 is SM_REMOTESESSION
LOG.debug("Detected remote desktop: ", newValue);
if (newValue != myRemoteDesktopConnected) {
myRemoteDesktopConnected = newValue;
if (myRemoteDesktopConnected) {
// We postpone notification to avoid recursive initialization of RemoteDesktopDetector
// (in case it's initialized by request from com.intellij.notification.EventLog)
ApplicationManager.getApplication().invokeLater(() -> Notifications.Bus.notify(
NOTIFICATION_GROUP
.createNotification(ApplicationBundle.message("remote.desktop.detected.message"), NotificationType.INFORMATION)
.setTitle(ApplicationBundle.message("remote.desktop.detected.title"))));
}
}
}
catch (Throwable e) {
myRemoteDesktopConnected = false;
myFailureDetected = true;
LOG.warn("Error while calling GetSystemMetrics", e);
}
}
}
/**
* <p><b>Compatible only with windows!</b></p>
*/
protected void fetchEventWithUser32() {
final User32 lib = User32.INSTANCE;
final WinUser.MSG msg = new WinUser.MSG();
final boolean hasMessage = lib.PeekMessage(msg, null, 0, 0, 1);
if (hasMessage) {
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
@Test
@EnabledOnOs(OS.WINDOWS)
@Disabled("Only run manually")
void cameraConnectedIsSeenWithUser32() throws InterruptedException {
// This test demonstrate how to get events from library using User32 but better to use EdsGetEvent of library
final User32 lib = User32.INSTANCE;
final AtomicBoolean cameraEventCalled = new AtomicBoolean(false);
TestShortcutUtil.registerCameraAddedHandler(inContext -> {
log.warn("Camera added called {}", inContext);
cameraEventCalled.set(true);
return new NativeLong(0);
});
final WinUser.MSG msg = new WinUser.MSG();
for (int i = 0; i < 100; i++) {
Thread.sleep(50);
final boolean hasMessage = lib.PeekMessage(msg, null, 0, 0, 1);
if (hasMessage) {
log.warn("Had message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
Assertions.assertTrue(cameraEventCalled.get());
}
@Override
public Rectangle getFocusedWindow() {
HWND hwnd = user32.GetForegroundWindow();
RECT rect = new User32.RECT();
boolean success = user32.GetWindowRect(hwnd, rect);
return success ? rect.toRectangle() : null;
//return getFocusedRectangle();
}
public static boolean switchToWinOs(String title) {
HWND hwnd = User32.INSTANCE.FindWindow(null, title);
if (hwnd == null) {
return false;
} else {
focusWinOs(hwnd);
return true;
}
}
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();
}
@Override
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
int code = wParam.intValue();
boolean cancel = onKeyUpdate(SystemState.from(code), PressState.from(code), info.time, info.vkCode);
if (cancel) {
return new LRESULT(1);
}
Pointer ptr = info.getPointer();
long peer = Pointer.nativeValue(ptr);
return User32.INSTANCE.CallNextHookEx(getHookManager().getHhk(this), nCode, wParam, new LPARAM(peer));
}
/**
* Returns a map of process HWND's to their window titles.
*
* @return
*/
public static Map<HWND, String> getWindows() {
Map<HWND, String> map = new HashMap<HWND, String>();
User32.INSTANCE.EnumWindows(new WNDENUMPROC() {
@Override
public boolean callback(HWND hWnd, Pointer arg1) {
String wText = getWindowTitle(hWnd);
map.put(hWnd, wText);
return true;
}
}, null);
return map;
}
/**
* Sends a key-down input followed by a key-up input for the given character
* value c.
*
* @param c
*/
public static void pressKey(int c) {
INPUT input = new INPUT();
input.type = new DWORD(INPUT.INPUT_KEYBOARD);
input.input.setType("ki");
input.input.ki.wScan = new WORD(0);
input.input.ki.time = new DWORD(0);
input.input.ki.dwExtraInfo = new ULONG_PTR(0);
input.input.ki.wVk = new WORD(c);
input.input.ki.dwFlags = new DWORD(KEYEVENTF_KEYDOWN);
User32.INSTANCE.SendInput(new DWORD(1), (INPUT[]) input.toArray(1), input.size());
input.input.ki.wVk = new WORD(c);
input.input.ki.dwFlags = new DWORD(KEYEVENTF_KEYUP);
User32.INSTANCE.SendInput(new DWORD(1), (INPUT[]) input.toArray(1), input.size());
}
/**
* Sends a key-down input for the given character value c.
*
* @param c
*/
public static void sendKeyDown(int c) {
INPUT input = new INPUT();
input.type = new DWORD(INPUT.INPUT_KEYBOARD);
input.input.setType("ki");
input.input.ki.wScan = new WORD(0);
input.input.ki.time = new DWORD(0);
input.input.ki.dwExtraInfo = new ULONG_PTR(0);
input.input.ki.wVk = new WORD(c);
input.input.ki.dwFlags = new DWORD(KEYEVENTF_KEYDOWN);
User32.INSTANCE.SendInput(new DWORD(1), (INPUT[]) input.toArray(1), input.size());
}
/**
* Sends a key-up input for the given character value c.
*
* @param c
*/
public static void sendKeyUp(int c) {
INPUT input = new INPUT();
input.type = new DWORD(INPUT.INPUT_KEYBOARD);
input.input.setType("ki");
input.input.ki.wScan = new WORD(0);
input.input.ki.time = new DWORD(0);
input.input.ki.dwExtraInfo = new ULONG_PTR(0);
input.input.ki.wVk = new WORD(c);
input.input.ki.dwFlags = new DWORD(KEYEVENTF_KEYUP);
User32.INSTANCE.SendInput(new DWORD(1), (INPUT[]) input.toArray(1), input.size());
}
private void setTransparent(Component w) {
this.componentHwnd = getHWnd(w);
this.settingWl = User32.INSTANCE.GetWindowLong(componentHwnd, WinUser.GWL_EXSTYLE);
int transparentWl = User32.INSTANCE.GetWindowLong(componentHwnd, WinUser.GWL_EXSTYLE) |
WinUser.WS_EX_LAYERED |
WinUser.WS_EX_TRANSPARENT;
User32.INSTANCE.SetWindowLong(componentHwnd, WinUser.GWL_EXSTYLE, transparentWl);
}
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);
}
private static String getGamePath() {
return WindowUtils.getAllWindows(false).stream().filter(window -> {
char[] className = new char[512];
User32.INSTANCE.GetClassName(window.getHWND(), className, 512);
return Native.toString(className).equals("POEWindowClass");
}).map(it -> {
String filePath = it.getFilePath();
return StringUtils.substringBeforeLast(filePath, "\\");
}).findAny().orElse(null);
}
public static void main(String[] args) throws Exception {
HOOKPROC hookProc = new HOOKPROC_bg();
HINSTANCE hInst = Kernel32.INSTANCE.GetModuleHandle(null);
User32.HHOOK hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, hookProc, hInst, 0);
if (hHook == null)
return;
User32.MSG msg = new User32.MSG();
System.err.println("Please press any key ....");
while (true) {
User32.INSTANCE.GetMessage(msg, null, 0, 0);
}
}
/**
* Load user32 library.
*
* @return JNA interface of the user32 library
*/
private static User32 loadUser32() {
try {
//LOGGER.debug("Load user32 library.");
return Native.load(User32.class);
//return Native.load(User32.class, W32APIOptions.DEFAULT_OPTIONS);
//return Native.load(User32.class, W32APIOptions.UNICODE_OPTIONS);
} catch (UnsatisfiedLinkError ex) {
LOGGER.warn("Can't load user32 library.", ex);
return null;
}
}
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 Rectangle getRectangle(HWND hwnd, int winNum) {
RECT rect = new User32.RECT();
boolean success = user32.GetWindowRect(hwnd, rect);
return success ? rect.toRectangle() : null;
}
private static void focusWinOs(HWND hwnd) {
User32.INSTANCE.ShowWindow(hwnd, 9); // SW_RESTORE
User32.INSTANCE.SetForegroundWindow(hwnd);
}
/**
* Update event structure.
*/
private void dispatchEvent() {
User32.INSTANCE.TranslateMessage(msg);
User32.INSTANCE.DispatchMessage(msg);
}
/**
* @return Title of the active window.
*/
public static String getCurrentWindowTitle() {
return getWindowTitle(User32.INSTANCE.GetForegroundWindow());
}