Displaying a tooltip on demand

by Richard Russell, August 2012

As a rule, a tooltip is displayed when the mouse moves into the tool's rectangle and stays there for a specified minimum period of time; typically this is when the user 'hovers' the mouse over a control or other region of interest. However it is also possible to force a tooltip to display 'on demand', under the control of your program.

The code listing below demonstrates how to do that:

        INSTALL @lib$+"WINLIB5"
 
        SYS "SetWindowText", @hwnd%, "Click anywhere"
 
        REM!WC Windows Constants:
        CW_USEDEFAULT = &80000000
        TTM_ADDTOOL = &404
        TTM_TRACKACTIVATE = &411
        TTM_UPDATETIPTEXT = &40C
        TTS_ALWAYSTIP = 1
        TTS_BALLOON = 64
        TTS_NOPREFIX = 2
        WS_POPUP = &80000000
 
        hwndTT% = FN_createwindow("tooltips_class32", "", \
        \         CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, \
        \         0, WS_POPUP + TTS_NOPREFIX + TTS_ALWAYSTIP + TTS_BALLOON, 0)
        IF hwndTT% = 0 ERROR 100, "Couldn't create tooltip"
 
        DIM ToolInfo{cbSize%, uFlags%, hwnd%, uID%, rc{l%,t%,r%,b%}, \
        \      hinst%, lpszText%}
        ToolInfo.cbSize% = DIM(ToolInfo{})
        ToolInfo.hwnd% = @hwnd%
 
        ToolTipText$ = "" + CHR$0
        ToolInfo.lpszText% = !^ToolTipText$
        SYS "SendMessage", hwndTT%, TTM_ADDTOOL, 0, ToolInfo{}
 
        PROC_setfocus(@hwnd%)
        REPEAT
          WAIT 1
          MOUSE X%, Y%, B%
          IF B% PROCactivate
        UNTIL FALSE
        END
 
        DEF PROCactivate
        ToolTipText$ = "Hello tooltip!" + CHR$0
        ToolInfo.lpszText% = !^ToolTipText$
        SYS "SendMessage", hwndTT%, TTM_UPDATETIPTEXT, 0, ToolInfo{}
        SYS "SendMessage", hwndTT%, TTM_TRACKACTIVATE, 1, ToolInfo{}
        WAIT 100
        ToolTipText$ = "" + CHR$0
        ToolInfo.lpszText% = !^ToolTipText$
        SYS "SendMessage", hwndTT%, TTM_UPDATETIPTEXT, 0, ToolInfo{}
        ENDPROC

As shown, clicking anywhere will cause a balloon tooltip (available in Windows XP or later) to be displayed at the mouse position, and to remain displayed for one second. If the TTS_BALLOON style is omitted a regular tooltip will be displayed.