elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Crear eventos en botones [Win API]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Crear eventos en botones [Win API]  (Leído 3,721 veces)
Alien-Z

Desconectado Desconectado

Mensajes: 177


C++ Programmer


Ver Perfil
Crear eventos en botones [Win API]
« en: 28 Agosto 2011, 22:30 pm »

Buenas:

Siguiendo el consejo de тαптяαпсє me he puesto a explorar Win API y he conseguido crear menus/sub-menus, botones y edit aparte de utilizar algunas funciones para toquetear archivos y leer datos básicos del disco duro (me pudo la curiosidad y pasé de la interfaz a otras cosas  :xD).

Bien, he podido crear eventos a los menus/sub-menus como se puede ver en este ejemplo:

Código
  1. case WM_COMMAND:
  2.            switch(LOWORD(wParam))
  3.            {
  4.                case item1_menu2:
  5.                    MessageBox(hwnd, "Mensaje de prueba", "Titulo del mensaje", MB_OK);
  6.                    break;
  7.                case item2_menu2:
  8.                    PostQuitMessage(0);
  9.                    break;
  10.            }
  11.            break;

Como sigo algunas guías en inglés por falta de material en castellano no comprendí muy bien lo que hace switch(LOWORD(wParam)) pero puedo suponer razonando que es algo asi como "al darle clic a ...", corregídme si me equivoco.

Ahora, he intentado crear un evento a un botón y un edit pero no lo consigo; aqui os dejo el código (en rojo lo correspondiente al botón, lo demás es lo que te da como plantilla Code::Blocks):

Citar
#include <windows.h>

/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
char szClassName[ ] = "CodeBlocksWindowsApp";

HINSTANCE mi_instance;

int WINAPI WinMain (HINSTANCE hThisInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpszArgument,
                     int nCmdShow)
{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */
    mi_instance = hThisInstance;

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "Code::Blocks Template Windows App",       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           544,                 /* The programs width */
           375,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nCmdShow);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}


/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
        case WM_CREATE:
        {
            HWND hwnd_boton1 = CreateWindowEx (NULL, "BUTTON", "Texto", WS_CHILD | WS_VISIBLE | WS_TABSTOP, 100, 100, 90, 25, hwnd, NULL, mi_instance, NULL);
            break;
        }


        case WM_DESTROY:
            PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
            break;
        default:                      /* for messages that we don't deal with */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}

Para crear el evento he añadido debajo del WM_CREATE esto otro basándome en los ejemplos de los tutoriales (en rojo señalo dónde me da error):

Citar
case WM_COMMAND:
        {
            if ((HWND)lParam==hwnd_boton1)
            {
                MessageBox(NULL, "Se ha presionado el boton", "Título", MB_OK | MB_ICONEXCLAMATION);
            }
            break;
        }

De ahi me surge otra duda: ¿Por qué para crear eventos en los menus se usa (LOWORD(wParam)) y en botones ((HWND)lParam==hwnd_boton1) si en ambos casos se hace "clic" para activar el evento?.

Gracias por adelantado. Saludos.


« Última modificación: 28 Agosto 2011, 22:45 pm por Alien-Z » En línea

Riki_89D


Desconectado Desconectado

Mensajes: 851


BCN CITY


Ver Perfil
Re: Crear eventos en botones [Win API]
« Respuesta #1 en: 31 Agosto 2011, 00:33 am »

Para crear un evento a un boton debes usar el mensaje WM_COMMAND,ademas te has dejado un parametro en la funcion CreateWindowEx,es el parametro antes de la instancion,pusiste NULL y alli lo que tienes que ponerle es un identificador para el boton,en un programa hay MUCHOS botones,el programa debe saber cual se pulsa no cres?¿,no hay mas que hacer un "cast" y listo!

aqui un ejemplo:


Código
  1.  
  2. typedef int IDBUTT;
  3.  
  4. ....
  5.  
  6. WinMain...
  7.  
  8.  
  9. WndProc(....)
  10. {
  11. IDBUTT Bot1 = 01;   //Identificador para el boton
  12.  
  13. switch (Mensajes)   //mensajes de la app
  14.  
  15. case WM_CREATE:
  16.  
  17. HWND hwnd_boton1 = CreateWindowEx (NULL, "BUTTON", "Texto", WS_CHILD | WS_VISIBLE | WS_TABSTOP, 100, 100, 90, 25, hwnd, (HMENU)Bot1, mi_instance, NULL);
  18.  
  19. break;
  20.  
  21.  
  22. case WM_COMMAND:
  23. if(wparam == Bot1)
  24. {
  25.  
  26.  
  27. //codigo que ejecutara al PULSAR el boton
  28.  
  29. }
  30.  
  31. break
  32.  
  33. ...y el resto
  34.  


pasate por la msdn y busca un poco en Google,hay mucha info de esto.



suerte


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Crear botones????
Diseño Gráfico
ROnsOcO 5 3,011 Último mensaje 20 Junio 2005, 01:21 am
por .Carlos
Crear botones
Java
yimc 1 2,397 Último mensaje 8 Marzo 2009, 23:50 pm
por Pablo Videla
Problema con eventos al crear controles por codigo
.NET (C#, VB.NET, ASP)
Zeroql 2 3,015 Último mensaje 14 Marzo 2010, 20:20 pm
por Zeroql
Crear n botones
Java
Tyrz 4 3,399 Último mensaje 22 Abril 2011, 10:59 am
por Tyrz
Crear un filtro para ver las conexiones de un usuario en el visor de eventos
Programación General
Nucleorion 0 2,175 Último mensaje 8 Octubre 2018, 15:18 pm
por Nucleorion
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines