@Override protected void doKeyPress(final int keyCode, final boolean shifted) throws InterruptedException { logger.log(Level.FINER, "doKeyPress " + keyCode + " " + shifted); while (isCtrlKeyDown()) { Thread.sleep(100); } final int lParam = 0x00000001 | 0x50 /* scancode */<< 16 | 0x01000000 /* extended */; final WPARAM wparam = new WinDef.WPARAM(keyCode); final WPARAM wparamShift = new WinDef.WPARAM(KeyEvent.VK_SHIFT); final LPARAM lparamDown = new WinDef.LPARAM(lParam); final LPARAM lparamUp = new WinDef.LPARAM(lParam | 1 << 30 | 1 << 31); if (shifted) { User32.INSTANCE.PostMessage(handler, WM_KEYDOWN, wparamShift, lparamDown); } User32.INSTANCE.PostMessage(handler, WM_KEYDOWN, wparam, lparamDown); User32.INSTANCE.PostMessage(handler, WM_KEYUP, wparam, lparamUp); if (shifted) { User32.INSTANCE.PostMessage(handler, WM_KEYUP, wparamShift, lparamUp); } }
/** * Finds the given process in the process list. * * @param processEntry The process entry. * @param filenamePattern pattern matching the filename of the process. * @return The found process entry. */ public static boolean findProcessEntry (final Tlhelp32.PROCESSENTRY32.ByReference processEntry, final Pattern filenamePattern) { Kernel32 kernel32 = Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); boolean found = false; try { while (kernel32.Process32Next(snapshot, processEntry)) { String fname = Native.toString(processEntry.szExeFile); if (fname != null && filenamePattern.matcher(fname).matches()) { found = true; break; } } } finally { kernel32.CloseHandle(snapshot); } return found; }
/** * 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); }
@Test public void test_windowHandle_Calls_currentPropertyValue_From_Window() throws Exception { doAnswer(invocation -> { Object[] args = invocation.getArguments(); Object reference = (Object)args[0]; reference = 1245; return 1234; }).when(element).getPropertyValue(anyInt()); IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class); UIAutomation instance = new UIAutomation(mocked_automation); AutomationWindow wndw = new AutomationWindow( new ElementBuilder(element).window(window).itemContainer(container).automation(instance)); WinDef.HWND handle = wndw.getNativeWindowHandle(); verify(element, atLeastOnce()).getPropertyValue(anyInt()); }
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); }
/** * Checks if MassEffect3.exe is currently running. Uses native code. * * @return */ public static boolean isMassEffect3Running() { try { Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); boolean result = false; WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); try { while (kernel32.Process32Next(snapshot, processEntry)) { if ("MassEffect3.exe".toUpperCase().equals(Native.toString(processEntry.szExeFile).toUpperCase())) { result = true; break; } } } finally { kernel32.CloseHandle(snapshot); } ModManager.debugLogger.writeMessage("Mass Effect 3 is " + (result ? "" : "not ") + "currently running."); return result; } catch (Throwable t) { ModManager.debugLogger.writeErrorWithException("Critical native access exception: ", t); ModManager.debugLogger.writeError("Mod Manager will report that the game is not running to continue normal operations."); return false; } }
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 reloadSessions() { WinDef.HWND hwnd = new WinDef.HWND(Native.getWindowPointer(MainFrame.this)); WinDef.HMENU systemMenu = user32.GetSystemMenu(hwnd, new WinDef.BOOL(0)); if (sessionsSeparatorPos > 0) { for (int i = sessionsSeparatorPos; i >= 0; i--) { user32.DeleteMenu(systemMenu, new WinDef.UINT(i), User32.MF_BYPOSITION); } } mapCustomMenuHandlers.clear(); sessionsSeparatorPos = 0; try { File kittyHomeFile = new File(kittyHome); if (kittyHomeFile.isDirectory()) { for (File sessions : kittyHomeFile.listFiles()) { if (sessions.isDirectory() && "Sessions".equals(sessions.getName())) { sessionsSeparatorPos = loadSessions(systemMenu, mapCustomMenuHandlers, "", sessions, 0); if (sessionsSeparatorPos > 0) { WinUtil.InsertMenuSeparator(systemMenu, sessionsSeparatorPos, ++CUSTOM_MENU_LAST_ID); } } } } } catch (UnsupportedEncodingException ex) { throw new RuntimeException("Error reloading esssions!", ex); } }
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); } } }
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; }
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; }
public void run() { UIAutomation automation = UIAutomation.getInstance(); do { this.rest(); Point p = MouseInfo.getPointerInfo().getLocation(); logger.info(p.getX() + " - " + p.getY()); WinDef.POINT point = new WinDef.POINT(); point.x = (int) p.getX(); point.y = (int) p.getY(); try { AutomationElement elementUnder = automation.getElementFromPoint(point); logger.info("From point = " + elementUnder.getName()); AutomationElement elementFocus = automation.getFocusedElement(); logger.info("From focus = " + elementFocus.getName()); } catch (Exception ex) { logger.info(ex.getStackTrace()); } } while (true); }
/** * 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); }
/** * Returns whether the element is off screen. * @return True if off screen. * @throws AutomationException Call to Automation API failed. */ public WinDef.BOOL offScreen() throws AutomationException { WinDef.BOOLByReference bbr = new WinDef.BOOLByReference(); final int res = this.element.getCurrentIsOffscreen(bbr); if (res != 0) { throw new AutomationException(res); } return bbr.getValue(); }
/** * Returns whether the element is a content element. * @return True if content element. * @throws AutomationException Call to Automation API failed. */ public WinDef.BOOL isContentElement() throws AutomationException { WinDef.BOOLByReference bbr = new WinDef.BOOLByReference(); final int res = this.element.getCurrentIsContentElement(bbr); if (res != 0) { throw new AutomationException(res); } return bbr.getValue(); }
/** * Returns whether the element is a control element. * @return True if control element. * @throws AutomationException Call to Automation API failed. */ public WinDef.BOOL isControlElement() throws AutomationException { WinDef.BOOLByReference bbr = new WinDef.BOOLByReference(); final int res = this.element.getCurrentIsControlElement(bbr); if (res != 0) { throw new AutomationException(res); } return bbr.getValue(); }
/** * Returns whether the element is enabled. * @return True if enabled. * @throws AutomationException Call to Automation API failed. */ public WinDef.BOOL isEnabled() throws AutomationException { WinDef.BOOLByReference bbr = new WinDef.BOOLByReference(); final int res = this.element.getCurrentIsEnabled(bbr); if (res != 0) { throw new AutomationException(res); } return bbr.getValue(); }
/** * Gets the clickable point for the control. * * @return The clickable point. * @throws AutomationException Call to Automation API failed. */ public WinDef.POINT getClickablePoint() throws AutomationException { WinDef.POINT.ByReference pbr = new WinDef.POINT.ByReference(); WinDef.BOOLByReference br = new WinDef.BOOLByReference(); final int res = this.element.getClickablePoint(pbr, br); if (res != 0) { throw new AutomationException(res); } return new WinDef.POINT(pbr.x, pbr.y); }
/** * Gets the bounding rectangle of the control. * * @return The bounding rectangle. * @throws AutomationException Call to Automation API failed. */ public WinDef.RECT getBoundingRectangle() throws AutomationException { WinDef.RECT rect = new WinDef.RECT(); final int res = this.element.getCurrentBoundingRectangle(rect); if (res != 0) { throw new AutomationException(res); } return rect; }
/** * Sets transparency of the window. * @param alpha 0..255 alpha attribute. * @throws Win32Exception WIN32 call has failed. * @throws AutomationException Something is wrong in automation. */ public void setTransparency(int alpha) throws Win32Exception, AutomationException { WinDef.HWND hwnd = this.getNativeWindowHandle(); if (user32.SetWindowLong(hwnd, User32.GWL_EXSTYLE, User32.WS_EX_LAYERED) == 0) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } if (!user32.SetLayeredWindowAttributes(hwnd, 0, (byte)alpha, User32.LWA_ALPHA)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } }
/** * Waits for the application to accept input, i.e. not be idle. * @param timeout Timeout to wait for. */ public void waitForInputIdle(final int timeout) { if (user32 == null) { user32 = User32.INSTANCE; } user32.WaitForInputIdle(this.handle, new WinDef.DWORD(timeout)); }
/** * Closes the window. * * @param title Title of the window to close. */ public void close(final String title) { if (user32 == null) { user32 = User32.INSTANCE; } WinDef.HWND hwnd = user32.FindWindow(null, title); if (hwnd != null) { Utils.closeWindow(hwnd); } }
/** * Closes the window. * * @param titlePattern a pattern matching the title of the window to close */ public void close(final Pattern titlePattern) { if (user32 == null) { user32 = User32.INSTANCE; } WinDef.HWND hwnd = Utils.findWindow(null, titlePattern); if (hwnd != null) { Utils.closeWindow(hwnd); } }
/** * Quits the process. * * @param title Title of the window of the process to quit. */ public void quit(final String title) { if (user32 == null) { user32 = User32.INSTANCE; } WinDef.HWND hwnd = user32.FindWindow(null, title); if (hwnd != null) { Utils.quitProcess(hwnd); } }
/** * Quits the process. * * @param titlePattern a pattern matching the title of the window of the process to quit */ public void quit(final Pattern titlePattern) { if (user32 == null) { user32 = User32.INSTANCE; } final WinDef.HWND handle = Utils.findWindow(null, titlePattern); if (handle != null) { Utils.quitProcess(handle); } }
@After public void cleanUp() { while (true) { WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, getLocal("notepad.title")); if (hwnd == null) { break; } Utils.closeWindow(hwnd); } }
@Test public void testGetClickablePointForDesktop() throws AutomationException { AutomationElement root = instance.getRootElement(); WinDef.POINT empty = new WinDef.POINT(0, 0); assertTrue("root:" + root.getClickablePoint(), root.getClickablePoint().dataEquals(empty)); }
@Test public void testGetCurrentBoundingRectangleForDesktop() throws AutomationException { AutomationElement root = instance.getRootElement(); WinDef.RECT empty = new WinDef.RECT(); assertTrue("root:" + root.getBoundingRectangle(), !root.getBoundingRectangle().dataEquals(empty)); }
@Test(expected = AutomationException.class) public void testGetCurrentBoundingRectangle_Throws_Exception_When_Automation_Returns_False() throws AutomationException { IUIAutomationElement mocked = Mockito.mock(IUIAutomationElement.class); when(mocked.getCurrentBoundingRectangle(isA(WinDef.RECT.class))).thenReturn(-1); AutomationElement element = new AutomationElement(mocked); element.getBoundingRectangle(); }
@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); } }
@Test public void testClick_Never_Calls_Invoke_From_Pattern() throws Exception { AutomationElement element = Mockito.mock(AutomationElement.class); Invoke invoke = Mockito.mock(Invoke.class); when(element.getClickablePoint()).thenReturn(new WinDef.POINT(0,0)); AutomationToolBarButton ctrl = new AutomationToolBarButton(element, invoke); ctrl.click(); verify(invoke, never()).invoke(); }
private static void setShutdownPrivileges() { final WinNT.HANDLEByReference token = new WinNT.HANDLEByReference(); Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES, token); final WinNT.LUID luid = new WinNT.LUID(); Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_SHUTDOWN_NAME, luid); final WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED)); Advapi32.INSTANCE.AdjustTokenPrivileges(token.getValue(), false, tp, 0, null, new IntByReference(0)); }
/** * Finds the URL for the Proxy Auto-Configuration (PAC) file using WPAD. * This is merely a wrapper around * {@link WinHttp#WinHttpDetectAutoProxyConfigUrl(com.sun.jna.platform.win32.WinDef.DWORD, com.github.markusbernhardt.proxy.jna.win.WTypes2.LPWSTRByReference) * WinHttpDetectAutoProxyConfigUrl} * * <p> * This method is blocking and may take some time to execute. * * @param dwAutoDetectFlags * @return the url of the PAC file or {@code null} if it cannot be located * using WPAD method. */ public static String detectAutoProxyConfigUrl(WinDef.DWORD dwAutoDetectFlags) { WTypes2.LPWSTRByReference ppwszAutoConfigUrl = new WTypes2.LPWSTRByReference(); boolean result = false; try { result = WinHttp.INSTANCE.WinHttpDetectAutoProxyConfigUrl(dwAutoDetectFlags, ppwszAutoConfigUrl); } catch (LastErrorException ex) { if (ex.getErrorCode() == WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED) { // This error is to be expected. It just means that the lookup // using either DHCP, DNS or both, failed because there wasn't // a useful reply from DHCP / DNS. (meaning the site hasn't // configured their DHCP Server or their DNS Server for WPAD) return null; } // Something more serious is wrong. There isn't much we can do // about it but at least we would like to log it. Logger.log(WinHttpHelpers.class, Logger.LogLevel.ERROR, "Windows function WinHttpDetectAutoProxyConfigUrl returned error : {0}", ex.getMessage()); return null; } if (result) { return ppwszAutoConfigUrl.getString(); } else { return null; } }
@Before public void setUp() { addr = new WinDivertAddress(); addr.IfIdx = new WinDef.UINT(0); addr.SubIfIdx = new WinDef.UINT(1); addr.Direction = new WinDef.USHORT(OUTBOUND.getValue()); raw = parseHexBinary("45000051476040008006f005c0a856a936f274fdd84201bb0876cfd0c19f9320501800ff8dba0000170303" + "00240000000000000c2f53831a37ed3c3a632f47440594cab95283b558bf82cb7784344c3314"); payload = parseHexBinary("17030300240000000000000c2f53831a37ed3c3a632f47440594cab95283b558bf82cb7784344c3314"); packet = new Packet(raw, addr); }
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); }