为什么我的线只在我显示消息框时绘制?

时间:2018-01-02 03:32:32

标签: windows user-interface

engine.cpp:

#ifndef UNICODE
#define UNICODE
#endif

#include "draw.h"

#include <windows.h>


HWND *window;

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void startEngine();

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) {
    // Register the window class.
    const wchar_t CLASS_NAME[] = L"Sample Window Class";

    WNDCLASS wc = {};

    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    // Create the window.

    HWND hwnd = CreateWindowEx(
        0,
        CLASS_NAME,
        L"title",
        WS_OVERLAPPEDWINDOW,

        //Size and position
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

        NULL, // Parent window
        NULL, // Menu
        hInstance, //Instnace handle
        NULL //Additional application data
    );

    window = &hwnd;

    if (hwnd == NULL)
    {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) startEngine, NULL, 0, NULL);

    // Run the message loop.
    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    case WM_PAINT:
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);
        FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
        EndPaint(hwnd, &ps);
        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

void startEngine() {
    MessageBox(*window, L"Message box working!", L"Confirmation", MB_OK);
    drawLine(100, 100, 200, 200, RGB(256, 0, 0));
}

draw.cpp:

#include "draw.h"
#include <Windows.h>

extern HWND *window;

void drawLine(int x1, int y1, int x2, int y2, COLORREF color) {
    HDC hDC = GetDC(*window);
    int slope = (y2 - y1) / (x2 - x1);
    while (x1 != x2 && y1 != y2) {
        if (SetPixel(hDC, x1, y1, color) == ERROR_INVALID_PARAMETER) {
            MessageBox(*window, "Invalid parameter to SetPixel in drawLine()", NULL, MB_OK);
            exit(EXIT_FAILURE);
        }
        x1 += slope;
        y1 += slope;
    }
    ReleaseDC(*window, hDC);
}

void drawSquare(int xPos, int yPos, int size, COLORREF color) {
    drawLine(xPos, yPos, xPos, yPos + size, color);
    drawLine(xPos + size, yPos, xPos + size, yPos + size, color);
    drawLine(xPos, yPos + size, xPos + size, yPos + size, color);
    drawLine(xPos, yPos, xPos + size, yPos, color);
}

所以我正在通过编写一个程序来学习GUI编程,该程序会将很少的形状绘制到窗口中。出于某种原因,startEngine()中的行仅在我显示消息框时绘制。为什么这样做?

此外,如果我做了其他任何错误,请随时纠正我。我真的想确保我以正确的方式做这些事情,而不仅仅是以一种有效的方式。

0 个答案:

没有答案