基于SDK的Win32窗口创建


#include "stdafx.h"
HINSTANCE g_hInstance = NULL;

// 主窗口处理函数
LRESULT CALLBACK WndProc (HWND hWnd, UINT uMsg,
                      WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage (0);
        break;
    }

    return DefWindowProc (hWnd, uMsg, wParam, lParam);
}

// 注册窗口类
void Register (LPSTR lpClassName, WNDPROC wndproc)
{
    WNDCLASSEX wce    = {0};
    wce.cbSize        = sizeof (wce);
    wce.cbClsExtra    = 0;
    wce.cbWndExtra    = 0;
    wce.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wce.hCursor       = NULL;
    wce.hIcon         = NULL;
    wce.hIconSm       = NULL;
    wce.hInstance     = g_hInstance;
    wce.lpfnWndProc   = wndproc;
    wce.lpszClassName = lpClassName;
    wce.lpszMenuName  = NULL;
    wce.style         = CS_HREDRAW | CS_VREDRAW;

    ATOM atom = RegisterClassEx (&wce);
    if (atom == 0)
    {
        MessageBox (NULL, "注册失败", "Info",MB_OK);
    }
}

// 创建主窗口
HWND CreateMain (LPSTR lpClassName, LPSTR lpWndName)
{
    HWND hWnd = CreateWindowEx(0, lpClassName,
                       lpWndName, WS_OVERLAPPEDWINDOW,
                   CW_USEDEFAULT, CW_USEDEFAULT,
                   CW_USEDEFAULT, CW_USEDEFAULT,
                            NULL, NULL,
                     g_hInstance, NULL);
                            
    return hWnd;
}

// 显示窗口
void Display (HWND hWnd)
{
    ShowWindow (hWnd, SW_SHOW);
    UpdateWindow (hWnd);
}

// 消息循环
void Message ()
{
    MSG msg = {0};
    while (GetMessage (&msg, NULL, 0, 0))
    {
        TranslateMessage (&msg);
        DispatchMessage (&msg);
    }
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // TODO: Place code here.
    g_hInstance = hInstance;
    Register ("MAIN", WndProc);
    HWND hWnd = CreateMain ("MAIN", "window");
    Display (hWnd);
    Message ();
    return 0;
}

你可能感兴趣的:(Win32)