从Java强制第三个窗口到前面

时间:2013-09-10 16:41:32

标签: java focus keyevent user32 hwnd

我正在开发一个Java应用程序,我想从一个我无法访问代码的具体窗口中获取并保存屏幕截图。为此,我有以下功能:

    public void nextStep(){
        final MyUser32 user32 = MyUser32.INSTANCE;
        user32.EnumWindows(new MyUser32.WNDENUMPROC() {

            public boolean callback(HWND hwnd, Pointer userData) {
                byte[] windowText = new byte[512];
                user32.GetWindowTextA(hwnd, windowText, 512);
                String wText = Native.toString(windowText);

            if(wText.contains(MyString)){
                System.out.println("Window hdwn: " + hwnd + " - Text: " + wText);
                User32.INSTANCE.ShowWindow(hwnd, WinUser.SW_MAXIMIZE);
                User32.INSTANCE.SetForegroundWindow(hwnd);
               //I ve tried with setFocus as well and does not work either
                capture();
            }
            return true;
        }
    }, null);
}

capture()方法如下:

public void capture(){
    Robot robot;
    try {
        robot = new Robot();
    } catch (AWTException e){
        throw new IllegalArgumentException("No robot");
    }
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyRelease(KeyEvent.VK_UP);
    robot.keyPress(KeyEvent.VK_PRINTSCREEN);
    robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
    robot.keyRelease(KeyEvent.VK_ALT);
    try {
        capt = (BufferedImage) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.imageFlavor);
        ImageIO.write(capt, "png", new File("captura.png"));
    } catch (HeadlessException | UnsupportedFlavorException | IOException e) {
        e.printStackTrace();
    }
}

MyUser32类如下:

public interface MyUser32 extends StdCallLibrary {
    MyUser32 INSTANCE = (MyUser32) Native.loadLibrary("user32", MyUser32.class);
    interface WNDENUMPROC extends StdCallCallback {
        boolean callback(HWND hwnd, Pointer arg);
    }
    boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg);
    int GetWindowTextA(HWND hwnd, byte[] lpString, int nMaxCount);
}

如果变量MyString有一个值,让我们说,“绘制”代码的这部分内容是:

- 列出所有活动窗口

- 对于标题中包含字符串“paint”的每一个:

*打印其信息,如标题和hwnd

*将它最大化到前面

*将其设置为前景窗口(同样,是)

*应用capture()方法,其执行:

首先按alt + up,最大化聚焦窗口,然后按alt + Capt。屏幕,仅捕获聚焦窗口并将其保存在剪贴板中。最后,它将捕获保存为“captura.png”

它适用于大多数窗口,例如paint或google chrome,但它对我有兴趣捕获的窗口效果不佳。有时它会将它带到前面,有时它没有任何明显的原因,但它永远不会被最大化或捕获,即使alt + up和alt + captScreen从我的物理键盘完美地工作,并且窗口的信息被打印永远都是。

有人知道如何强制第三个窗口获得焦点?我想问题就在那里,但我可能错了。此外,我没有任何其他窗口正在强制保持焦点。

非常感谢!

0 个答案:

没有答案
相关问题