Meo
Meo

Reputation: 12491

How to steal focus on Windows 7

I am trying to transfer focus from one instance of IntelliJ to another. Even though the window shows up on top of everything and the cursor starts blinking, the focus is actually in the previous window, and the icon is blinking in the taskbar.

Switching between frames of one process is fine, but switching to another process is the problem.

Windows 7 x64, jdk1.7.0_51

JFrame frame = WindowManager.getInstance().getFrame(project);

//the only reliable way I found to bring it to the top
boolean aot = frame.isAlwaysOnTop();
frame.setAlwaysOnTop(true);
frame.setAlwaysOnTop(aot);

int frameState = frame.getExtendedState();
if ((frameState & Frame.ICONIFIED) == Frame.ICONIFIED) {
    // restore the frame if it is minimized
    frame.setExtendedState(frameState ^ Frame.ICONIFIED);
}
frame.toFront();
frame.requestFocus();
//frame.requestFocusInWindow(); same behaviour as requestFocus

I also tried Robot, and creating new temporary Frame as was suggested in other questions with no luck.

Upvotes: 0

Views: 281

Answers (2)

Meo
Meo

Reputation: 12491

Seems like I used the Robot hack incorrectly before, because now it seems to work fine:

        try {
            //remember the last location of mouse
            final Point oldMouseLocation = MouseInfo.getPointerInfo().getLocation();

            //simulate a mouse click on title bar of window
            Robot robot = new Robot();
            robot.mouseMove(frame.getX(), frame.getY());
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

            //move mouse to old location
            robot.mouseMove((int) oldMouseLocation.getX(), (int) oldMouseLocation.getY());
        } catch (Exception ex) {
            //just ignore exception, or you can handle it as you want
        } finally {
            frame.setAlwaysOnTop(false);
        }

source: https://stackoverflow.com/a/7404378/685796

Upvotes: 1

LINEMAN78
LINEMAN78

Reputation: 2562

JFrame.setVisible(true) usually works for me in swing.

Upvotes: 0

Related Questions