Greg Ercolano wrote:

>       Note that with this technique, 'this' can be passed to the
>       callback, so that it has access to this instance of the class. eg:
> 
>     static void Sample_Callback(Fl_Widget*, void *data) {
>       MyMenuBar *mmb = (MyMenuBar*)data;      // get 'this'
>       mmb->xxx();                             // now can access non-static 
> class elements/methods
>     }
>     [..]
>     MyMenuBar(int X,int Y,int W,int H):Fl_Menu_Bar(X,Y,W,H) {
>       add("&File/&Sample", 0, Sample_Callback, (void*)this); // <-- pass 
> 'this' to cb
>     }

    Here's an example that shows this in action.

    This opens two windows, each with its own instance of the custom
    menubar. Each menubar instance has unique, instance specific data
    that the static callback can access when the File -> Do Callback
    item is chosen by the user in each window:

---- snip
#include <stdio.h>
#include <time.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Menu_Bar.H>
//
// Example of derived menubar class with callback that can access class 
instance data -erco 12/07/10
//
class MyMenuBar : public Fl_Menu_Bar {
    const char *id_;                    // instance-specific data
public:
    void id(const char* val) { id_ = val; }
    const char* id() const   { return(id_); }
    static void MenuCallback(Fl_Widget *, void *data) {
        // Show how we can access instance-specific data
        MyMenuBar *mmb = (MyMenuBar*)data;
        printf("Sample callback, instance '%s'\n", mmb->id());
    }
    MyMenuBar(int X,int Y,int W,int H):Fl_Menu_Bar(X,Y,W,H) {
        add("&File/&Do Callback", 0, MenuCallback, (void*)this);        // 
passes 'this' to cb when invoked
    }
};
int main() {
    // WINDOW #1 + MENUBAR
    Fl_Window w1(0,0,400,400,"Window #1");
    MyMenuBar m1(0,0,400,25);
    m1.id("Menu #1");                   // set instance specific data
    w1.end();
    w1.show();

    // WINDOW #2 + MENUBAR
    Fl_Window w2(400,0,400,400,"Window #2");
    MyMenuBar m2(0,0,400,25);
    m2.id("Menu #2");                   // set instance specific data
    w2.end();
    w2.show();

    return(Fl::run());
}
---- snip
_______________________________________________
fltk mailing list
[email protected]
http://lists.easysw.com/mailman/listinfo/fltk

Reply via email to