Colaboraciones en el Guille

Manejo del Notify Icon como en VS.2005 (VB6)

Manejando el Ballon Tool Tip

 

Fecha: 17/Feb/2006  (16/Feb/2006)
Autor: Carlos Ramos K. - esdecarlos@hotmail.com carakan@gmail.com

 


Bueno siendo mi primera colaboración lo haré para VB 6, soy DCE 2 estrellas, Boliviano y... al grano.

Hace meses que estoy usando el Visual Studio .NET 2005 Express Edition y me encontré con el nuevo notify icon con la posibilidad de mostrar un mensaje en forma de balón (Ballon Tool Tip),y que además podías hacer click en el para hacer alguna rutina, me gusto mucho pero, me pidieron unos prototipos para un programa (claro debían estar hechos en VB6) y quise meter esta herramientita para hacerla mas atractiva ,así que trate de modificar un código que encontré en el KB de MSDN Library 2003 pero que solamente lo explicaba para los sistemas operativos Win 98 y NT.

Entonces tuve que mover cielos y mares para poder encontrar las modificaciones para que fuese compatible con el ballon y lo encontré pero toda esa documentación era dirigida a C, pero no fue mucho esfuerzo trasladarlo a VB, hice mis pruebas en Windows XP (muy pocas) y resulta, para un ejemplo les muestro la corrida :-) :

Notyfi icon con Ballon Tool Tip en VB 6

A continuación les va el código:

Option Explicit
' Esta es la Estructura que necesita InitCommonControlsEx
Private Type tagINITCOMMONCONTROLSEX
    dwSize As Long
    dwICC As Long
End Type
' Aqui estan los tipos de inicializacion de temas
Private Const ICC_LISTVIEW_CLASSES = &H1          ' listview, header
Private Const ICC_TREEVIEW_CLASSES = &H2          ' treeview, tooltips
Private Const ICC_BAR_CLASSES = &H4               ' toolbar, statusbar, trackbar, tooltips
Private Const ICC_TAB_CLASSES = &H8               ' tab, tooltips
Private Const ICC_UPDOWN_CLASS = &H10             ' updown
Private Const ICC_PROGRESS_CLASS = &H20           ' progress
Private Const ICC_HOTKEY_CLASS = &H40             ' hotkey
Private Const ICC_ANIMATE_CLASS = &H80            ' animate
Private Const ICC_WIN95_CLASSES = &HFF
Private Const ICC_DATE_CLASSES = &H100            ' month picker, date picker, time picker, updown
Private Const ICC_USEREX_CLASSES = &H200          ' comboex
Private Const ICC_COOL_CLASSES = &H400            ' rebar (coolbar) control

' Nueva funcion para iniciarlizar los temas de XP
Private Declare Function InitCommonControlsEx Lib "comctl32.dll" (lpInitCtrls As tagINITCOMMONCONTROLSEX) As Boolean
' Creamos una instancia de la estructura
Dim Ini As tagINITCOMMONCONTROLSEX
' Estructura del notify icon (Version 5 o posterior)
Private Type NOTIFYICONDATA ' declaracion del tipo de datos para notificar el Notify
    cbSize As Long
    hwnd As Long
    uID As Long
    uFlags As Long
    uCallbackMessage As Long
    hIcon As Long
    szTip As String * 128   'Desde aqui el nuevo notify
    dwState As Long
    dwStateMask As Long
    szInfo As String * 256
    uTimeout As Long        ' Este es compartido con (uVersion as Long)
    szInfoTitle As String * 64
    dwInfoFlags As Long
    ' guidItem As GUID (solo para la version 6)
End Type
' Para la version de el Notify icon (por defecto en XP ya esta inicializado)
Private Const NOTIFYICON_VERSION = 3

'constantes relacionas con el raton
Private Const WM_RBUTTONUP = &H205
Private Const WM_LBUTTONDBLCLK = &H203
Private Const WM_MOUSEMOVE = &H200
Private Const WM_USER = &H400
' Constantes relacionadas con el Ballon tool tip
Private Const NIN_BALLOONSHOW = (WM_USER + 2)
Private Const NIN_BALLOONHIDE = (WM_USER + 3)
Private Const NIN_BALLOONTIMEOUT = (WM_USER + 4)
' Esta es la que me gusta !!!!
Private Const NIN_BALLOONUSERCLICK = (WM_USER + 5)
'constantes de lo que queremos que muestre el Notify
Private Const NIF_ICON = &H2 ' queremos que muestre un Notify
Private Const NIF_MESSAGE = &H1 ' queremos que nos envie un mensaje
Private Const NIF_TIP = &H4 ' queremos que muestre un texto al posicionarnos encima
' Para la version 5
Private Const NIF_STATE = &H8 ' Devuelve el estado
Private Const NIF_INFO = &H10 ' Muestra un ballon en el notify icon

' Aqui las constantes para los Notifys de los ballons tips
' No muestra nada
Private Const NIIF_NONE = &H0
' Muestra un Notify de Informacion
Private Const NIIF_INFO = &H1
' Muestra un Notify de Precaucion
Private Const NIIF_WARNING = &H2
' Muestra un Notify de Error
Private Const NIIF_ERROR = &H3

'constantes para añadir, borrar o modificar el Notify
Private Const NIM_ADD = &H0             ' añadirlo a la barra de tareas
Private Const NIM_DELETE = &H2  ' borrarlo de la barra de tareas
Private Const NIM_MODIFY = &H1  ' modificarlo
' Para la version 5
Private Const NIM_SETFOCUS = &H3                ' Da el foco a la barra de tareas
Private Const NIM_SETVERSION = &H4      ' Asigna la version del Notify icon

' declaracion de la funcion
Private Declare Function Shell_NotifyIcon Lib "shell32" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Boolean

' Creamos una instancia del notify
Dim Notify As NOTIFYICONDATA

Private Sub btnCambiar_Click()
    Me.Hide
    ' Mensajillo Personalizado
    Notify.dwInfoFlags = NIIF_WARNING
    Notify.szInfoTitle = Me.txtTitulo.Text + Chr$(0)
    Notify.szInfo = "Usted lo que escribio es :" + vbCr + Me.txtMensaje.Text + Chr$(0)
    ' llamamos a NIM_MODIFY para mostrar de nuevo el ballon
    Shell_NotifyIcon NIM_MODIFY, Notify
End Sub

Private Sub Close_Click()
    Unload Me
End Sub

Private Sub Form_Initialize()
    Ini.dwSize = Len(Ini)
    Ini.dwICC = ICC_COOL_CLASSES
    ' Verifica si se inicializan correctamente los controles
    If Not InitCommonControlsEx(Ini) Then
        MsgBox "no se inicializo", vbCritical, "Error al inicializarse"
    End If
End Sub

Private Sub Form_Load()
    Me.Hide                                                                             ' Oculto el Form
    Notify.cbSize = Len(Notify)                                 ' Tamaño de la estructura
    Notify.hIcon = Me.Icon                      ' Notify mostrado en la barra
    Notify.hwnd = Me.hwnd                       ' Ventana que manipula el proceso
    Notify.uCallbackMessage = WM_MOUSEMOVE             ' Procedimiento que maneja los eventos
    Notify.szTip = "Notify con Ballon tool tip" & Chr$(0)     ' tool tip clasico
    Notify.uFlags = NIF_ICON Or NIF_MESSAGE Or NIF_INFO Or NIF_TIP ' los eventos que pueden hacerse
    ' Mensaje que se mostrara en el ballon tool tip
    Notify.szInfo = "Esto solo es una prueba" + vbCr + "Aprete aqui para ver el" + vbCr + "El formulario" + Chr$(0)
    ' Titulo del ballon tool tip
    Notify.szInfoTitle = "Prueba" & Chr$(0)
    ' Tiempo en milisegundos (Aunque no responde)
    Notify.uTimeout = 10 'Or NOTIFYICON_VERSION
    ' Hacer que se muestre el ballon tool tip al crearse
    Notify.dwInfoFlags = NIIF_INFO
    'Notify.uVersion = NOTIFYICON_VERSION (Si es que se quiere saber la version del Notify)
    Notify.uID = 1& ' un identificador del Notify
    Shell_NotifyIcon NIM_ADD, Notify ' llamamos a la funcion para añadirlo
End Sub

Private Sub Form_Unload(Cancel As Integer)
    ' al cerrar quitamos el Notyfi
    Shell_NotifyIcon NIM_DELETE, Notify
End Sub
Private Sub form_MouseMove(Button As Integer, Shift As Integer, x As Single, Y As Single)
    Static rec As Boolean
    Dim msg As Long
    msg = x / Screen.TwipsPerPixelX
    If rec = False Then 
    rec = True 
    Select Case msg
        Case WM_LBUTTONDBLCLK:             ' doble click con el boton izquierdo del raton
            Me.Show                                 ' mostramos el formulario
        Case WM_RBUTTONUP:
            Me.PopupMenu Menu             ' click con el boton secundario, mostramos el menu correspondiente
        Case NIN_BALLOONUSERCLICK:     'Click al ballon Tool Tip
            MsgBox "hizo click al ballon", vbExclamation, "Mensaje"
            Me.Show
    End Select
    rec = False
End If
End Sub

Private Sub Show_Click()
Me.Show
End Sub

Además que utilizo una nueva función de inicialización de los temas XP con la función InitCommonControlsEx que según dice es una versión mas reciente de la conocida InitCommonControls, espero que les sea de su agrado, debo aclarar que su función es solamente para Windows Me y superiores.

Esperando que voten por este artículo, tendré más sorpresas.

 


Fichero con el código de ejemplo: Carakan_Notify_icon.zip - 10 KB

(MD5 checksum: [450A19746800D5035D904C751075FD62])


ir al índice principal del Guille