Question

I'm developing a Swing application and I need to flash the Windows taskbar. I can't use frame.requestFocus() because I don't want to steal focus from any other application.

Was it helpful?

Solution

I don't know if it applies to newer versions of Windows, but the .toFront() method used to flash the window if none of the current VM's windows were in the foreground.

This means that calling frame.toFront() on a minimized frame would always make it flash...

OTHER TIPS

JNIWrapper with its winpack extension can do what you want.

The Demo on the site shows it in action.

You can either force-minimize your GUI and .toFront-en it:

        Gui.frame.setState(Frame.ICONIFIED);
        for (int i = 0; i < 3; i++) {
            Thread.sleep(10);
            Gui.frame.toFront();
            Thread.sleep(10);
            Gui.frame.setVisible(false);
            Thread.sleep(10);
            Gui.frame.toBack();
            Thread.sleep(10);
            Gui.frame.setVisible(true);
        }
        // be creative!!

which sadly will remove the focus from the active window. You could find out the active window and reactivate it afterwards. But still, the flashing will only last for about three seconds.

...or get down to the really root of the matter by using a DLL-call on FlashWindow. Calling dlls is not possible with clean Java code, you'll need the help of other programming languages, possible e.g. with JNA. Other than that, you could also write your own program in another language and call it from your Java application. I'll give an example in AutoHotkey below:

AutoHotkey Code:

    if 0 != 1       ; note: in ahk, 1 corresponds args[1] and 0 corresponds args.length
    {
        msgbox, There needs to be ONE parameter passed over to this file, which is the name of the window that should be flashed.
        ExitApp
    }
    programName = %1%
    winget, hWnd, ID, %programName%
    DllCall("FlashWindow",UInt,hWnd,Int,True)

compiled into a file called flash.exe, put into your Java working directory, you can call it from any function:

    Runtime.getRuntime().exec("./flash.exe \"" + MyJFrame.getTitle() + "\"");

Alternatively, one could use the AutoHotkey.dll and access it within the Javacode (there are guides on how to do it on the internet), so there'd be no need for any external exe files.

If you still have problems achieving the flashing in the windows taskbar, please let me know!

The best way to do this:

if (!isFocused()) {
        setVisible(false);
        setVisible(true);
    }

Using Swing per se, you very probably can't; that's a Widnows specific thing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top