Get Active Shell in SWT, even if the Shell is not on focus Get Active Shell in SWT, even if the Shell is not on focus windows windows

Get Active Shell in SWT, even if the Shell is not on focus


Recently, I had a similar problem and though you probably found a solution in the meanwhile, I'd like to share mine for future reference.

The ShellActivationTracker adds a display filter that listens for Activate events and - if the activated widget is a Shell - remembers the most recently activated Shell. Thus you can query the (last) active shell even if your application is currently not active/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;    }  }}