Search code examples
c++macosuser-interfacefltk

FLTK: Event when a window gets focus on MacOS


Using FLTK, I'm writing a desktop application which uses multiple windows. The application manages a list of open windows and shows them in the menu with these lines:

for( int i = 0; i < windows.size(); ++i ) {
    menu->add(("&Windows/"+windows[i].name).c_str(), 0, MyMenuCallback);
}

Now I want to set a checkmark in front of the name of the top-most window:

flags = FL_MENU_TOGGLE|FL_MENU_VALUE;
menu->add(("&Windows/"+windows[i].name).c_str(), 0, MyMenuCallback, 0, flags);

I'm stuck at installing an event handler that gets called whenever the top-most window changes. I was hoping Fl::add_handler( &genericEventHandler ); would get called whenever focus changes, but that is not the case. So, my question is: How do I get notified, when the focus of my windows changes?


Solution

  • You should subclass Fl_Window to override its handle method to monitor FL_FOCUS and FL_UNFOCUS events. Here is a sample:

    class MyWindow : public Fl_Window {
    public:
        MyWindow(int X,int Y,int W,int H, const char* title) : Fl_Window (X, Y, W, H, title) {}
    
        int handle(int e) {
            switch(e) {
                case FL_FOCUS:
                    std::cout << "Window " << label() << " is focused" << std::endl;
                    break;
                case FL_UNFOCUS:
                    std::cout << "Window " << label() << " has lost focus" << std::endl;
                    break;
            }
            return(Fl_Window::handle(e));
        }
    };
    
    int main() {
        MyWindow win1(100, 100, 200,200, "Window 1");
        win1.show();
    
        MyWindow win2(350, 100, 200,200, "Window 2");
        win2.show();
    
        return Fl::run();
    }