2017-01-25 1 views
0

Недавно я закончил вводный урок на C++ и решил перейти на Visual C++, чтобы попытаться сделать небольшое приложение.Не удалось создать окно Visual C++

До сих пор все, что я хочу, это хотя бы создать и показать окно, больше не идти дальше. Я использовал много учебных пособий Microsoft для получения кода, который у меня есть.

Обратите внимание, что у меня есть много комментариев, чтобы помочь мне понять, что я делаю. I`m с помощью Microsoft Visual Studio 2015

#include <tchar.h> //A Win32 character string that can be used to describe ANSI, DBCS, or Unicode strings 
        //Enclose the strings in _T() if an incompatibility error occures or (LPCWSTR)L"" 
#include <windows.h> 

// Global variable 
HINSTANCE hinst; 

//Function prototype for the window procedure so the inside of the program knows wazup 
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); 
BOOL InitApplication(HINSTANCE); 
BOOL InitInstance(HINSTANCE, int); 

//Instead of your usual console program, you get WinMain() instead of int main(int argc,char *argv[]) 
INT WINAPI wWinMain(HINSTANCE hInst, //Instance of the program being executed 
    HINSTANCE hPrevInst,    //Previous instance, not used much anymore 
    LPWSTR lpCmdLine,    //Holds command line arguments 
    INT nShowCmd)     //Tells how the program should start(minumised, maximised...) 
{ 
    /*Steps to create a window: 
     - Register a window class 
     - Create the window 
     - Show the window 
     - Setup a callback procedure 
    */ 

    //We can tell if the window class has failed if RegisterClassEx() returns 0. 
    //Fortunatley, there is another handy function, namely GetLastError(). 
    //GetLastError() will return an error code, which can then be used to track down the cause of the error. 
    //https://msdn.microsoft.com/en-us/library/ms681381.aspx 
    if (!InitApplication(hInst)) 
    { 
     int nResult = GetLastError(); 
     MessageBox(NULL, 
      _T("Window class creation failed"), 
      _T("Window Class Failed"), 
      MB_ICONERROR); 
     return 1; 
    } 
    //Window creation & display: 
    if (!InitInstance(hInst, nShowCmd)){ 
     int nResult = GetLastError(); 
     MessageBox(NULL, 
      _T("Window creation failed"), 
      _T("Window Creation Failed"), 
      MB_ICONERROR); 
     return 1; 
    } 

    //The windows 'callback procedure' is necessary to continue 
    MSG msg; //Message handler 
    ZeroMemory(&msg, sizeof(MSG)); 
    //Main loop for the program 
    while (GetMessage(&msg, NULL, 0, 0)) 
    { 
     TranslateMessage(&msg);//translates virtual key messages to character messages 
     DispatchMessage(&msg); //Sends any messages to the callvack procedure, so it can be handled 
    } 
    //Still returns an int! 
    return 0; 
} 

BOOL InitApplication(HINSTANCE hinstance) 
{ 
    //The window class defines the overall 'look and feel' of the window that we want to create. 
    //First we create an instance of a window class 
    WNDCLASSEX wClass; 
    //For more about WNDCLASSEX: https://msdn.microsoft.com/en-us/library/ms633577(VS.85).aspx 

    //Clearing all the parameters of the WNDCLASSEX instance wClass to zero 
    ZeroMemory(&wClass, sizeof(WNDCLASSEX)); 
    //Now we are setting up all sotrts of parameters for our instance: 
    wClass.cbClsExtra = NULL;      // cbClsExtra   Additional parameters 
    wClass.cbSize = sizeof(WNDCLASSEX);    // cbSize    Specifies the size of the window class 
    wClass.cbWndExtra = NULL;      // cbWndExtra   Additional parameters 
    wClass.hbrBackground = (HBRUSH)COLOR_WINDOW; // hbrBackground  Sets background color for the window 
    wClass.hCursor = LoadCursor(NULL, IDC_ARROW); // hCursor    The cursor that will appear in the window 
    wClass.hIcon = NULL;       // hIcon    Icon for the window 
    wClass.hIconSm = NULL;       // hIconSm    Small icon for the window 
    wClass.hInstance = hinstance;     // hInstance   Handle to the application instance 
    wClass.lpfnWndProc = (WNDPROC)WinProc;   // lpfnWndProc   The callback procedure (more on that later) 
    wClass.lpszClassName = _T("Window Class");  // lpszClassName  The unique name of the window class 
    wClass.lpszMenuName = NULL;      // lpszMenuName  Used for menus 
    wClass.style = CS_HREDRAW | CS_VREDRAW;   // style    The look and feel of the window 

    // Register the window class. 
    return RegisterClassEx(&wClass); 
} 

BOOL InitInstance(HINSTANCE hinstance, int nCmdShow) 
{ 
    // Save the application-instance handle. 
    hinst = hinstance; 
    // Create the main window. 
    //CreateWindowEx returns a HWND 
    HWND hwnd = CreateWindowEx( // A "handle" is a generic identifier + like "new" 
     0,      // DWORD, extended window style of the window being created https://msdn.microsoft.com/en-us/library/windows/desktop/ff700543(v=vs.85).aspx 
     _T("MainsWClass"),  // LPCTSTR, A null-terminated string or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. 
     _T("Sample"),   // LPCTSTR, The window name. 
     WS_OVERLAPPEDWINDOW,  // DWORD, Style of the window created 

     CW_USEDEFAULT,   // int, X - default horizontal position 
     CW_USEDEFAULT,   // int, Y - default vertical position 
     CW_USEDEFAULT,   // int, nWidth - default width 
     CW_USEDEFAULT,   // int, nHeight - default height 

     (HWND)NULL,    // HWND, hWndParent - handle to the parrent or owner window of the window being created (opptional for pop-up) 
     (HMENU)NULL,    // HMENU, hMenu 
     hinstance,    // HINSTANCE, hInstance - A handle to the instance of the module to be associated with the window. 
     (LPVOID)NULL);   // LPVOID, Pointer to a value to be passed to the window through the CREATESTRUCT structure 

    //If the creation fails, returns FALSE 
    if (!hwnd) 
     return FALSE; 
    else{ 
     // Show the window and send a WM_PAINT message to the window procedure. 
     ShowWindow(hwnd, nCmdShow); 
     UpdateWindow(hwnd); 
     return TRUE; 
    } 
} 

//callback procedure 
LRESULT CALLBACK WinProc(
    HWND hWnd,  //Handle of the window that we want to monitor 
    UINT msg,  //Message we are receiving 
    WPARAM wParam, //Additionnal info for the received message 
    LPARAM lParam) 
{ 
    switch (msg) 
    { 
    case WM_DESTROY: //Message sent to the application if the program was closed using the X on the top of the window 
    { 
     PostQuitMessage(0); 
     return 0; 
    } 
    break; 
    } 

    return DefWindowProc(hWnd, msg, wParam, lParam); 
} 
+1

* Где * ваша программа не работает? И что такое [код ошибки] (https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381 (v = vs.85) .aspx), возвращаемый 'GetLastError'? –

+1

Вы * действительно * не хотите запускать программирование пользовательского интерфейса, как это; см. https://msdn.microsoft.com/en-us/windows/uwp/get-started/create-a-basic-windows-10-app-in-cpp для лучшего маршрута. –

+0

В дополнение к тому, что заявил @Someprogrammerdude - используйте отладчик, чтобы выяснить, где ваша программа терпит неудачу. –

ответ

2

Вы регистрируете класс окна с именем "Window Class", но попытаться создать окно класса "MainsWClass". Этот класс неизвестен. Вам необходимо создать окно класса окна, которое ранее было зарегистрировано (либо самостоятельно, либо один из предварительно определенных классов окон, например "BUTTON").

+0

Большое вам спасибо. Не понимал, что это то, что должно туда идти! – Artur

+0

@Artur: Это то же, что вы тоже прокомментировали: '// LPCTSTR, строка с нулевым символом или атом класса, созданный предыдущим вызовом функции RegisterClass или RegisterClassEx.' – IInspectable

Смежные вопросы