c++ - Visual C++ 窗口创建失败

标签 c++ winapi visual-c++ visual-studio-2015

我最近完成了 C++ 的入门类(class),并决定跳转到 Visual C++ 尝试制作一个小应用程序。

到目前为止,我想要的只是至少创建并显示一个窗口,没有进行任何进一步的操作。 我使用了许多 Microsoft 教程来获取我拥有的代码。

请注意,我有很多评论可以帮助我理解我在做什么。 我正在使用 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);
}

最佳答案

您正在注册一个名为 "Window Class" 的窗口类,但尝试创建一个类为 "MainsWClass" 的窗口。那个类(class)不详。您需要创建一个先前已注册的窗口类的窗口(由您自己创建,或者创建一个预定义的窗口类,如 "BUTTON")。

关于c++ - Visual C++ 窗口创建失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856046/

相关文章:

c++ - 在我的文档中创建文件夹

visual-studio - 存储新类的默认目录?

c++ - 一次只能操纵一个 union 成员是什么意思?

c++ - 如何在 WinApi 中从 HANDLE 制作 FILE*?

c++ - 尝试使用 libpng 加载图像时 Windows 上出现运行时错误

c++ - SDL2 渲染纹理明显滞后于鼠标

c++ - 支持初始化 std::map 成员编译器错误

c++ - 如何修复类函数 "prototype does not match"和 "cadidate is"错误

c++ - 哪些 STL 容器需要使用 CAdapt?

winapi - Windows API - 带空格的 CreateProcess() 路径