[SOLUCIONADO] ¿Cómo añadir dos botones al formulario?

Iniciado por Meta, 7 Abril 2018, 17:49 PM

0 Miembros y 3 Visitantes están viendo este tema.

Meta

Editado, volver a leer el post anterior donde pone Edito:.

Falta este donde encajarlo bien.
Código (cpp) [Seleccionar]
HWND btnOK = CreateWindowW(
L"BUTTON", // clase del control
L"OK",
WS_CHILD | WS_PUSBUTTON | WS_VISIBLE, // estilo del control. La clase button puede ser checkbox, radio, etc.
5, 5, // posición respecto del client area del parent
40, 20,  // dimensiones del control
hWnd,   // --> este es el handle de tu ventana principal
1, // este es el identificador de tu control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInstance,
nullptr);
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

srWhiteSkull

Vale, ahí lo puedes hacer también, pero con la función que te cité te sirve para cualquier componente, incluso ventanas y puedes usarla en cualquier parte del programa, por ejemplo en un evento, ya que la programación en Win32 es así, a base de eventos o mensajes.


Meta

Buenas:

Por fin.

Código (cpp) [Seleccionar]
case WM_CREATE:
{
HWND btnOK = CreateWindowW(
L"BUTTON", // Clase del control.
L"Abrir", // Etiqueta del botón.
WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
45, 135, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)101, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);

HWND btnOK2 = CreateWindowW(
L"BUTTON", // Clase del control.
L"Cerrar", // Etiqueta del botón.
WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
165, 135, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)102, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);
}


Me falta detallitos como centrar el formulario en el centro de la pantalla.

Ahora voy a por los comandos para abrir y cerrar la bandeja del lector.

Abrir:
Código (cpp) [Seleccionar]
mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);

Cerrar:
Código (cpp) [Seleccionar]
mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);

Para que funcione, antes hacer esto:




En el lenguaje C++ del CLR, este es su código.
Código (cpp) [Seleccionar]
private: System::Void button_Abrir_Click(System::Object^  sender, System::EventArgs^  e) {
label_Mensaje->Text = "Abriendo...";
Application::DoEvents();
mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);
label_Mensaje->Text = "Abierto.";
}

Para que funcione bien los eventos del Abriendo... y Abierto.

Sigo investigando.

Saludos y muchas gracias por todo a tod@s.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Meta

#24
Buenas de nuevo:

Teniendo el código completo que ya y por fin puse un label y dos botones gracias a estos enlaces y ayudas de ustedes.

https://msdn.microsoft.com/es-es/library/windows/desktop/ms632679(v=vs.85).aspx
https://msdn.microsoft.com/es-es/library/windows/desktop/bb775951(v=vs.85).aspx



Código commpleto.
Código (cpp) [Seleccionar]
#include "stdafx.h"
#include "Bandeja_Form_Win32_cpp.h"
#include "mmsystem.h" // No olvidar.

#define MAX_LOADSTRING 100

// Variables globales:
HINSTANCE hInst;                                // Instancia actual
WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal

// Declaraciones de funciones adelantadas incluidas en este módulo de código:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                    _In_opt_ HINSTANCE hPrevInstance,
                    _In_ LPWSTR    lpCmdLine,
                    _In_ int       nCmdShow)
{
   UNREFERENCED_PARAMETER(hPrevInstance);
   UNREFERENCED_PARAMETER(lpCmdLine);

   // TODO: colocar código aquí.

   // Inicializar cadenas globales
   LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
   LoadStringW(hInstance, IDC_BANDEJAFORMWIN32CPP, szWindowClass, MAX_LOADSTRING);
   MyRegisterClass(hInstance);

   // Realizar la inicialización de la aplicación:
   if (!InitInstance (hInstance, nCmdShow))
   {
       return FALSE;
   }

   HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_BANDEJAFORMWIN32CPP));

   MSG msg;

   // Bucle principal de mensajes:
   while (GetMessage(&msg, nullptr, 0, 0))
   {
       if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
       {
           TranslateMessage(&msg);
           DispatchMessage(&msg);
       }
   }

   return (int) msg.wParam;
}



//
//  FUNCIÓN: MyRegisterClass()
//
//  PROPÓSITO: registrar la clase de ventana.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
   WNDCLASSEXW wcex;

   wcex.cbSize = sizeof(WNDCLASSEX);

   wcex.style          = CS_HREDRAW | CS_VREDRAW;
   wcex.lpfnWndProc    = WndProc;
   wcex.cbClsExtra     = 0;
   wcex.cbWndExtra     = 0;
   wcex.hInstance      = hInstance;
   wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_BANDEJAFORMWIN32CPP));
   wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
   wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
   wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_BANDEJAFORMWIN32CPP);
   wcex.lpszClassName  = szWindowClass;
   wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

   return RegisterClassExW(&wcex);
}

//
//   FUNCIÓN: InitInstance(HINSTANCE, int)
//
//   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
//
//   COMENTARIOS:
//
//        En esta función, se guarda el identificador de instancia en una variable común y
//        se crea y muestra la ventana principal del programa.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
  hInst = hInstance; // Almacenar identificador de instancia en una variable global

  // #######################################################################
  // Redimensionar formulario a 300 x 300.
  HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
     CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, nullptr, nullptr, hInstance, nullptr);
  // #######################################################################

  if (!hWnd)
  {
     return FALSE;
  }

  ShowWindow(hWnd, nCmdShow);
  UpdateWindow(hWnd);

  return TRUE;
}

//
//  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PROPÓSITO:  procesar mensajes de la ventana principal.
//
//  WM_COMMAND  - procesar el menú de aplicaciones
//  WM_PAINT    - Pintar la ventana principal
//  WM_DESTROY  - publicar un mensaje de salida y volver
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   switch (message)
   {
// #######################################################################
// Crear botones Abrir y Cerrar.
case WM_CREATE:
{
HWND btnOK = CreateWindowW(
L"BUTTON", // Clase del control.
L"Abrir", // Etiqueta del botón.
WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
45, 135, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)101, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);

HWND btnOK2 = CreateWindowW(
L"BUTTON", // Clase del control.
L"Cerrar", // Etiqueta del botón.
WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
165, 135, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)102, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);

// Label o etiqueta.
HWND edit = CreateWindowW(
L"STATIC", // Clase del control.
L"Hola.", // Etiqueta del botón.
WS_CHILD | SS_SIMPLE | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
125, 55, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)103, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);
}

break;
// #######################################################################

   case WM_COMMAND:
       {
           int wmId = LOWORD(wParam);
           // Analizar las selecciones de menú:
           switch (wmId)
           {
           case IDM_ABOUT:
               DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
               break;
           case IDM_EXIT:
               DestroyWindow(hWnd);
               break;
           default:
               return DefWindowProc(hWnd, message, wParam, lParam);
           }
       }
       break;
   case WM_PAINT:
       {
           PAINTSTRUCT ps;
           HDC hdc = BeginPaint(hWnd, &ps);
           // TODO: Agregar cualquier código de dibujo que use hDC aquí...
           EndPaint(hWnd, &ps);
       }
       break;
   case WM_DESTROY:
       PostQuitMessage(0);
       break;
   default:
       return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

// Controlador de mensajes del cuadro Acerca de.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
   UNREFERENCED_PARAMETER(lParam);
   switch (message)
   {
   case WM_INITDIALOG:
       return (INT_PTR)TRUE;

   case WM_COMMAND:
       if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
       {
           EndDialog(hDlg, LOWORD(wParam));
           return (INT_PTR)TRUE;
       }
       break;
   }
   return (INT_PTR)FALSE;
}


Ahora mismo, debo introducir comandos a los botones y no tengo idea como hacerlo.

En el botón Abrir:
Código (cpp) [Seleccionar]

mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);



En el botón Cerrar:

Código (cpp) [Seleccionar]
mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);


Si todo marcha bien, habremos acabado.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Meta

Gracias.

He puesto este código. Lee los mensajes si o si de forma muy correcta. Probé este código de abajo para abrir la bandeja y da error al compilar.
// #################################################################### Begin.
case IDC_BUTTON_1:
// MessageBox(hWnd, L"Botón 1 pulsado", L"Ejemplo", MB_OK | MB_ICONINFORMATION);
// Mostrar mensaje.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Abriendo...  ");

// Abrir bandeja del lector.
mciSendString("set CDAudio door open", nullptr, 0, nullptr);

// Mostrar mensaje Abierto. Que es cuando ya finalizó.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Abierto.     ");
break;
case IDC_BUTTON_2:
// Mostrar mensaje.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Cerrando...  ");
// Cerrar bandeja del lector.
// mciSendString("set CDAudio closed open", nullptr, 0, nullptr);
// Mostrar mensaje.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Cerrado.     ");
break;
// #################################################################### End.


Errores:
Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido
Error (activo)   E0167   un argumento de tipo "const char *" no es compatible con un parámetro de tipo "LPCWSTR"   Bandeja_Form_Win32_cpp   c:\Users\usuario\Documents\Visual Studio 2017\Projects\Bandeja_Form_Win32_cpp\Bandeja_Form_Win32_cpp\Bandeja_Form_Win32_cpp.cpp   201   


Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido
Error   C2664   'MCIERROR mciSendStringW(LPCWSTR,LPWSTR,UINT,HWND)': el argumento 1 no puede convertirse de 'const char [22]' a 'LPCWSTR'   Bandeja_Form_Win32_cpp   c:\users\usuario\documents\visual studio 2017\projects\bandeja_form_win32_cpp\bandeja_form_win32_cpp\bandeja_form_win32_cpp.cpp   201
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Meta

Buenas:

Ya funciona al 100 %. Solo falta pulir algunas cosas como iniciar el formulario en el centro de la pantalla y cambiar el tamaño del texto de la etiqueta STATIC.

Dejo el código completo aquí por si alguien lo necesita o solo le pica la curiosidad.

Código (cpp) [Seleccionar]
#include "stdafx.h"
#include "Bandeja_Form_Win32_cpp.h"
#include "mmsystem.h" // No olvidar.

#define MAX_LOADSTRING 100
#define IDC_BUTTON_1 201 // No olvidar.
#define IDC_BUTTON_2 202 // No olvidar.
#define IDC_STATIC_1 303 // No olvidar.

// Variables globales:
HINSTANCE hInst;                                // Instancia actual
WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal

// Declaraciones de funciones adelantadas incluidas en este módulo de código:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: colocar código aquí.

    // Inicializar cadenas globales
    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadStringW(hInstance, IDC_BANDEJAFORMWIN32CPP, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Realizar la inicialización de la aplicación:
    if (!InitInstance (hInstance, nCmdShow))
    {
        return FALSE;
    }

    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_BANDEJAFORMWIN32CPP));

    MSG msg;

    // Bucle principal de mensajes:
    while (GetMessage(&msg, nullptr, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}



//
//  FUNCIÓN: MyRegisterClass()
//
//  PROPÓSITO: registrar la clase de ventana.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEXW wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_BANDEJAFORMWIN32CPP));
    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_BANDEJAFORMWIN32CPP);
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    return RegisterClassExW(&wcex);
}

//
//   FUNCIÓN: InitInstance(HINSTANCE, int)
//
//   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
//
//   COMENTARIOS:
//
//        En esta función, se guarda el identificador de instancia en una variable común y
//        se crea y muestra la ventana principal del programa.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   hInst = hInstance; // Almacenar identificador de instancia en una variable global

   // ################################################################### Begin.
   // Redimensionar formulario a 300 x 300.
   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, nullptr, nullptr, hInstance, nullptr);
   // #################################################################### End.

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PROPÓSITO:  procesar mensajes de la ventana principal.
//
//  WM_COMMAND  - procesar el menú de aplicaciones
//  WM_PAINT    - Pintar la ventana principal
//  WM_DESTROY  - publicar un mensaje de salida y volver
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
// ################################################################### Begin.
// Crear botones Abrir, Cerrar y mostrar mensajes.
case WM_CREATE:
{
HWND btnOK = CreateWindowW(
L"BUTTON", // Clase del control.
L"Abrir", // Etiqueta del botón.
WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
45, 135, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)201, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);

HWND btnOK2 = CreateWindowW(
L"BUTTON", // Clase del control.
L"Cerrar", // Etiqueta del botón.
WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
165, 135, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)202, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);

// Label o etiqueta.
HWND edit = CreateWindowW(
L"STATIC", // Clase del control.
L"Hola.", // Etiqueta del botón.
WS_CHILD | SS_SIMPLE | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
125, 55, // Posición respecto del client area del parent.
75, 23, // Dimensiones del control.
hWnd, // --> Este es el handle de la ventana principal.
(HMENU)303, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
hInst,
nullptr);
}

break;
// #################################################################### End.

    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            // Analizar las selecciones de menú:
            switch (wmId)
            {
// #################################################################### Begin.
case IDC_BUTTON_1:
// MessageBox(hWnd, L"Botón 1 pulsado", L"Ejemplo", MB_OK | MB_ICONINFORMATION);
// Mostrar mensaje.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Abriendo...  ");

// Abrir bandeja del lector.
mciSendString(L"set CDAudio door open", nullptr, 0, nullptr);

// Mostrar mensaje Abierto. Que es cuando ya finalizó.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Abierto.     ");
break;
case IDC_BUTTON_2:
// Mostrar mensaje.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Cerrando...  ");
// Cerrar bandeja del lector.
mciSendString(L"set CDAudio door closed", nullptr, 0, nullptr);
// Mostrar mensaje.
SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Cerrado.     ");
break;
// #################################################################### End.
            case IDM_ABOUT:
                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
                break;
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
            EndPaint(hWnd, &ps);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Controlador de mensajes del cuadro Acerca de.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}


Saludos camaradas. ;)
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/