【问题标题】:Win32 Window not displayingWin32 窗口不显示
【发布时间】:2016-03-29 15:16:26
【问题描述】:

我正在开发一个 directX 应用程序,并且正在尝试设置一个窗口。但问题是我的窗口没有显示,而是显示我在创建窗口失败时创建的弹出窗口。我已经多次制作窗户,现在它无法正常工作。我在例程中唯一改变的是我将应用程序切换到 64 位应用程序而不是 32 位应用程序。我有一台 64 位计算机,它应该可以工作。

main.cpp

#include "Render\window.h"

int CALLBACK WinMain(HINSTANCE appInstance, HINSTANCE prevInstance, LPSTR cmdLine, int cmdCount)
{
    Window window("Program", 800, 600);

    MSG msg = { 0 };
    while (true)
    {
        if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);

            if (msg.message == WM_QUIT) break;
        }
    }

    return 0;
}

window.h

#pragma once

#include <Windows.h>

class Window
{
private:
    const char* const m_Title;
    const int m_Width;
    const int m_Height;
    HWND m_Handler;
public:
    Window(const char* title, int width, int height);

    inline HWND GetHandler() const { return m_Handler; }
private:
    void Init();
};

window.cpp

#include "window.h"

LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    if (msg == WM_DESTROY || msg == WM_CLOSE)
    {
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, msg, wparam, lparam);
}

Window::Window(const char* title, int width, int height)
    : m_Title(title), m_Width(width), m_Height(height)
{
    Init();
}

void Window::Init()
{
    WNDCLASS windowClass;
    windowClass.style = CS_OWNDC;
    windowClass.lpfnWndProc = WinProc;
    windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
    windowClass.lpszClassName = L"MainWindow";
    RegisterClass(&windowClass);

    m_Handler = CreateWindow(L"MainWindow", (LPCWSTR)m_Title, WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, 100, 100, m_Width, m_Height, nullptr, nullptr, nullptr, nullptr);
    if (m_Handler == 0)
    {
        MessageBox(nullptr, L"Problem with creating window!", L"Error", MB_OK);
        exit(0);
    }
}

【问题讨论】:

  • 你也知道它是一个“句柄”而不是“处理程序”?

标签: c++ winapi directx-12


【解决方案1】:

您的WNDCLASS 结构包含未初始化的数据。您是否忽略了编译器警告?调用RegisterClass 时不会检查错误。 RegisterClass 很可能失败了,你不管怎样都按。

确保WNDCLASS 结构已初始化:

WNDCLASS windowClass = { 0 };

并在您调用 Win32 API 函数时检查错误。在这里,检查RegisterClass 返回的值。文档会告诉您它的含义。

值得称赞的是,您至少检查了CreateWindow 返回的值。但是文档告诉您,如果发生故障,请致电GetLastError 找出呼叫失败的原因。你没有那样做吗?我怀疑您最大的问题是您没有足够详细地阅读文档。

当您调用CreateWindow 时,您尝试将m_Title 作为窗口文本参数传递。编译器以类型不匹配错误反对。你用这个演员压制了这个错误:

(LPCWSTR)m_Title

现在,m_Titleconst char*。它不是const wchar_t*。没有多少演员可以做到这一点。不要抛弃类型不匹配错误。传递正确的类型。

要么调用CreateWindowA 并传递m_Title,要么将m_Title 更改为const wchar_t* 类型。如果您执行后者,则需要传递一个宽文本 L"Program" 而不是 "Program"

【讨论】:

  • 大声笑,初学者的错误我不知道为什么没有出现错误或警告。
猜你喜欢
  • 2011-01-29
  • 2011-09-28
  • 2020-02-16
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多