com.sun.jna.platform.win32.User32 Java Examples

The following examples show how to use com.sun.jna.platform.win32.User32. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PowerPointHandler.java    From Quelea with GNU General Public License v3.0 8 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: Win32ProcessTools.java    From jpexs-decompiler with GNU General Public License v3.0 7 votes vote down vote up
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;
}
 
Example #3
Source File: ChatHelper.java    From MercuryTrade with MIT License 7 votes vote down vote up
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);
}
 
Example #4
Source File: RemoteDesktopDetector.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
    }
  }
}
 
Example #5
Source File: MouseEventReceiver.java    From Simplified-JNA with MIT License 6 votes vote down vote up
@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));
}
 
Example #6
Source File: WinUtil.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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);
}
 
Example #7
Source File: Mouse.java    From Simplified-JNA with MIT License 6 votes vote down vote up
/**
 * 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());
}
 
Example #8
Source File: RobotUtils.java    From karate with MIT License 6 votes vote down vote up
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();
}
 
Example #9
Source File: WindowsUtils.java    From RemoteSupportTool with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #10
Source File: MainTestKeyHook.java    From MercuryTrade with MIT License 5 votes vote down vote up
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);
    }
}
 
Example #11
Source File: FxDemo.java    From java-example with MIT License 5 votes vote down vote up
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;
}
 
Example #12
Source File: AppMain.java    From MercuryTrade with MIT License 5 votes vote down vote up
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);
}
 
Example #13
Source File: TestOpaque.java    From MercuryTrade with MIT License 5 votes vote down vote up
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);
    }
 
Example #14
Source File: AbstractAdrFrame.java    From MercuryTrade with MIT License 5 votes vote down vote up
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);
}
 
Example #15
Source File: UnityOpenFilePostHandler.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example #16
Source File: EventCameraTest.java    From canon-sdk-java with MIT License 5 votes vote down vote up
@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());
}
 
Example #17
Source File: Keyboard.java    From Simplified-JNA with MIT License 5 votes vote down vote up
/**
 * 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());
}
 
Example #18
Source File: Keyboard.java    From Simplified-JNA with MIT License 5 votes vote down vote up
/**
 * 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());
}
 
Example #19
Source File: Keyboard.java    From Simplified-JNA with MIT License 5 votes vote down vote up
/**
 * 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());
}
 
Example #20
Source File: EventFetcherLogicRunner.java    From canon-sdk-java with MIT License 5 votes vote down vote up
/**
 * <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);
    }
}
 
Example #21
Source File: WinUtil.java    From SikuliX1 with MIT License 5 votes vote down vote up
@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();
}
 
Example #22
Source File: Windows.java    From Simplified-JNA with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: KeyEventReceiver.java    From Simplified-JNA with MIT License 5 votes vote down vote up
@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));
}
 
Example #24
Source File: RobotUtils.java    From karate with MIT License 5 votes vote down vote up
public static boolean switchToWinOs(String title) {
    HWND hwnd = User32.INSTANCE.FindWindow(null, title);
    if (hwnd == null) {
        return false;
    } else {
        focusWinOs(hwnd);
        return true;
    }
}
 
Example #25
Source File: StageUtils.java    From xJavaFxTool-spring with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #26
Source File: DeviceHookThread.java    From Simplified-JNA with MIT License 5 votes vote down vote up
@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();
}
 
Example #27
Source File: Windows.java    From Simplified-JNA with MIT License 4 votes vote down vote up
/**
 * @param hWnd
 * @return Title of a given process HWND.
 */
public static String getWindowTitle(HWND hWnd) {
	char[] buffer = new char[MAX_TITLE_LENGTH * 2];
	User32.INSTANCE.GetWindowText(hWnd, buffer, MAX_TITLE_LENGTH);
	return Native.toString(buffer);
}
 
Example #28
Source File: Win32ProcessTools.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
public static boolean drawIcon(BufferedImage ret, WinDef.HICON hIcon, int diFlags) {

        WinDef.HDC hdcScreen = User32.INSTANCE.GetDC(null);
        WinDef.HDC hdcMem = Gdi32.INSTANCE.CreateCompatibleDC(hdcScreen);

        WinDef.HBITMAP bitmap = Gdi32.INSTANCE.CreateCompatibleBitmap(hdcScreen, ret.getWidth(), ret.getHeight());

        WinNT.HANDLE hbmOld = Gdi32.INSTANCE.SelectObject(hdcMem, bitmap);

        WinNT.HANDLE hBrush = Gdi32.INSTANCE.CreateSolidBrush(new WinDef.DWORD(0xffffff));
        WinDef.RECT rect = new WinDef.RECT();
        rect.left = 0;
        rect.top = 0;
        rect.right = ret.getWidth();
        rect.bottom = ret.getHeight();
        User32.INSTANCE.FillRect(hdcMem, rect, hBrush);
        Gdi32.INSTANCE.DeleteObject(hBrush);

        boolean ok = User32.INSTANCE.DrawIconEx(hdcMem, 0, 0, hIcon, ret.getWidth(), ret.getHeight(), new WinDef.UINT(0), new WinDef.HBRUSH(Pointer.NULL), diFlags);

        if (!ok) {
            return false;
        }

        for (int x = 0; x < ret.getWidth(); x++) {
            for (int y = 0; y < ret.getHeight(); y++) {
                int rgb = Gdi32.INSTANCE.GetPixel(hdcMem, x, y).intValue();
                int r = (rgb >> 16) & 0xff;
                int g = (rgb >> 8) & 0xff;
                int b = (rgb) & 0xff;
                rgb = (b << 16) + (g << 8) + r;
                ret.setRGB(x, y, rgb);
            }
        }

        Gdi32.INSTANCE.SelectObject(hdcMem, hbmOld);
        Gdi32.INSTANCE.DeleteObject(bitmap);
        Gdi32.INSTANCE.DeleteDC(hdcMem);
        User32.INSTANCE.ReleaseDC(null, hdcScreen);
        return true;
    }
 
Example #29
Source File: WinUtil.java    From SikuliX1 with MIT License 4 votes vote down vote up
private static Rectangle getRectangle(HWND hwnd, int winNum) {
  RECT rect = new User32.RECT();
  boolean success = user32.GetWindowRect(hwnd, rect);
  return success ? rect.toRectangle() : null;
}
 
Example #30
Source File: UI.java    From HubTurbo with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void getMainWindowHandle(String windowTitle) {
    if (PlatformSpecific.isOnWindows()) {
        mainWindowHandle = User32.INSTANCE.FindWindow(null, windowTitle);
    }
}