Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: Meta en 7 Abril 2018, 17:49 pm



Título: [SOLUCIONADO] ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 17:49 pm
Hola:

He creado un formulario con Windows Form (Win32). Quiero añadir en él dos botones. Por ahora he hecho esto.

Paso 1:
(https://social.msdn.microsoft.com/Forums/getfile/1249949)

Paso 2:
(https://social.msdn.microsoft.com/Forums/getfile/1249950)

Pado 3:
(https://social.msdn.microsoft.com/Forums/getfile/1249951)

Se me genera códigos pero no se ve el formulario. Lo que demuestra se un engorro programar así hoy en día, pero hay empresas que si programan así y enseñan en algunas universidades les gusten a los alumnos o no.

Paso 4:
(https://social.msdn.microsoft.com/Forums/getfile/1249955)

Aquí lo dejo el formulario como si fuese por defeto 300x300 pero en realidad es muy grande para mi gusto.

Quiero hacer dos cosas. Poner el tamaño del formulario a 300 x 300 y introducir 2 botones. Quiero hacer.

Un botón se llama: Abrir y el otro Cerrar.

¿Cómo se hace?

Saludos.

PD: La verdad, no sabía que fuera tan coñazo, pesado, complicado en hacer lo que estoy pidiendo.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: ivancea96 en 7 Abril 2018, 17:58 pm
Revisa el post, no se ve nada.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 18:07 pm
Vuelve a cargar la página para que se vean las imágenes, son 4, cada paso una captura.

Si no se ve nada por mucho que hagas, me avisas y lo subo en otro lado.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: ivancea96 en 7 Abril 2018, 18:23 pm
Bueno, ocurre que los links de Microsoft a veces pasan primero por una web de selección de cuenta Microsoft, por lo que no e veía la imagen.

Por lo demás, probablemente te interesa más buscar un proyecto de ejemplo con lo que dices. Los controles con WinApi son bastante diferentes a con C# y otros frameworks.
https://msdn.microsoft.com/en-us/library/windows/desktop/hh298354%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 (https://msdn.microsoft.com/en-us/library/windows/desktop/hh298354%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396)


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 18:46 pm
Buenas:

Me alegro que ya se pueda ver als capturas de pantalla.

En todo el proyecto he encontrado el código para redimensionar la ventana aquí.

Código
  1.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  2.      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

Pisiste el enlace, pero no se parece nada para modificar las coordenadas X, Y, así pongo los valores a 300 x 300.

Dios mio, si que es complicado el santo formulario con el Win32. ;)

En el ejemplo que diste:
Código
  1. HWND hwndButton = CreateWindow(
  2.    L"BUTTON",  // Predefined class; Unicode assumed
  3.    L"OK",      // Button text
  4.    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
  5.    10,         // x position
  6.    10,         // y position
  7.    100,        // Button width
  8.    100,        // Button height
  9.    m_hwnd,     // Parent window
  10.    NULL,       // No menu.
  11.    (HINSTANCE)GetWindowLong(m_hwnd, GWL_HINSTANCE),
  12.    NULL);      // Pointer not needed.
  13.  

Es todo un reto.

Saludos.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: BloodSharp en 7 Abril 2018, 18:51 pm
Dios mio, si que es complicado el santo formulario con el Win32. ;)

Es todo un reto.

Si querés algo equivalente en C/C++ de C# o VB.NET tendrías que crear el proyecto con la opción de CLR que se vé en la primera imagen...


B#


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 19:04 pm
CLR es .net. Estoy haciendo pruebas con Win32, C++ nativo. ;)


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: ivancea96 en 7 Abril 2018, 19:31 pm
Buenas:

Me alegro que ya se pueda ver als capturas de pantalla.

En todo el proyecto he encontrado el código para redimensionar la ventana aquí.

Código
  1.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  2.      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

Pisiste el enlace, pero no se parece nada para modificar las coordenadas X, Y, así pongo los valores a 300 x 300.

Dios mio, si que es complicado el santo formulario con el Win32. ;)

En el ejemplo que diste:
Código
  1. HWND hwndButton = CreateWindow(
  2.    L"BUTTON",  // Predefined class; Unicode assumed
  3.    L"OK",      // Button text
  4.    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
  5.    10,         // x position
  6.    10,         // y position
  7.    100,        // Button width
  8.    100,        // Button height
  9.    m_hwnd,     // Parent window
  10.    NULL,       // No menu.
  11.    (HINSTANCE)GetWindowLong(m_hwnd, GWL_HINSTANCE),
  12.    NULL);      // Pointer not needed.
  13.  

Es todo un reto.

Saludos.

Más que complicado, es un workflow diferente, además de no orientado a objetos. Fíjate en la función CreateWindow y sus parámetros en MSDN, son muchos parámetros porque son muchas opciones, pero nada más.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 20:04 pm
Buenas:

Código
  1. HWND hwndButton = CreateWindow(
  2.    L"BUTTON",  // Predefined class; Unicode assumed
  3.    L"OK",      // Button text
  4.    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
  5.    10,         // x position
  6.    10,         // y position
  7.    100,        // Button width
  8.    100,        // Button height
  9.    m_hwnd,     // Parent window
  10.    NULL,       // No menu.
  11.    (HINSTANCE)GetWindowLong(m_hwnd, GWL_HINSTANCE),
  12.    NULL);      // Pointer not needed.

Código
  1.   HWND hWnd = CreateWindowW(
  2.   szWindowClass,
  3.   szTitle,
  4.   WS_OVERLAPPEDWINDOW,
  5.      CW_USEDEFAULT,
  6.   0,
  7.   CW_USEDEFAULT,
  8.   0,
  9.   nullptr,
  10.   nullptr,
  11.   hInstance,
  12.   nullptr);

Ahora mismo averiguando poner el formulario al tamaño de 300 x 300 que no logro ni para atrás.

Código
  1.   HWND hWnd = CreateWindowW(
  2.   szWindowClass,
  3.   szTitle,
  4.   WS_OVERLAPPEDWINDOW,
  5.      CW_USEDEFAULT,
  6.   0,
  7.   CW_USEDEFAULT,
  8.   0,
  9.   nullptr,
  10.   nullptr,
  11.   hInstance,
  12.   nullptr);


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 7 Abril 2018, 20:40 pm
...tienes que usar la función SetWindowPos()

https://msdn.microsoft.com/es-es/library/a1yzfz6d.aspx


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 21:19 pm
Buenas:

No se ni donde poner ese código.

aaaa.cpp:
Código
  1. // aaaa.cpp: define el punto de entrada de la aplicación.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "aaaa.h"
  6.  
  7. #define MAX_LOADSTRING 100
  8.  
  9. // Variables globales:
  10. HINSTANCE hInst;                                // Instancia actual
  11. WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
  12. WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal
  13.  
  14. // Declaraciones de funciones adelantadas incluidas en este módulo de código:
  15. ATOM                MyRegisterClass(HINSTANCE hInstance);
  16. BOOL                InitInstance(HINSTANCE, int);
  17. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  18. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  19.  
  20. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  21.                     _In_opt_ HINSTANCE hPrevInstance,
  22.                     _In_ LPWSTR    lpCmdLine,
  23.                     _In_ int       nCmdShow)
  24. {
  25.    UNREFERENCED_PARAMETER(hPrevInstance);
  26.    UNREFERENCED_PARAMETER(lpCmdLine);
  27.  
  28.    // TODO: colocar código aquí.
  29.  
  30.    // Inicializar cadenas globales
  31.    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  32.    LoadStringW(hInstance, IDC_AAAA, szWindowClass, MAX_LOADSTRING);
  33.    MyRegisterClass(hInstance);
  34.  
  35.    // Realizar la inicialización de la aplicación:
  36.    if (!InitInstance (hInstance, nCmdShow))
  37.    {
  38.        return FALSE;
  39.    }
  40.  
  41.    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_AAAA));
  42.  
  43.    MSG msg;
  44.  
  45.    // Bucle principal de mensajes:
  46.    while (GetMessage(&msg, nullptr, 0, 0))
  47.    {
  48.        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  49.        {
  50.            TranslateMessage(&msg);
  51.            DispatchMessage(&msg);
  52.        }
  53.    }
  54.  
  55.    return (int) msg.wParam;
  56. }
  57.  
  58.  
  59.  
  60. //
  61. //  FUNCIÓN: MyRegisterClass()
  62. //
  63. //  PROPÓSITO: registrar la clase de ventana.
  64. //
  65. ATOM MyRegisterClass(HINSTANCE hInstance)
  66. {
  67.    WNDCLASSEXW wcex;
  68.  
  69.    wcex.cbSize = sizeof(WNDCLASSEX);
  70.  
  71.    wcex.style          = CS_HREDRAW | CS_VREDRAW;
  72.    wcex.lpfnWndProc    = WndProc;
  73.    wcex.cbClsExtra     = 0;
  74.    wcex.cbWndExtra     = 0;
  75.    wcex.hInstance      = hInstance;
  76.    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_AAAA));
  77.    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  78.    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  79.    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_AAAA);
  80.    wcex.lpszClassName  = szWindowClass;
  81.    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  82.  
  83.    return RegisterClassExW(&wcex);
  84. }
  85.  
  86. //
  87. //   FUNCIÓN: InitInstance(HINSTANCE, int)
  88. //
  89. //   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
  90. //
  91. //   COMENTARIOS:
  92. //
  93. //        En esta función, se guarda el identificador de instancia en una variable común y
  94. //        se crea y muestra la ventana principal del programa.
  95. //
  96. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  97. {
  98.   hInst = hInstance; // Almacenar identificador de instancia en una variable global
  99.  
  100.   HWND hWnd = CreateWindowW(
  101.   szWindowClass,
  102.   szTitle,
  103.   WS_OVERLAPPEDWINDOW,
  104. CW_USEDEFAULT,
  105.   0,
  106.   CW_USEDEFAULT,
  107.   0,
  108.   nullptr,
  109.   nullptr,
  110.   hInstance,
  111.   nullptr);
  112.  
  113.   if (!hWnd)
  114.   {
  115.      return FALSE;
  116.   }
  117.  
  118.   ShowWindow(hWnd, nCmdShow);
  119.   UpdateWindow(hWnd);
  120.  
  121.   return TRUE;
  122. }
  123.  
  124. // ######################################################################
  125.  
  126. HWND hwndButton = CreateWindow(
  127. L"BUTTON",  // Predefined class; Unicode assumed
  128. L"OK",      // Button text
  129. WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
  130. 10,         // x position
  131. 10,         // y position
  132. 100,        // Button width
  133. 100,        // Button height
  134. m_hwnd,     // Parent window
  135. NULL,       // No menu.
  136. (HINSTANCE)GetWindowLong(m_hwnd, GWL_HINSTANCE),
  137. NULL);      // Pointer not needed.
  138.  
  139. // ######################################################################
  140.  
  141. //
  142. //  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
  143. //
  144. //  PROPÓSITO:  procesar mensajes de la ventana principal.
  145. //
  146. //  WM_COMMAND  - procesar el menú de aplicaciones
  147. //  WM_PAINT    - Pintar la ventana principal
  148. //  WM_DESTROY  - publicar un mensaje de salida y volver
  149. //
  150. //
  151. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  152. {
  153.    switch (message)
  154.    {
  155.    case WM_COMMAND:
  156.        {
  157.            int wmId = LOWORD(wParam);
  158.            // Analizar las selecciones de menú:
  159.            switch (wmId)
  160.            {
  161.            case IDM_ABOUT:
  162.                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  163.                break;
  164.            case IDM_EXIT:
  165.                DestroyWindow(hWnd);
  166.                break;
  167.            default:
  168.                return DefWindowProc(hWnd, message, wParam, lParam);
  169.            }
  170.        }
  171.        break;
  172.    case WM_PAINT:
  173.        {
  174.            PAINTSTRUCT ps;
  175.            HDC hdc = BeginPaint(hWnd, &ps);
  176.            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
  177.            EndPaint(hWnd, &ps);
  178.        }
  179.        break;
  180.    case WM_DESTROY:
  181.        PostQuitMessage(0);
  182.        break;
  183.    default:
  184.        return DefWindowProc(hWnd, message, wParam, lParam);
  185.    }
  186.    return 0;
  187. }
  188.  
  189. // Controlador de mensajes del cuadro Acerca de.
  190. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  191. {
  192.    UNREFERENCED_PARAMETER(lParam);
  193.    switch (message)
  194.    {
  195.    case WM_INITDIALOG:
  196.        return (INT_PTR)TRUE;
  197.  
  198.    case WM_COMMAND:
  199.        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  200.        {
  201.            EndDialog(hDlg, LOWORD(wParam));
  202.            return (INT_PTR)TRUE;
  203.        }
  204.        break;
  205.    }
  206.    return (INT_PTR)FALSE;
  207. }
  208.  

Hay dos códigos más, el del botón:
Código
  1. HWND hwndButton = CreateWindow(
  2.    L"BUTTON",  // Predefined class; Unicode assumed
  3.    L"OK",      // Button text
  4.    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
  5.    10,         // x position
  6.    10,         // y position
  7.    100,        // Button width
  8.    100,        // Button height
  9.    m_hwnd,     // Parent window
  10.    NULL,       // No menu.
  11.    (HINSTANCE)GetWindowLong(m_hwnd, GWL_HINSTANCE),
  12.    NULL);      // Pointer not needed.

Que lo dice aquí (https://msdn.microsoft.com/es-es/library/windows/desktop/hh298354(v=vs.85).aspx?f=255&MSPPError=-2147217396), y el punto de coordenada que lo dice aquí (https://msdn.microsoft.com/es-es/library/a1yzfz6d.aspx) como han puesto.

Coordenada.
Código
  1. void CMyApp::OnHideApplication()
  2. {
  3.   //m_pMainWnd is the main application window, a member of CMyApp
  4.   ASSERT_VALID(m_pMainWnd);
  5.  
  6.   // hide the application's windows before closing all the documents
  7.   m_pMainWnd->ShowWindow(SW_HIDE);
  8.   m_pMainWnd->ShowOwnedPopups(FALSE);
  9.  
  10.   // put the window at the bottom of z-order, so it isn't activated
  11.   m_pMainWnd->SetWindowPos(&CWnd::wndBottom, 0, 0, 0, 0,
  12.      SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
  13. }

Saludos.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 7 Abril 2018, 21:50 pm
Puedes meter la función en la misma función de instancia. Jo que tampoco es nada del otro mundo :

Código:
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   hInst = hInstance; // Almacenar identificador de instancia en una variable global
 
   HWND hWnd = CreateWindowW(
  szWindowClass,
  szTitle,
  WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
  0,
  CW_USEDEFAULT,
  0,
  nullptr,
  nullptr,
  hInstance,
  nullptr);
 
   if (!hWnd)
   {
      return FALSE;
   }
 
   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);
   // AQUI POR EJEMPLO!!! pos : (100,100), size(600,400)
   SetWindowPos(hWnd, 0, 100, 100, 600, 400, NULL);
 
   return TRUE;
}


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 22:21 pm
Muchas gracias campeón.

Aún así me dice algo más de un error.

Código
  1. #include "stdafx.h"
  2. #include "aaaa.h"
  3.  
  4. #define MAX_LOADSTRING 100
  5.  
  6. // Variables globales:
  7. HINSTANCE hInst;                                // Instancia actual
  8. WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
  9. WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal
  10.  
  11. // Declaraciones de funciones adelantadas incluidas en este módulo de código:
  12. ATOM                MyRegisterClass(HINSTANCE hInstance);
  13. BOOL                InitInstance(HINSTANCE, int);
  14. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  15. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  16.  
  17. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  18.                     _In_opt_ HINSTANCE hPrevInstance,
  19.                     _In_ LPWSTR    lpCmdLine,
  20.                     _In_ int       nCmdShow)
  21. {
  22.    UNREFERENCED_PARAMETER(hPrevInstance);
  23.    UNREFERENCED_PARAMETER(lpCmdLine);
  24.  
  25.    // TODO: colocar código aquí.
  26.  
  27.    // Inicializar cadenas globales
  28.    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  29.    LoadStringW(hInstance, IDC_AAAA, szWindowClass, MAX_LOADSTRING);
  30.    MyRegisterClass(hInstance);
  31.  
  32.    // Realizar la inicialización de la aplicación:
  33.    if (!InitInstance (hInstance, nCmdShow))
  34.    {
  35.        return FALSE;
  36.    }
  37.  
  38.    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_AAAA));
  39.  
  40.    MSG msg;
  41.  
  42.    // Bucle principal de mensajes:
  43.    while (GetMessage(&msg, nullptr, 0, 0))
  44.    {
  45.        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  46.        {
  47.            TranslateMessage(&msg);
  48.            DispatchMessage(&msg);
  49.        }
  50.    }
  51.  
  52.    return (int) msg.wParam;
  53. }
  54.  
  55.  
  56.  
  57. //
  58. //  FUNCIÓN: MyRegisterClass()
  59. //
  60. //  PROPÓSITO: registrar la clase de ventana.
  61. //
  62. ATOM MyRegisterClass(HINSTANCE hInstance)
  63. {
  64.    WNDCLASSEXW wcex;
  65.  
  66.    wcex.cbSize = sizeof(WNDCLASSEX);
  67.  
  68.    wcex.style          = CS_HREDRAW | CS_VREDRAW;
  69.    wcex.lpfnWndProc    = WndProc;
  70.    wcex.cbClsExtra     = 0;
  71.    wcex.cbWndExtra     = 0;
  72.    wcex.hInstance      = hInstance;
  73.    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_AAAA));
  74.    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  75.    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  76.    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_AAAA);
  77.    wcex.lpszClassName  = szWindowClass;
  78.    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  79.  
  80.    return RegisterClassExW(&wcex);
  81. }
  82.  
  83. //
  84. //   FUNCIÓN: InitInstance(HINSTANCE, int)
  85. //
  86. //   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
  87. //
  88. //   COMENTARIOS:
  89. //
  90. //        En esta función, se guarda el identificador de instancia en una variable común y
  91. //        se crea y muestra la ventana principal del programa.
  92. //
  93. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  94. {
  95.   hInst = hInstance; // Almacenar identificador de instancia en una variable global
  96.  
  97.   HWND hWnd = CreateWindowW(
  98.   szWindowClass,
  99.   szTitle,
  100.   WS_OVERLAPPEDWINDOW,
  101. CW_USEDEFAULT,
  102.   0,
  103.   CW_USEDEFAULT,
  104.   0,
  105.   nullptr,
  106.   nullptr,
  107.   hInstance,
  108.   nullptr);
  109.  
  110.   if (!hWnd)
  111.   {
  112.      return FALSE;
  113.   }
  114.  
  115.   ShowWindow(hWnd, nCmdShow);
  116.   UpdateWindow(hWnd);
  117.  
  118.   return TRUE;
  119. }
  120.  
  121. // ######################################################################
  122.  
  123. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  124. {
  125. hInst = hInstance; // Almacenar identificador de instancia en una variable global
  126.  
  127. HWND hWnd = CreateWindowW(
  128. szWindowClass,
  129. szTitle,
  130. WS_OVERLAPPEDWINDOW,
  131. CW_USEDEFAULT,
  132. 0,
  133. CW_USEDEFAULT,
  134. 0,
  135. nullptr,
  136. nullptr,
  137. hInstance,
  138. nullptr);
  139.  
  140. if (!hWnd)
  141. {
  142. return FALSE;
  143. }
  144.  
  145. ShowWindow(hWnd, nCmdShow);
  146. UpdateWindow(hWnd);
  147. // AQUI POR EJEMPLO!!! pos : (100,100), size(600,400)
  148. SetWindowPos(hWnd, 0, 100, 100, 600, 400, NULL);
  149.  
  150. return TRUE;
  151. }
  152.  
  153. // ######################################################################
  154.  
  155. //
  156. //  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
  157. //
  158. //  PROPÓSITO:  procesar mensajes de la ventana principal.
  159. //
  160. //  WM_COMMAND  - procesar el menú de aplicaciones
  161. //  WM_PAINT    - Pintar la ventana principal
  162. //  WM_DESTROY  - publicar un mensaje de salida y volver
  163. //
  164. //
  165. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  166. {
  167.    switch (message)
  168.    {
  169.    case WM_COMMAND:
  170.        {
  171.            int wmId = LOWORD(wParam);
  172.            // Analizar las selecciones de menú:
  173.            switch (wmId)
  174.            {
  175.            case IDM_ABOUT:
  176.                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  177.                break;
  178.            case IDM_EXIT:
  179.                DestroyWindow(hWnd);
  180.                break;
  181.            default:
  182.                return DefWindowProc(hWnd, message, wParam, lParam);
  183.            }
  184.        }
  185.        break;
  186.    case WM_PAINT:
  187.        {
  188.            PAINTSTRUCT ps;
  189.            HDC hdc = BeginPaint(hWnd, &ps);
  190.            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
  191.            EndPaint(hWnd, &ps);
  192.        }
  193.        break;
  194.    case WM_DESTROY:
  195.        PostQuitMessage(0);
  196.        break;
  197.    default:
  198.        return DefWindowProc(hWnd, message, wParam, lParam);
  199.    }
  200.    return 0;
  201. }
  202.  
  203. // Controlador de mensajes del cuadro Acerca de.
  204. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  205. {
  206.    UNREFERENCED_PARAMETER(lParam);
  207.    switch (message)
  208.    {
  209.    case WM_INITDIALOG:
  210.        return (INT_PTR)TRUE;
  211.  
  212.    case WM_COMMAND:
  213.        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  214.        {
  215.            EndDialog(hDlg, LOWORD(wParam));
  216.            return (INT_PTR)TRUE;
  217.        }
  218.        break;
  219.    }
  220.    return (INT_PTR)FALSE;
  221. }

Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido
Error   C2084   la función 'BOOL InitInstance(HINSTANCE,int)' ya tiene un cuerpo   aaaa   c:\users\usuario\documents\visual studio 2017\projects\aaaa\aaaa\aaaa.cpp   130   


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 7 Abril 2018, 22:23 pm
A ver Mc fly, no deberías tener dos funciones de instancia  :rolleyes:


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 7 Abril 2018, 23:14 pm
Buenas:

El como lo hice me funciona pero no aparece botón ni cambio de tamaño del formulario.
Código
  1. // aaaa.cpp: define el punto de entrada de la aplicación.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "aaaa.h"
  6.  
  7. #define MAX_LOADSTRING 100
  8.  
  9. // Variables globales:
  10. HINSTANCE hInst;                                // Instancia actual
  11. WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
  12. WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal
  13.  
  14. // Declaraciones de funciones adelantadas incluidas en este módulo de código:
  15. ATOM                MyRegisterClass(HINSTANCE hInstance);
  16. BOOL                InitInstance(HINSTANCE, int);
  17. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  18. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  19.  
  20. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  21.                     _In_opt_ HINSTANCE hPrevInstance,
  22.                     _In_ LPWSTR    lpCmdLine,
  23.                     _In_ int       nCmdShow)
  24. {
  25.    UNREFERENCED_PARAMETER(hPrevInstance);
  26.    UNREFERENCED_PARAMETER(lpCmdLine);
  27.  
  28.    // TODO: colocar código aquí.
  29.  
  30.    // Inicializar cadenas globales
  31.    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  32.    LoadStringW(hInstance, IDC_AAAA, szWindowClass, MAX_LOADSTRING);
  33.    MyRegisterClass(hInstance);
  34.  
  35.    // Realizar la inicialización de la aplicación:
  36.    if (!InitInstance (hInstance, nCmdShow))
  37.    {
  38.        return FALSE;
  39.    }
  40.  
  41.    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_AAAA));
  42.  
  43.    MSG msg;
  44.  
  45.    // Bucle principal de mensajes:
  46.    while (GetMessage(&msg, nullptr, 0, 0))
  47.    {
  48.        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  49.        {
  50.            TranslateMessage(&msg);
  51.            DispatchMessage(&msg);
  52.        }
  53.    }
  54.  
  55.    return (int) msg.wParam;
  56. }
  57.  
  58.  
  59.  
  60. //
  61. //  FUNCIÓN: MyRegisterClass()
  62. //
  63. //  PROPÓSITO: registrar la clase de ventana.
  64. //
  65. ATOM MyRegisterClass(HINSTANCE hInstance)
  66. {
  67.    WNDCLASSEXW wcex;
  68.  
  69.    wcex.cbSize = sizeof(WNDCLASSEX);
  70.  
  71.    wcex.style          = CS_HREDRAW | CS_VREDRAW;
  72.    wcex.lpfnWndProc    = WndProc;
  73.    wcex.cbClsExtra     = 0;
  74.    wcex.cbWndExtra     = 0;
  75.    wcex.hInstance      = hInstance;
  76.    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_AAAA));
  77.    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  78.    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  79.    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_AAAA);
  80.    wcex.lpszClassName  = szWindowClass;
  81.    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  82.  
  83.    return RegisterClassExW(&wcex);
  84. }
  85.  
  86. //
  87. //   FUNCIÓN: InitInstance(HINSTANCE, int)
  88. //
  89. //   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
  90. //
  91. //   COMENTARIOS:
  92. //
  93. //        En esta función, se guarda el identificador de instancia en una variable común y
  94. //        se crea y muestra la ventana principal del programa.
  95. //
  96. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  97. {
  98.   hInst = hInstance; // Almacenar identificador de instancia en una variable global
  99.  
  100.   HWND hWnd = CreateWindowW(
  101.   szWindowClass,
  102.   szTitle,
  103.   WS_OVERLAPPEDWINDOW,
  104. CW_USEDEFAULT,
  105.   0,
  106.   CW_USEDEFAULT,
  107.   0,
  108.   nullptr,
  109.   nullptr,
  110.   hInstance,
  111.   nullptr);
  112.  
  113.   if (!hWnd)
  114.   {
  115.      return FALSE;
  116.   }
  117.  
  118.   ShowWindow(hWnd, nCmdShow);
  119.   UpdateWindow(hWnd);
  120.  
  121.   return TRUE;
  122.  
  123.   // ######################################################################
  124.   hInst = hInstance; // Almacenar identificador de instancia en una variable global
  125.  
  126.   HWND hWnd2 = CreateWindowW(
  127.   szWindowClass,
  128.   szTitle,
  129.   WS_OVERLAPPEDWINDOW,
  130.   CW_USEDEFAULT,
  131.   0,
  132.   CW_USEDEFAULT,
  133.   0,
  134.   nullptr,
  135.   nullptr,
  136.   hInstance,
  137.   nullptr);
  138.  
  139.   if (!hWnd2)
  140.   {
  141.   return FALSE;
  142.   }
  143.  
  144.   ShowWindow(hWnd2, nCmdShow);
  145.   UpdateWindow(hWnd2);
  146.   // AQUI POR EJEMPLO!!! posición(100,100), tamaño(600,400)
  147.   SetWindowPos(hWnd2, 0, 100, 100, 600, 400, NULL);
  148.  
  149.   return TRUE;
  150.   // ######################################################################
  151. }
  152.  
  153. //
  154. //  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
  155. //
  156. //  PROPÓSITO:  procesar mensajes de la ventana principal.
  157. //
  158. //  WM_COMMAND  - procesar el menú de aplicaciones
  159. //  WM_PAINT    - Pintar la ventana principal
  160. //  WM_DESTROY  - publicar un mensaje de salida y volver
  161. //
  162. //
  163. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  164. {
  165.    switch (message)
  166.    {
  167.    case WM_COMMAND:
  168.        {
  169.            int wmId = LOWORD(wParam);
  170.            // Analizar las selecciones de menú:
  171.            switch (wmId)
  172.            {
  173.            case IDM_ABOUT:
  174.                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  175.                break;
  176.            case IDM_EXIT:
  177.                DestroyWindow(hWnd);
  178.                break;
  179.            default:
  180.                return DefWindowProc(hWnd, message, wParam, lParam);
  181.            }
  182.        }
  183.        break;
  184.    case WM_PAINT:
  185.        {
  186.            PAINTSTRUCT ps;
  187.            HDC hdc = BeginPaint(hWnd, &ps);
  188.            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
  189.            EndPaint(hWnd, &ps);
  190.        }
  191.        break;
  192.    case WM_DESTROY:
  193.        PostQuitMessage(0);
  194.        break;
  195.    default:
  196.        return DefWindowProc(hWnd, message, wParam, lParam);
  197.    }
  198.    return 0;
  199. }
  200.  
  201. // Controlador de mensajes del cuadro Acerca de.
  202. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  203. {
  204.    UNREFERENCED_PARAMETER(lParam);
  205.    switch (message)
  206.    {
  207.    case WM_INITDIALOG:
  208.        return (INT_PTR)TRUE;
  209.  
  210.    case WM_COMMAND:
  211.        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  212.        {
  213.            EndDialog(hDlg, LOWORD(wParam));
  214.            return (INT_PTR)TRUE;
  215.        }
  216.        break;
  217.    }
  218.    return (INT_PTR)FALSE;
  219. }
  220.  


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 7 Abril 2018, 23:19 pm
Es algún tipo de broma?

Código:
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{ // de verdad esto es serio?
   hInst = hInstance; // Almacenar identificador de instancia en una variable global
 
   HWND hWnd = CreateWindowW(
   szWindowClass,
   szTitle,
   WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
   0,
   CW_USEDEFAULT,
   0,
   nullptr,
   nullptr,
   hInstance,
   nullptr);
 
   if (!hWnd)
   {
      return FALSE;
   }
 
   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);
 
   return TRUE; // me estas vacilando o algo asi?
 
   // ######################################################################
   hInst = hInstance; // Almacenar identificador de instancia en una variable global
 
   HWND hWnd2 = CreateWindowW(
   szWindowClass,
   szTitle,
   WS_OVERLAPPEDWINDOW,
   CW_USEDEFAULT,
   0,
   CW_USEDEFAULT,
   0,
   nullptr,
   nullptr,
   hInstance,
   nullptr);
 
   if (!hWnd2)
   {
   return FALSE;
   }
 
   ShowWindow(hWnd2, nCmdShow);
   UpdateWindow(hWnd2);
   // AQUI POR EJEMPLO!!! posición(100,100), tamaño(600,400)
   SetWindowPos(hWnd2, 0, 100, 100, 600, 400, NULL);
 
   return TRUE;
   // ######################################################################
}

Simplemente te tienes que deshacer de las primeras líneas de la instancia... y si en verdad esto es serio creo que lo primero que deberías hacer es aprender a programar C en la consola y luego pasar a cosas mayores.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 8 Abril 2018, 00:10 am
Ejecuta pero no hace nada, misma pantalla, el tamaño, aunque lo varíe, no hace nada.

Código
  1. #include "stdafx.h"
  2. #include "aaaa.h"
  3.  
  4. #define MAX_LOADSTRING 100
  5.  
  6. // Variables globales:
  7. HINSTANCE hInst;                                // Instancia actual
  8. WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
  9. WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal
  10.  
  11. // Declaraciones de funciones adelantadas incluidas en este módulo de código:
  12. ATOM                MyRegisterClass(HINSTANCE hInstance);
  13. BOOL                InitInstance(HINSTANCE, int);
  14. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  15. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  16.  
  17. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  18.                     _In_opt_ HINSTANCE hPrevInstance,
  19.                     _In_ LPWSTR    lpCmdLine,
  20.                     _In_ int       nCmdShow)
  21. {
  22.    UNREFERENCED_PARAMETER(hPrevInstance);
  23.    UNREFERENCED_PARAMETER(lpCmdLine);
  24.  
  25.    // TODO: colocar código aquí.
  26.  
  27.    // Inicializar cadenas globales
  28.    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  29.    LoadStringW(hInstance, IDC_AAAA, szWindowClass, MAX_LOADSTRING);
  30.    MyRegisterClass(hInstance);
  31.  
  32.    // Realizar la inicialización de la aplicación:
  33.    if (!InitInstance (hInstance, nCmdShow))
  34.    {
  35.        return FALSE;
  36.    }
  37.  
  38.    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_AAAA));
  39.  
  40.    MSG msg;
  41.  
  42.    // Bucle principal de mensajes:
  43.    while (GetMessage(&msg, nullptr, 0, 0))
  44.    {
  45.        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  46.        {
  47.            TranslateMessage(&msg);
  48.            DispatchMessage(&msg);
  49.        }
  50.    }
  51.  
  52.    return (int) msg.wParam;
  53. }
  54.  
  55.  
  56.  
  57. //
  58. //  FUNCIÓN: MyRegisterClass()
  59. //
  60. //  PROPÓSITO: registrar la clase de ventana.
  61. //
  62. ATOM MyRegisterClass(HINSTANCE hInstance)
  63. {
  64.    WNDCLASSEXW wcex;
  65.  
  66.    wcex.cbSize = sizeof(WNDCLASSEX);
  67.  
  68.    wcex.style          = CS_HREDRAW | CS_VREDRAW;
  69.    wcex.lpfnWndProc    = WndProc;
  70.    wcex.cbClsExtra     = 0;
  71.    wcex.cbWndExtra     = 0;
  72.    wcex.hInstance      = hInstance;
  73.    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_AAAA));
  74.    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  75.    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  76.    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_AAAA);
  77.    wcex.lpszClassName  = szWindowClass;
  78.    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  79.  
  80.    return RegisterClassExW(&wcex);
  81. }
  82.  
  83. //
  84. //   FUNCIÓN: InitInstance(HINSTANCE, int)
  85. //
  86. //   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
  87. //
  88. //   COMENTARIOS:
  89. //
  90. //        En esta función, se guarda el identificador de instancia en una variable común y
  91. //        se crea y muestra la ventana principal del programa.
  92. //
  93.  
  94.  
  95.   // ######################################################################
  96. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  97. { // de verdad esto es serio?
  98. hInst = hInstance; // Almacenar identificador de instancia en una variable global
  99.  
  100. HWND hWnd = CreateWindowW(
  101. szWindowClass,
  102. szTitle,
  103. WS_OVERLAPPEDWINDOW,
  104. CW_USEDEFAULT,
  105. 0,
  106. CW_USEDEFAULT,
  107. 0,
  108. nullptr,
  109. nullptr,
  110. hInstance,
  111. nullptr);
  112.  
  113. if (!hWnd)
  114. {
  115. return FALSE;
  116. }
  117.  
  118. ShowWindow(hWnd, nCmdShow);
  119. UpdateWindow(hWnd);
  120.  
  121. return TRUE; // me estas vacilando o algo asi?
  122.  
  123. // ######################################################################
  124. hInst = hInstance; // Almacenar identificador de instancia en una variable global
  125.  
  126. HWND hWnd2 = CreateWindowW(
  127. szWindowClass,
  128. szTitle,
  129. WS_OVERLAPPEDWINDOW,
  130. CW_USEDEFAULT,
  131. 0,
  132. CW_USEDEFAULT,
  133. 0,
  134. nullptr,
  135. nullptr,
  136. hInstance,
  137. nullptr);
  138.  
  139. if (!hWnd2)
  140. {
  141. return FALSE;
  142. }
  143.  
  144. ShowWindow(hWnd2, nCmdShow);
  145. UpdateWindow(hWnd2);
  146. // AQUI POR EJEMPLO!!! posición(100,100), tamaño(600,400)
  147. SetWindowPos(hWnd2, 0, 50, 50, 100, 100, NULL);
  148.  
  149. return TRUE;
  150. // ######################################################################
  151. }
  152.   // ######################################################################
  153.  
  154.  
  155. //
  156. //  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
  157. //
  158. //  PROPÓSITO:  procesar mensajes de la ventana principal.
  159. //
  160. //  WM_COMMAND  - procesar el menú de aplicaciones
  161. //  WM_PAINT    - Pintar la ventana principal
  162. //  WM_DESTROY  - publicar un mensaje de salida y volver
  163. //
  164. //
  165. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  166. {
  167.    switch (message)
  168.    {
  169.    case WM_COMMAND:
  170.        {
  171.            int wmId = LOWORD(wParam);
  172.            // Analizar las selecciones de menú:
  173.            switch (wmId)
  174.            {
  175.            case IDM_ABOUT:
  176.                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  177.                break;
  178.            case IDM_EXIT:
  179.                DestroyWindow(hWnd);
  180.                break;
  181.            default:
  182.                return DefWindowProc(hWnd, message, wParam, lParam);
  183.            }
  184.        }
  185.        break;
  186.    case WM_PAINT:
  187.        {
  188.            PAINTSTRUCT ps;
  189.            HDC hdc = BeginPaint(hWnd, &ps);
  190.            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
  191.            EndPaint(hWnd, &ps);
  192.        }
  193.        break;
  194.    case WM_DESTROY:
  195.        PostQuitMessage(0);
  196.        break;
  197.    default:
  198.        return DefWindowProc(hWnd, message, wParam, lParam);
  199.    }
  200.    return 0;
  201. }
  202.  
  203. // Controlador de mensajes del cuadro Acerca de.
  204. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  205. {
  206.    UNREFERENCED_PARAMETER(lParam);
  207.    switch (message)
  208.    {
  209.    case WM_INITDIALOG:
  210.        return (INT_PTR)TRUE;
  211.  
  212.    case WM_COMMAND:
  213.        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  214.        {
  215.            EndDialog(hDlg, LOWORD(wParam));
  216.            return (INT_PTR)TRUE;
  217.        }
  218.        break;
  219.    }
  220.    return (INT_PTR)FALSE;
  221. }


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: ivancea96 en 8 Abril 2018, 12:42 pm
No se programa copiando y pegando código. Ni el código de srWhiteSkull leíste...

Lo mejor es que intentes otro tipo de proyecto de consola, como dice srWhiteSkull. WinAPI no es complicada, pero hay que saber C para usarla. Y saber C no es copiar y pegar trozos de código de la MSDN. Saber C es saber hacer ese código tú; saberlo leer e interpretar, o por lo menos, esforzarse en entenderlo.

Te podemos hacer el código nosotros con un botón. Pero dime tú que utilidad tendría eso.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 8 Abril 2018, 21:22 pm
Hola:

Leer, leer y leer he leído hasta las cejas.

Quiero redimensionar el formulario a 300 x 300 o al menos por ahí de ese tamaño. En cuanto a los dos botones, lo que quiero hacer, es ponerlo en el formulario. Lo que hace el botón, simplemente es abrir la bandeja del disco o lector y el otro cerrar.

En Win32 modo consola C++ es así.
Código
  1. #include "stdafx.h"
  2. #include "Windows.h"
  3. #include "iostream"
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. // Título de la ventana.
  10. SetConsoleTitle(L"Consola C++ Win32 2017");
  11.  
  12. // Variable.
  13. char entrada[] = "\0"; // Guarda A, a, C, y c tipo string que introduces desde la consola.
  14.  
  15. while (true)
  16. {
  17. // Muestra en pantalla textos.
  18. cout << "Control bandeja del lector: " << endl << endl;
  19. cout << "A - Abrir bandeja." << endl;
  20. cout << "C - Cerrar bandeja." << endl;
  21. cout << "==========================" << endl;
  22.  
  23. cin >> entrada; // Aquí introduces letras A, a, C, y c.
  24.  
  25. cout << "\n" << endl;
  26.  
  27. // Abrir bandeja.
  28. if ((entrada[0] == 'a') || (entrada[0] == 'A'))
  29. {
  30. cout << "Abriendo..." << endl << endl; // Muestra en pantalla textos.
  31. mciSendString(L"set cdaudio door open", nullptr, 0, nullptr);
  32. cout << "Abierto." << endl << endl; // Muestra en pantalla textos.
  33. }
  34. // Cerrar bandeja.
  35. else if ((entrada[0] == 'c') || (entrada[0] == 'C'))
  36. {
  37. cout << "Cerrando..." << endl << endl; // Muestra en pantalla textos.
  38. mciSendString(L"set cdaudio door closed", nullptr, 0, nullptr);
  39. cout << "Cerrado." << endl << endl; // Muestra en pantalla textos.
  40. }
  41. // Si haz pulsado otro caracter distinto de A, C, a, y c aparece
  42. else
  43. {
  44. cout << "Solo pulsar A o C." << endl << endl; // este mensaje.
  45.  
  46. }
  47. }
  48. return EXIT_SUCCESS;
  49. }

Consola C++ CLR .net:
Código
  1. #include "stdafx.h"
  2.  
  3. using namespace System;
  4. using namespace System::Runtime::InteropServices;
  5. using namespace System::Text;
  6.  
  7. [DllImport("winmm.dll")]
  8. extern Int32 mciSendString(String^ lpstrCommand, StringBuilder^ lpstrReturnString,
  9. int uReturnLength, IntPtr hwndCallback);
  10.  
  11. static void DoEvents()
  12. {
  13. Console::SetCursorPosition(0, 6);
  14. Console::Write("Abriendo...");
  15. }
  16.  
  17. static void DoEvents2()
  18. {
  19. Console::SetCursorPosition(0, 6);
  20. Console::Write("Cerrando...");
  21. }
  22.  
  23. int main(array<System::String ^> ^args)
  24. {
  25. StringBuilder^ rt = gcnew StringBuilder(127);
  26.  
  27. // Título de la ventana.
  28. Console::Title = "Consola C++ CLR 2017";
  29.  
  30. // Tamaño ventana consola.
  31. Console::WindowWidth = 29; // X. Ancho.
  32. Console::WindowHeight = 8; // Y. Alto.
  33.  
  34.   // Cursor invisible.
  35. Console::CursorVisible = false;
  36.  
  37. // Posición del mansaje en la ventana.
  38. Console::SetCursorPosition(0, 0);
  39. Console::WriteLine("Control bandeja del lector : \n\n" +
  40. "A - Abrir bandeja. \n" +
  41. "C - Cerrar bandeja. \n" +
  42. "========================== \n");
  43.  
  44. ConsoleKey key;
  45. //Console::CursorVisible = false;
  46. do
  47. {
  48. key = Console::ReadKey(true).Key;
  49.  
  50. String^ mensaje = "";
  51.  
  52. //Asignamos la tecla presionada por el usuario
  53. switch (key)
  54. {
  55. case ConsoleKey::A:
  56. mensaje = "Abriendo...";
  57. Console::SetCursorPosition(0, 6);
  58. DoEvents();
  59. mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);
  60. mensaje = "Abierto.";
  61. break;
  62.  
  63. case ConsoleKey::C:
  64. mensaje = "Cerrando...";
  65. Console::SetCursorPosition(0, 6);
  66. DoEvents2();
  67. mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);
  68. mensaje = "Cerrado.";
  69. break;
  70. }
  71.  
  72. Console::SetCursorPosition(0, 6);
  73. Console::Write("           ");
  74. Console::SetCursorPosition(0, 6);
  75. Console::Write(mensaje);
  76.  
  77. } while (key != ConsoleKey::Escape);
  78. return 0;
  79. }

Formulario C++ CLR .net: (Sólo pongo una imagen, si quieren el código lo subo).

Lo quiero que salga como abajo en formulario pero en Win32. ;)
(https://www.subeimagenes.com/img/captura-1852378.PNG)

Para dejarlo más claro.

Para abrir bandeja se usa este código.
Código
  1. mciSendString(L"set cdaudio door open", nullptr, 0, nullptr);

Cerrar bandeja.
Código
  1. mciSendString(L"set cdaudio door closed", nullptr, 0, nullptr);

Dejando claro que el Winmm.lib está cargado en el Visual Studio.

Es todo lo que quiero saber, antes que nada, crear botones y redimensionar formulario como quiera.

Saludos.



Edito:
Lo que he hecho.

De este código que viene predeterminado.
Código
  1.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  2.      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

De los 0 le puse 300 ya que quiero 300 x 300 y no funciona.
Código
  1.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  2.      CW_USEDEFAULT, 300, CW_USEDEFAULT, 300, nullptr, nullptr, hInstance, nullptr);

Tuve que cambiar el orden del CW_USEDEFAULT y 300 como indica abajo y por fin funciona la redimensión.
Código
  1.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  2.      CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, nullptr, nullptr, hInstance, nullptr);

Por fin funciona esa parte.
La otra parte de los botones no.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 8 Abril 2018, 22:06 pm
Si has leído y no has revisado el código y ves normal que una función retorne impidiendo que parte del código repetido no se ejecute, donde se incluye la función de redimensionar y posicionar, entonces no hay mucho que hacer... a lo mejor en otra vida puede que te des cuenta  :xD


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 8 Abril 2018, 22:11 pm
Editado, volver a leer el post anterior donde pone Edito:.

Falta este donde encajarlo bien.
Código
  1. HWND btnOK = CreateWindowW(
  2. L"BUTTON", // clase del control
  3. L"OK",
  4. WS_CHILD | WS_PUSBUTTON | WS_VISIBLE, // estilo del control. La clase button puede ser checkbox, radio, etc.
  5. 5, 5, // posición respecto del client area del parent
  6. 40, 20,  // dimensiones del control
  7. hWnd,   // --> este es el handle de tu ventana principal
  8. 1, // este es el identificador de tu control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  9. hInstance,
  10. nullptr);


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 8 Abril 2018, 22:17 pm
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.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: srWhiteSkull en 8 Abril 2018, 22:26 pm
https://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 8 Abril 2018, 23:56 pm
Buenas:

Por fin.
(https://www.subeimagenes.com/img/captura2-1852537.PNG)
Código
  1. case WM_CREATE:
  2. {
  3. HWND btnOK = CreateWindowW(
  4. L"BUTTON", // Clase del control.
  5. L"Abrir", // Etiqueta del botón.
  6. WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  7. 45, 135, // Posición respecto del client area del parent.
  8. 75, 23, // Dimensiones del control.
  9. hWnd, // --> Este es el handle de la ventana principal.
  10. (HMENU)101, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  11. hInst,
  12. nullptr);
  13.  
  14. HWND btnOK2 = CreateWindowW(
  15. L"BUTTON", // Clase del control.
  16. L"Cerrar", // Etiqueta del botón.
  17. WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  18. 165, 135, // Posición respecto del client area del parent.
  19. 75, 23, // Dimensiones del control.
  20. hWnd, // --> Este es el handle de la ventana principal.
  21. (HMENU)102, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  22. hInst,
  23. nullptr);
  24. }

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
  1. mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);

Cerrar:
Código
  1. mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);

Para que funcione, antes hacer esto:
(https://www.subeimagenes.com/img/captura3-1852539.PNG)

(https://www.subeimagenes.com/img/captura4-1852541.PNG)

En el lenguaje C++ del CLR, este es su código.
Código
  1. private: System::Void button_Abrir_Click(System::Object^  sender, System::EventArgs^  e) {
  2. label_Mensaje->Text = "Abriendo...";
  3. Application::DoEvents();
  4. mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);
  5. label_Mensaje->Text = "Abierto.";
  6. }
Para que funcione bien los eventos del Abriendo... y Abierto.

Sigo investigando.

Saludos y muchas gracias por todo a tod@s.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 9 Abril 2018, 17:43 pm
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

(https://www.subeimagenes.com/img/captura-1853213.PNG)

Código commpleto.
Código
  1. #include "stdafx.h"
  2. #include "Bandeja_Form_Win32_cpp.h"
  3. #include "mmsystem.h" // No olvidar.
  4.  
  5. #define MAX_LOADSTRING 100
  6.  
  7. // Variables globales:
  8. HINSTANCE hInst;                                // Instancia actual
  9. WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
  10. WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal
  11.  
  12. // Declaraciones de funciones adelantadas incluidas en este módulo de código:
  13. ATOM                MyRegisterClass(HINSTANCE hInstance);
  14. BOOL                InitInstance(HINSTANCE, int);
  15. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  16. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  17.  
  18. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  19.                     _In_opt_ HINSTANCE hPrevInstance,
  20.                     _In_ LPWSTR    lpCmdLine,
  21.                     _In_ int       nCmdShow)
  22. {
  23.    UNREFERENCED_PARAMETER(hPrevInstance);
  24.    UNREFERENCED_PARAMETER(lpCmdLine);
  25.  
  26.    // TODO: colocar código aquí.
  27.  
  28.    // Inicializar cadenas globales
  29.    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  30.    LoadStringW(hInstance, IDC_BANDEJAFORMWIN32CPP, szWindowClass, MAX_LOADSTRING);
  31.    MyRegisterClass(hInstance);
  32.  
  33.    // Realizar la inicialización de la aplicación:
  34.    if (!InitInstance (hInstance, nCmdShow))
  35.    {
  36.        return FALSE;
  37.    }
  38.  
  39.    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_BANDEJAFORMWIN32CPP));
  40.  
  41.    MSG msg;
  42.  
  43.    // Bucle principal de mensajes:
  44.    while (GetMessage(&msg, nullptr, 0, 0))
  45.    {
  46.        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  47.        {
  48.            TranslateMessage(&msg);
  49.            DispatchMessage(&msg);
  50.        }
  51.    }
  52.  
  53.    return (int) msg.wParam;
  54. }
  55.  
  56.  
  57.  
  58. //
  59. //  FUNCIÓN: MyRegisterClass()
  60. //
  61. //  PROPÓSITO: registrar la clase de ventana.
  62. //
  63. ATOM MyRegisterClass(HINSTANCE hInstance)
  64. {
  65.    WNDCLASSEXW wcex;
  66.  
  67.    wcex.cbSize = sizeof(WNDCLASSEX);
  68.  
  69.    wcex.style          = CS_HREDRAW | CS_VREDRAW;
  70.    wcex.lpfnWndProc    = WndProc;
  71.    wcex.cbClsExtra     = 0;
  72.    wcex.cbWndExtra     = 0;
  73.    wcex.hInstance      = hInstance;
  74.    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_BANDEJAFORMWIN32CPP));
  75.    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  76.    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  77.    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_BANDEJAFORMWIN32CPP);
  78.    wcex.lpszClassName  = szWindowClass;
  79.    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  80.  
  81.    return RegisterClassExW(&wcex);
  82. }
  83.  
  84. //
  85. //   FUNCIÓN: InitInstance(HINSTANCE, int)
  86. //
  87. //   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
  88. //
  89. //   COMENTARIOS:
  90. //
  91. //        En esta función, se guarda el identificador de instancia en una variable común y
  92. //        se crea y muestra la ventana principal del programa.
  93. //
  94. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  95. {
  96.   hInst = hInstance; // Almacenar identificador de instancia en una variable global
  97.  
  98.   // #######################################################################
  99.   // Redimensionar formulario a 300 x 300.
  100.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  101.      CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, nullptr, nullptr, hInstance, nullptr);
  102.   // #######################################################################
  103.  
  104.   if (!hWnd)
  105.   {
  106.      return FALSE;
  107.   }
  108.  
  109.   ShowWindow(hWnd, nCmdShow);
  110.   UpdateWindow(hWnd);
  111.  
  112.   return TRUE;
  113. }
  114.  
  115. //
  116. //  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
  117. //
  118. //  PROPÓSITO:  procesar mensajes de la ventana principal.
  119. //
  120. //  WM_COMMAND  - procesar el menú de aplicaciones
  121. //  WM_PAINT    - Pintar la ventana principal
  122. //  WM_DESTROY  - publicar un mensaje de salida y volver
  123. //
  124. //
  125. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  126. {
  127.    switch (message)
  128.    {
  129. // #######################################################################
  130. // Crear botones Abrir y Cerrar.
  131. case WM_CREATE:
  132. {
  133. HWND btnOK = CreateWindowW(
  134. L"BUTTON", // Clase del control.
  135. L"Abrir", // Etiqueta del botón.
  136. WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  137. 45, 135, // Posición respecto del client area del parent.
  138. 75, 23, // Dimensiones del control.
  139. hWnd, // --> Este es el handle de la ventana principal.
  140. (HMENU)101, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  141. hInst,
  142. nullptr);
  143.  
  144. HWND btnOK2 = CreateWindowW(
  145. L"BUTTON", // Clase del control.
  146. L"Cerrar", // Etiqueta del botón.
  147. WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  148. 165, 135, // Posición respecto del client area del parent.
  149. 75, 23, // Dimensiones del control.
  150. hWnd, // --> Este es el handle de la ventana principal.
  151. (HMENU)102, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  152. hInst,
  153. nullptr);
  154.  
  155. // Label o etiqueta.
  156. HWND edit = CreateWindowW(
  157. L"STATIC", // Clase del control.
  158. L"Hola.", // Etiqueta del botón.
  159. WS_CHILD | SS_SIMPLE | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  160. 125, 55, // Posición respecto del client area del parent.
  161. 75, 23, // Dimensiones del control.
  162. hWnd, // --> Este es el handle de la ventana principal.
  163. (HMENU)103, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  164. hInst,
  165. nullptr);
  166. }
  167.  
  168. break;
  169. // #######################################################################
  170.  
  171.    case WM_COMMAND:
  172.        {
  173.            int wmId = LOWORD(wParam);
  174.            // Analizar las selecciones de menú:
  175.            switch (wmId)
  176.            {
  177.            case IDM_ABOUT:
  178.                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  179.                break;
  180.            case IDM_EXIT:
  181.                DestroyWindow(hWnd);
  182.                break;
  183.            default:
  184.                return DefWindowProc(hWnd, message, wParam, lParam);
  185.            }
  186.        }
  187.        break;
  188.    case WM_PAINT:
  189.        {
  190.            PAINTSTRUCT ps;
  191.            HDC hdc = BeginPaint(hWnd, &ps);
  192.            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
  193.            EndPaint(hWnd, &ps);
  194.        }
  195.        break;
  196.    case WM_DESTROY:
  197.        PostQuitMessage(0);
  198.        break;
  199.    default:
  200.        return DefWindowProc(hWnd, message, wParam, lParam);
  201.    }
  202.    return 0;
  203. }
  204.  
  205. // Controlador de mensajes del cuadro Acerca de.
  206. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  207. {
  208.    UNREFERENCED_PARAMETER(lParam);
  209.    switch (message)
  210.    {
  211.    case WM_INITDIALOG:
  212.        return (INT_PTR)TRUE;
  213.  
  214.    case WM_COMMAND:
  215.        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  216.        {
  217.            EndDialog(hDlg, LOWORD(wParam));
  218.            return (INT_PTR)TRUE;
  219.        }
  220.        break;
  221.    }
  222.    return (INT_PTR)FALSE;
  223. }

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

En el botón Abrir:
Código
  1. mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero);


En el botón Cerrar:

Código
  1. mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero);


Si todo marcha bien, habremos acabado.


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 10 Abril 2018, 16:33 pm
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.
Código:
				// #################################################################### 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


Título: Re: ¿Cómo añadir dos botones al formulario?
Publicado por: Meta en 10 Abril 2018, 21:04 pm
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
  1. #include "stdafx.h"
  2. #include "Bandeja_Form_Win32_cpp.h"
  3. #include "mmsystem.h" // No olvidar.
  4.  
  5. #define MAX_LOADSTRING 100
  6. #define IDC_BUTTON_1 201 // No olvidar.
  7. #define IDC_BUTTON_2 202 // No olvidar.
  8. #define IDC_STATIC_1 303 // No olvidar.
  9.  
  10. // Variables globales:
  11. HINSTANCE hInst;                                // Instancia actual
  12. WCHAR szTitle[MAX_LOADSTRING];                  // Texto de la barra de título
  13. WCHAR szWindowClass[MAX_LOADSTRING];            // nombre de clase de la ventana principal
  14.  
  15. // Declaraciones de funciones adelantadas incluidas en este módulo de código:
  16. ATOM                MyRegisterClass(HINSTANCE hInstance);
  17. BOOL                InitInstance(HINSTANCE, int);
  18. LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
  19. INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
  20.  
  21. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  22.                     _In_opt_ HINSTANCE hPrevInstance,
  23.                     _In_ LPWSTR    lpCmdLine,
  24.                     _In_ int       nCmdShow)
  25. {
  26.    UNREFERENCED_PARAMETER(hPrevInstance);
  27.    UNREFERENCED_PARAMETER(lpCmdLine);
  28.  
  29.    // TODO: colocar código aquí.
  30.  
  31.    // Inicializar cadenas globales
  32.    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
  33.    LoadStringW(hInstance, IDC_BANDEJAFORMWIN32CPP, szWindowClass, MAX_LOADSTRING);
  34.    MyRegisterClass(hInstance);
  35.  
  36.    // Realizar la inicialización de la aplicación:
  37.    if (!InitInstance (hInstance, nCmdShow))
  38.    {
  39.        return FALSE;
  40.    }
  41.  
  42.    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_BANDEJAFORMWIN32CPP));
  43.  
  44.    MSG msg;
  45.  
  46.    // Bucle principal de mensajes:
  47.    while (GetMessage(&msg, nullptr, 0, 0))
  48.    {
  49.        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
  50.        {
  51.            TranslateMessage(&msg);
  52.            DispatchMessage(&msg);
  53.        }
  54.    }
  55.  
  56.    return (int) msg.wParam;
  57. }
  58.  
  59.  
  60.  
  61. //
  62. //  FUNCIÓN: MyRegisterClass()
  63. //
  64. //  PROPÓSITO: registrar la clase de ventana.
  65. //
  66. ATOM MyRegisterClass(HINSTANCE hInstance)
  67. {
  68.    WNDCLASSEXW wcex;
  69.  
  70.    wcex.cbSize = sizeof(WNDCLASSEX);
  71.  
  72.    wcex.style          = CS_HREDRAW | CS_VREDRAW;
  73.    wcex.lpfnWndProc    = WndProc;
  74.    wcex.cbClsExtra     = 0;
  75.    wcex.cbWndExtra     = 0;
  76.    wcex.hInstance      = hInstance;
  77.    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_BANDEJAFORMWIN32CPP));
  78.    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
  79.    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  80.    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_BANDEJAFORMWIN32CPP);
  81.    wcex.lpszClassName  = szWindowClass;
  82.    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
  83.  
  84.    return RegisterClassExW(&wcex);
  85. }
  86.  
  87. //
  88. //   FUNCIÓN: InitInstance(HINSTANCE, int)
  89. //
  90. //   PROPÓSITO: guardar el identificador de instancia y crear la ventana principal
  91. //
  92. //   COMENTARIOS:
  93. //
  94. //        En esta función, se guarda el identificador de instancia en una variable común y
  95. //        se crea y muestra la ventana principal del programa.
  96. //
  97. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  98. {
  99.   hInst = hInstance; // Almacenar identificador de instancia en una variable global
  100.  
  101.   // ################################################################### Begin.
  102.   // Redimensionar formulario a 300 x 300.
  103.   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
  104.      CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, nullptr, nullptr, hInstance, nullptr);
  105.   // #################################################################### End.
  106.  
  107.   if (!hWnd)
  108.   {
  109.      return FALSE;
  110.   }
  111.  
  112.   ShowWindow(hWnd, nCmdShow);
  113.   UpdateWindow(hWnd);
  114.  
  115.   return TRUE;
  116. }
  117.  
  118. //
  119. //  FUNCIÓN: WndProc(HWND, UINT, WPARAM, LPARAM)
  120. //
  121. //  PROPÓSITO:  procesar mensajes de la ventana principal.
  122. //
  123. //  WM_COMMAND  - procesar el menú de aplicaciones
  124. //  WM_PAINT    - Pintar la ventana principal
  125. //  WM_DESTROY  - publicar un mensaje de salida y volver
  126. //
  127. //
  128. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  129. {
  130.    switch (message)
  131.    {
  132. // ################################################################### Begin.
  133. // Crear botones Abrir, Cerrar y mostrar mensajes.
  134. case WM_CREATE:
  135. {
  136. HWND btnOK = CreateWindowW(
  137. L"BUTTON", // Clase del control.
  138. L"Abrir", // Etiqueta del botón.
  139. WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  140. 45, 135, // Posición respecto del client area del parent.
  141. 75, 23, // Dimensiones del control.
  142. hWnd, // --> Este es el handle de la ventana principal.
  143. (HMENU)201, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  144. hInst,
  145. nullptr);
  146.  
  147. HWND btnOK2 = CreateWindowW(
  148. L"BUTTON", // Clase del control.
  149. L"Cerrar", // Etiqueta del botón.
  150. WS_CHILD | BS_PUSHBUTTON | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  151. 165, 135, // Posición respecto del client area del parent.
  152. 75, 23, // Dimensiones del control.
  153. hWnd, // --> Este es el handle de la ventana principal.
  154. (HMENU)202, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  155. hInst,
  156. nullptr);
  157.  
  158. // Label o etiqueta.
  159. HWND edit = CreateWindowW(
  160. L"STATIC", // Clase del control.
  161. L"Hola.", // Etiqueta del botón.
  162. WS_CHILD | SS_SIMPLE | WS_VISIBLE, // Estilo del control. La clase button puede ser checkbox, radio, etc.
  163. 125, 55, // Posición respecto del client area del parent.
  164. 75, 23, // Dimensiones del control.
  165. hWnd, // --> Este es el handle de la ventana principal.
  166. (HMENU)303, // Este es el identificador del control. De modo predefinido 1 = IDOK, 2 = IDCANCEL
  167. hInst,
  168. nullptr);
  169. }
  170.  
  171. break;
  172. // #################################################################### End.
  173.  
  174.    case WM_COMMAND:
  175.        {
  176.            int wmId = LOWORD(wParam);
  177.            // Analizar las selecciones de menú:
  178.            switch (wmId)
  179.            {
  180. // #################################################################### Begin.
  181. case IDC_BUTTON_1:
  182. // MessageBox(hWnd, L"Botón 1 pulsado", L"Ejemplo", MB_OK | MB_ICONINFORMATION);
  183. // Mostrar mensaje.
  184. SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Abriendo...  ");
  185.  
  186. // Abrir bandeja del lector.
  187. mciSendString(L"set CDAudio door open", nullptr, 0, nullptr);
  188.  
  189. // Mostrar mensaje Abierto. Que es cuando ya finalizó.
  190. SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Abierto.     ");
  191. break;
  192. case IDC_BUTTON_2:
  193. // Mostrar mensaje.
  194. SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Cerrando...  ");
  195. // Cerrar bandeja del lector.
  196. mciSendString(L"set CDAudio door closed", nullptr, 0, nullptr);
  197. // Mostrar mensaje.
  198. SetWindowText(GetDlgItem(hWnd, IDC_STATIC_1), L"Cerrado.     ");
  199. break;
  200. // #################################################################### End.
  201.            case IDM_ABOUT:
  202.                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
  203.                break;
  204.            case IDM_EXIT:
  205.                DestroyWindow(hWnd);
  206.                break;
  207.            default:
  208.                return DefWindowProc(hWnd, message, wParam, lParam);
  209.            }
  210.        }
  211.        break;
  212.    case WM_PAINT:
  213.        {
  214.            PAINTSTRUCT ps;
  215.            HDC hdc = BeginPaint(hWnd, &ps);
  216.            // TODO: Agregar cualquier código de dibujo que use hDC aquí...
  217.            EndPaint(hWnd, &ps);
  218.        }
  219.        break;
  220.    case WM_DESTROY:
  221.        PostQuitMessage(0);
  222.        break;
  223.    default:
  224.        return DefWindowProc(hWnd, message, wParam, lParam);
  225.    }
  226.    return 0;
  227. }
  228.  
  229. // Controlador de mensajes del cuadro Acerca de.
  230. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
  231. {
  232.    UNREFERENCED_PARAMETER(lParam);
  233.    switch (message)
  234.    {
  235.    case WM_INITDIALOG:
  236.        return (INT_PTR)TRUE;
  237.  
  238.    case WM_COMMAND:
  239.        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
  240.        {
  241.            EndDialog(hDlg, LOWORD(wParam));
  242.            return (INT_PTR)TRUE;
  243.        }
  244.        break;
  245.    }
  246.    return (INT_PTR)FALSE;
  247. }

Saludos camaradas. ;)