Get active shell in SWT, even if the shell is not in focus

Display.getActiveShell() seems to only consider the shell as active if it is focused. If at the moment another application has focus, i.e. Display.getActiveShell() returns null .

I need a method that will always tell me that Shell is in focus of my SWT application, even if my SWT application is not in focus.

I quickly cracked this piece of code, although sometimes I get an AssertionException :

 public static Shell getActiveShell() { Display display = Display.getDefault(); Shell result = display.getActiveShell(); if (result == null) { Shell[] shells = display.getShells(); for (Shell shell : shells) { if (shell.getShells().length == 0) { if (result != null) throw new AssertionException(); result = shell; } } } return result; } 

Is there any standard way to approach this problem besides writing my own method?

+9
source share
1 answer

I had a similar problem recently, and although you probably found a solution in the meantime, I would like to share mine for future reference.

ShellActivationTracker adds a display filter that listens for Activate events and - if the activated widget is Shell - remembers the last activated Shell . This way you can request the (last) active shell, even if your application is currently not active / not focused.

 class ShellActivationTracker implements Listener { Shell activeShell; ShellActivationTracker(Display display) { activeShell = display.getActiveShell(); display.addFilter(SWT.Activate, this); } @Override public void handleEvent(Event event) { if (event.widget instanceof Shell) { activeShell = (Shell)event.widget; } } } 
+10
source

All Articles