1.5FLTK消息处理

在FLTK中是通过Fl_Widegt::handle(),虚拟函数来处理系统的消息。我们可以查看Fltk的源代码来分析系统是怎样处理一些系统消息的,如按钮的消息处理

/*******************************************************
Fl_Button中处理消息的代码,省略了具体的处理代码
*******************************************************/
int Fl_Button::handle(int event) {
    switch (event)
    {
        case FL_ENTER:
        case FL_LEAVE:     return 1;
        case FL_PUSH:         ……
        case FL_DRAG:        ……
        case FL_RELEASE:     ……
        case FL_SHORTCUT:   ……
        case FL_FOCUS :       ……
        case FL_UNFOCUS :    ……
        case FL_KEYBOARD :  ……
        default:return 0;
    }
}

可以看出了,系统的一些消息,都是在构件的handle()中进行处理的。 系统的主要消息有以下

鼠标事件消息 焦点事件消息
FL_PUSH FL_ENTER
FL_DRAG FL_LEAVE
FL_RELEASE FL_FOCUS
FL_MOVE FL_UNFOCUS
键盘事件消息 剪贴板事件消息
FL_KEYBOARD FL_PASTE
FL_SHORTCUT FL_SELECTIONCLEAR
构件事件消息
FL_DEACTIVATE FL_ACTIVE
FL_HIDE FL_SHOW

通过重载handle函数我们可扩充标准构件,下面是一个鼠标移动到上面就改变颜色的按钮的实现源代码。

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/fl_ask.H>

class EnterButton : public Fl_Button
{
    int handle(int e)
    {
        switch (e)
        {
              case  FL_ENTER:
                 color(FL_GREEN);
                 labelsize(18);
                 redraw();
                 return 1;
             case  FL_LEAVE:
                 color(FL_GRAY);
                 labelsize(18);
                 redraw();
                 return 1;
             default: return Fl_Button::handle(e);         
        }
    }

public:  
    EnterButton(int x, int y, int w, int h, const char *l ) : Fl_Button(x,y,w,h,l) {}
};

static void  cb(Fl_Widget* s,  void *data)
{
    fl_alert( "Hello World!" );
}

int main(int argc, char **argv)
{
    Fl_Window* w  =  new  Fl_Window(130, 50);
    EnterButton *eBtn  =  new  EnterButton(25,50,120,25,"HelloWorld");
    eBtn->callback((Fl_Callback*)cb);
    w->end();
    w->show(argc, argv);
    return Fl::run();
}

运行显示效果如图:

Linux下演示(截屏时鼠标没有取到)