private void createHotKeys() { Thread keys = new Thread(() -> { keysThreadID = Kernel32.INSTANCE.GetCurrentThreadId(); User32.INSTANCE.RegisterHotKey(new HWND(Pointer.NULL), 1, MOD_WIN | MOD_NOREPEAT, VK_E); MSG msg = new MSG(); while (User32.INSTANCE.GetMessage(msg, new HWND(Pointer.NULL), 0, 0) != 0 && running) { if (msg.message == WM_HOTKEY) { try { switch (msg.wParam.intValue()) { case 1: new ProcessBuilder("explorer.exe", ",").start(); break; } } catch (IOException e) { e.printStackTrace(); } } } User32.INSTANCE.UnregisterHotKey(Pointer.NULL, 1); }); keys.start(); }
/** * Captures the window. * * @param hwnd The window to capture. * @param filename Name to save the output into. * @throws AWTException Robot exception. * @throws IOException IO Exception. */ public static void capture(final WinDef.HWND hwnd, final String filename) throws AWTException, IOException, Win32Exception { ensureWinApiInstances(); WinDef.RECT rect = new WinDef.RECT(); if (!user32.GetWindowRect(hwnd, rect)) { throw new Win32Exception(kernel32.GetLastError()); } Rectangle rectangle = new Rectangle(rect.left, rect.top, rect.right -rect.left, rect.bottom -rect.top); BufferedImage image = new Robot().createScreenCapture(rectangle); ImageIO.write(image, "png", new File(filename)); }
@Test public void testStartProcess_Starts_Notepad() { try { Utils.startProcess("notepad.exe"); this.andRest(); WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, getLocal("notepad.title")); assertTrue("startProcess - no process", hwnd != null); } catch (IOException io) { assertTrue("startProcess: " + io.getMessage(), false); } assertTrue("startProcess", true); }
@Test public void testQuitProcess_Quits_Notepad() { try { Utils.startProcess("notepad.exe"); WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, getLocal("notepad.title")); if (hwnd != null) { Utils.quitProcess(hwnd); } } catch (IOException io) { assertTrue("quitProcess: " + io.getMessage(), false); } assertTrue("quitProcess", true); }
@Test public void testCloseWindow_Closes_Notepad() { try { Utils.startProcess("notepad.exe"); WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, getLocal("notepad.title")); if (hwnd != null) { Utils.closeWindow(hwnd); } } catch (IOException io) { assertTrue("quitProcess: " + io.getMessage(), false); } assertTrue("quitProcess", true); }
/** * Gets the native window handles. * * @return the native window handles */ private void getNativeWindowHandles() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { HWND fgWindow = User32.INSTANCE.GetForegroundWindow(); int titleLength = User32.INSTANCE.GetWindowTextLength(fgWindow) + 1; char[] title = new char[titleLength]; User32.INSTANCE.GetWindowText(fgWindow, title, titleLength); int awtCanvasHandle = (int) Pointer.nativeValue(fgWindow.getPointer()); setApplicationHandle(awtCanvasHandle); } }); }
/** * Executes a command. * TODO: list possible commands and arguments * * @param input * A command without its colon at the beginning * @return True if the command requests the program to exit. */ public boolean isExitAndExecute(String input) { String[] args = input.split(" "); String cmd = args[0]; if (cmd.equals("exit")) { return true; } else if (cmd.equals("focus")) { synchronized(mainWindow) { mainWindow.setVisible(true); mainWindow.toFront(); } } else if (cmd.equals("hide")) { List<HWND> windowsToHide = WindowsUtils.findByTitle(args[1]); for (HWND window : windowsToHide) { WindowsUtils.setVisible(window, false); } } return false; }
public static Map<String, WindowInfo> EnumerateWin32ChildWindows(HWND parentHwnd) { final Map<String, WindowInfo> infoList = new LinkedHashMap<String, WindowInfo>(); class ChildWindowCallback implements WinUser.WNDENUMPROC { @Override public boolean callback(HWND hWnd, Pointer lParam) { WindowInfo wi = new WindowInfo(hWnd, true); infoList.put(wi.hwndStr, wi); return true; } } Api.User32Ex.instance.EnumChildWindows(parentHwnd, new ChildWindowCallback(), new Pointer(0)); return infoList; }
public static String getControlText(HWND hCtrl) { String text = null; if (isHWnd(hCtrl)) { int textLength = user32.SendMessage(hCtrl, WM_GETTEXTLENGTH, 0, 0); if (textLength == 0) { text = ""; } else { char[] lpText = new char[textLength + 1]; if (textLength == user32.SendMessage(hCtrl, WM_GETTEXT, lpText.length, lpText)) { text = new String(lpText, 0, textLength); } } } return text; }
private void registerAllHotKeys() // must register hot keys in the same thread that is watching for hotkey messages { //System.out.println("registering hotkeys"); for (TargetKeyPress tkp : KeyboardHook.targetList) { //BOOL WINAPI RegisterHotKey(HWND hWnd, int id, UINT fsModifiers, UINT vk); int modifiers = User32.MOD_NOREPEAT; if (tkp.withShift) modifiers = modifiers | User32.MOD_SHIFT; if (tkp.withCtrl) modifiers = modifiers | User32.MOD_CONTROL; if (tkp.withAlt) modifiers = modifiers | User32.MOD_ALT; //System.out.println("RegisterHotKey " + tkp.idNumber + "," + modifiers + ", " + tkp.targetKeyCode); if (!User32.INSTANCE.RegisterHotKey(new WinDef.HWND(Pointer.NULL), tkp.idNumber, modifiers, tkp.targetKeyCode)) { System.out.println("Couldn't register hotkey " + tkp.targetKeyCode); } } }
@Test public void getClassName() { Assert.assertNull(Win.getClassName(NOTEPAD_TITLE)); Assert.assertNull(Win.getClassName((HWND) null)); // run notepad int pid = runNotepad(); HWND hWnd = Win.getHandle_(NOTEPAD_TITLE); Assert.assertNotNull(hWnd); Assert.assertEquals(NOTEPAAD_CLASS_NAME, Win.getClassName(NOTEPAD_TITLE)); Assert.assertEquals(NOTEPAAD_CLASS_NAME, Win.getClassName(hWnd)); // close notepad closeNotepad(pid); Assert.assertNull(Win.getClassName(NOTEPAD_TITLE)); Assert.assertNull(Win.getClassName(hWnd)); }
private static void createWindow(final File f) { SwingUtilities.invokeLater(() -> { if (!f.isDirectory()) // if the file was changed or deleted before this could execute, exit return; final BDWindow w = new BDWindow(f); windows.add(w); w.pack(); w.setVisible(true); threadPool.execute(() -> { // sets whether the windows blur the background behind them Settings.INSTANCE.blurBackground.addListener(enabled -> { ch.njol.betterdesktop.win32.User32.enableBlur(w, enabled); }); // disables the windows from being hidden when "peeking" the desktop Settings.INSTANCE.excludeFromPeek.addListener(enabled -> { Dwmapi.setExcludedFromPeek(w, enabled); }); // prevents "show desktop" button from hiding the windows if (Settings.INSTANCE.showOnDesktop.get()) { final HWND progman = User32.INSTANCE.FindWindow("Progman", "Program Manager"); User32.INSTANCE.SetWindowLongPtr(new HWND(Native.getComponentPointer(w)), WinUser.GWL_HWNDPARENT, progman.getPointer()); // the following is required so that this setting actually does something - no idea why though try { Thread.sleep(100); } catch (final InterruptedException e1) {} w.setAlwaysOnTop(true); w.setAlwaysOnTop(false); } }); }); }
public static void setBlurBehind(final Window w, final boolean blur) { final HWND hwnd = new HWND(); hwnd.setPointer(Native.getComponentPointer(w)); // final int error = INSTANCE.DwmEnableBlurBehindWindow(hwnd, new Dwmapi.DWM_BLURBEHIND[] {new DWM_BLURBEHIND(blur)}); // System.out.println(error); }
public static void setExcludedFromPeek(final Window w, final boolean excluded) { final HWND hwnd = new HWND(); hwnd.setPointer(Native.getComponentPointer(w)); // final int error = INSTANCE.DwmSetWindowAttribute(hwnd, DWMWA_EXCLUDED_FROM_PEEK, new IntByReference(excluded ? 1 : 0), 4); // System.out.println(error); }
public static WindowHolder findAndShowWindow(String className, String windowsName) { HWND hWnd = user32.FindWindow(className, windowsName); if (hWnd == null) { System.out.println("there is no running calc app"); return null; } user32.ShowWindow(hWnd, User32.SW_SHOW); WINDOWINFO pwi = new WINDOWINFO(); WindowHolder windowHolder = new WindowHolder(hWnd, pwi); user32.SetForegroundWindow(hWnd); return windowHolder; }
public static WindowHolder findChildWindowByText(WindowHolder parenWindow, String text) { WinDef.DWORD fiveButton = new WinDef.DWORD(Long.parseLong(text)); WinDef.HWND fiveButtonWnd = user32.GetWindow(parenWindow.getParentWindow(), fiveButton); if (fiveButtonWnd == null) { return null; } WINDOWINFO pwi = new WINDOWINFO(); System.out.println(user32.GetWindowInfo(fiveButtonWnd, pwi)); WindowHolder windowHolder = new WindowHolder(fiveButtonWnd, pwi); return windowHolder; }
@Override public boolean callback(HWND hWnd, Pointer data) { char[] textBuffer = new char[512]; char[] textBuffer2 = new char[512]; User32.INSTANCE.GetClassName(hWnd, textBuffer, 512); User32.INSTANCE.GetWindowText(hWnd, textBuffer2, 512); String wText = Native.toString(textBuffer); String wText2 = Native.toString(textBuffer2); childList.add(hWnd); System.out.println("className: " + wText + " title: " + wText2); return true; }
public WindowHolder(HWND parentWindow, WINDOWINFO info) { super(); this.parentWindow = parentWindow; this.info = info; this.rect = info.rcWindow; this.clientRect = info.rcClient; }
public void reDraw(HWND hwnd, Window window) { this.hwnd = hwnd; if (icon != -1) { nvgDeleteImage(window.getNVGID(), icon); icon = -1; } if (icon == -1) { icon = Util.getIcon(hwnd, window); if (icon == -1) tryAgain = true; } }
@Override public void init() { super.init(); WindowManager.createWindow(handle, window, true); long hwndGLFW = glfwGetWin32Window(window.getID()); HWND hwnd = new HWND(Pointer.createConstant(hwndGLFW)); WindowProc proc = new WindowProc() { @Override public long invoke(long hw, int uMsg, long wParam, long lParam) { if (hw == hwndGLFW) switch (uMsg) { case WM_WINDOWPOSCHANGING: WINDOWPOS pos = new WINDOWPOS(new Pointer(lParam)); pos.flags |= SWP_NOZORDER | SWP_NOACTIVATE; pos.write(); break; } return org.lwjgl.system.windows.User32.DefWindowProc(hw, uMsg, wParam, lParam); } }; User32.INSTANCE.SetWindowLongPtr(hwnd, GWL_WNDPROC, Pointer.createConstant(proc.address())); User32Ext.INSTANCE.SetWindowLongPtr(hwnd, GWL_EXSTYLE, WS_EX_TOOLWINDOW); User32Ext.INSTANCE.SetWindowLongPtr(hwnd, GWL_STYLE, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); User32.INSTANCE.SetWindowPos(hwnd, new HWND(Pointer.createConstant(HWND_BOTTOM)), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); wallpaper = window.getResourceLoader().loadNVGTexture(getCurrentDesktopWallpaper(), true); TaskManager.addTask(() -> window.setVisible(true)); }
public static String getAppUserModelId(HWND hwnd) { IntByReference processID = new IntByReference(); User32.INSTANCE.GetWindowThreadProcessId(hwnd, processID); HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processID.getValue()); UINTByReference length = new UINTByReference(); Kernel32Ext.INSTANCE.GetApplicationUserModelId(hProcess, length, null); char[] modelID = new char[length.getValue().intValue()]; Kernel32Ext.INSTANCE.GetApplicationUserModelId(hProcess, length, modelID); return new String(Native.toString(modelID)); }
/** * Quits the given process. * * @param handle The handle to quit. */ public static void quitProcess(final WinDef.HWND handle) { ensureWinApiInstances(); user32.PostMessage(handle, WinUser.WM_QUIT, null, null); }
/** * Closes the given window. * * @param handle The handle of the window to close. */ public static void closeWindow(final WinDef.HWND handle) { ensureWinApiInstances(); user32.PostMessage(handle, WinUser.WM_CLOSE, null, null); }
@After public void tearDown() { // Must be a better way of doing this???? this.andRest(); WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, getLocal("notepad.title")); if (hwnd != null) { Utils.quitProcess(hwnd); } }
private boolean isActiveWindow(HWND wnd) { WINDOWINFO pwi = new WINDOWINFO(); pwi.size(); if (MyUser32.INSTANCE.GetWindowInfo(wnd, pwi)) { pwi.read(); return pwi.dwWindowStatus == 1; } return false; }
public static void setDimensions(String className, String windowName) throws SetWindowPositionError, WindowNotFoundException { HWND handle = User32.INSTANCE.FindWindowA(className, windowName); if(handle == null) { throw new WindowNotFoundException(className, windowName); } boolean success = User32.INSTANCE.SetWindowPos(handle, null, DEFAULT_WINDOW_X, DEFAULT_WINDOW_Y, DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT, 0x0000); if(success == false) { throw new SetWindowPositionError(windowName); } }
/** * Sets the application handle. * * @param HWND * the new application handle */ private void setApplicationHandle(int HWND) { if (HWND > 0) { appHandle = HWND; logger.info("-> Found application HWND: " + appHandle); init(appHandle); // Initialises the c++ core in the native dll initialized = true; } else { logger.severe("-> Couldnt retrieve the application handle!"); } }
public BufferedImage capture(final HWND hWnd) { final HDC hdcWindow = User32.INSTANCE.GetDC(hWnd); final HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow); final RECT bounds = new RECT(); User32Extra.INSTANCE.GetClientRect(hWnd, bounds); final int width = bounds.right - bounds.left; final int height = bounds.bottom - bounds.top; if (width * height <= 0) { return null; } final HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height); final HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap); GDI32Extra.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDIExtra.SRCCOPY); GDI32.INSTANCE.SelectObject(hdcMemDC, hOld); GDI32.INSTANCE.DeleteDC(hdcMemDC); final BITMAPINFO bmi = new BITMAPINFO(); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = WinGDI.BI_RGB; final Memory buffer = new Memory(width * height * 4); GDI32.INSTANCE.GetDIBits(hdcWindow, hBitmap, 0, height, buffer, bmi, WinGDI.DIB_RGB_COLORS); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, width, height, buffer.getIntArray(0, width * height), 0, width); GDI32.INSTANCE.DeleteObject(hBitmap); User32.INSTANCE.ReleaseDC(hWnd, hdcWindow); return image; }
/** * Finds all visible window threads. * * @return All visible window threads. */ public static List<HWND> findAll() { final List<HWND> windows = new LinkedList<>(); user32.EnumWindows(new User32.WNDENUMPROC() { @Override public boolean callback(HWND hWnd, Pointer arg) { if (user32.IsWindowVisible(hWnd)) { windows.add(hWnd); } return true; } }, null); return windows; }
/** * Finds windows using the PID of their process. * * @param pid The PID of the process. * @param windows A list of windows in which the search is performed. * @return The windows whose process has the given PID. */ public static List<HWND> findByPID(long pid, List<HWND> windows) { final List<HWND> filteredWindows = new LinkedList<>(); for (HWND window : windows) { IntByReference PIDRef = new IntByReference(); user32.GetWindowThreadProcessId(window, PIDRef); if (PIDRef.getValue() == pid) { filteredWindows.add(window); } } return filteredWindows; }
/** * Finds windows by their title. * * @param title A string contained in the title of the windows. * @param windows A list of windows in which the search is performed. * @return The windows having the given title. */ public static List<HWND> findByTitle(String title, List<HWND> windows) { final List<HWND> filteredWindows = new LinkedList<>(); for (HWND window : windows) { char[] windowText = new char[512]; user32.GetWindowText(window, windowText, 512); String currentTitle = Native.toString(windowText).trim(); if (!currentTitle.isEmpty() && currentTitle.contains(title)) { filteredWindows.add(window); } } return filteredWindows; }
@Override protected Size getActualSize() { final HWND control = User32.INSTANCE.GetDlgItem(handler, 0); final int[] rect = new int[4]; User32.INSTANCE.GetWindowRect(control, rect); final Size bsSize = new Size(rect[2] - rect[0], rect[3] - rect[1]); return bsSize; }
long getHwnd() { if (hwnd == 0) { try { hwnd = getField(src, "hwnd").getLong(src); _hwnd = new HWND(new Pointer(hwnd)); } catch (Exception exc) { exc.printStackTrace(); } } return hwnd; }
public void targetDragged() { HWND hwnd = Api.getWindowFromCursorPos();//new Point(targetX,targetY) String handleStr = Api.GetHandleAsString(hwnd); String classStr = WindowsEnumeratedXml.escapeXmlAttributeValue(Api.getWindowClassName(hwnd)); String parentStr = Api.GetHandleAsString(User32Ex.instance.GetParent(hwnd)); PointerByReference pointer = new PointerByReference(); User32Ex.instance.GetWindowThreadProcessId(hwnd, pointer); int pid = pointer.getPointer().getInt(0); String enumProperties = ""; if (!SynthuseDlg.config.isUiaBridgeDisabled()) { //System.out.println("useCachedRequests false"); if (uiabridge == null) uiabridge = new UiaBridge(); uiabridge.useCachedRequests(false); enumProperties = uiabridge.getWindowInfo(targetX, targetY, WindowInfo.UIA_PROPERTY_LIST_ADV); } String runtimeId = WindowInfo.getRuntimeIdFromProperties(enumProperties); String framework = WindowInfo.getFrameworkFromProperties(enumProperties); Rectangle rect = UiaBridge.getBoundaryRect(enumProperties); Point offsetPoint = WindowInfo.findOffset(rect, targetX, targetY); lblStatus.setText("rid:" + runtimeId + " " + framework + " class: " + classStr + " hWnd: " + handleStr + " parent: " + parentStr + " X,Y (" + targetX + ", " + targetY + ") offset: " + offsetPoint.x + ", " + offsetPoint.y); if (!lastDragHwnd.equals(handleStr) || !lastRuntimeId.equals(runtimeId)) { if (!lastDragHwnd.isEmpty()) { Api.refreshWindow(Api.GetHandleFromString(lastDragHwnd)); } lastDragHwnd = handleStr; lastRuntimeId = runtimeId; lastDragPid = pid; //lastDragHwnd = (hwnd + ""); if (framework.equals(UiaBridge.FRAMEWORK_ID_WPF) || framework.equals(UiaBridge.FRAMEWORK_ID_SILVER)) {// WPF and Silverlight apps don't expose their child windows boundaries the same as win32 apps Api.highlightWindow(Api.User32Ex.instance.GetDesktopWindow(), rect.x, rect.y, rect.x + rect.width, rect.y + rect.height); } else Api.highlightWindow(hwnd); XpathManager.buildXpathStatementThreaded(hwnd, enumProperties, textPane, xpathEvents); } }
public static String getClassName(final String title, final String text, final String control) { String className = null; if (StringUtils.isNotBlank(control)) { HWND hWnd = Control.getHandle_(title, text, control); if (hWnd != null) { className = getClassName(hWnd); } } return className; }
public static String getWindowText(HWND hWnd) { String text = null; if (isHWnd(hWnd)) { int textLength = user32.GetWindowTextLength(hWnd); if (textLength == 0) { text = ""; } else { char[] lpText = new char[textLength + 1]; user32.GetWindowText(hWnd, lpText, lpText.length); text = new String(lpText, 0, textLength); } } return text; }
private static HWND getNextSiblingHandle(final String title, final String text, final String control, final HWND itemHWND) { HWND nextSiblingHWND = null; if (itemHWND != null) { HWND hWnd = Control.getHandle_(title, text, control); if (hWnd != null) { nextSiblingHWND = Win32.user32.SendMessage(hWnd, TVM_GETNEXTITEM, new WPARAM(TVGN_NEXT), itemHWND); } } return nextSiblingHWND; }