SWT - event to reliably know, if shell user has switched to another shell

focus, shell, swt

Solution

Let's assume you have three shells. A main shell and two shells which can be opened from the main shell.

So the main shell should be notified when another shell gets activated. You can add a listener which waits for a specific event type (in the main shell):

    shell.addListener(SWT.Show, new Listener() {

        @Override
        public void handleEvent(Event e) {
            System.out.println("activated: " + e.text);
        }
    });

The other shells should fire (`notify`) this event when they got activated. For that you add a shell listener to the other two shells, and `fire` the event in the method `shellActivated()` with `o.notifyListeners();`.

    shell.addShellListener(new ShellAdapter() {
        @Override
        public void shellActivated(ShellEvent e) {
            Shell shellSrc = (Shell) e.getSource();
            Display display  = shellSrc.getDisplay();

            Event event = new Event();
            event.type = SWT.Show;
            event.text = "other shell 1";

            Shell[] shells = display.getShells();
            for(Shell o : shells) {
                o.notifyListeners(SWT.Show, event);
            }
        }
    });

When you activate one of the other two shells the main shell will be notified with the event type `SWT.Show`.

Problem

I need to know, when a user switches to another shell, by clicking in it. I tried `shellListener.shellDeactivated()` but this event is triggered, when the shell looses focus to it's own controls, means when a Control in the active Shell was clicked. This is not the intended behaviour, since I need to know, when another Shell was activated, instead of mine. Any Ideas?

Original source