Win32API实现的第一个窗口程序

代码

流程
在Windows上,一个窗口程序是由消息驱动的,所以创建一个窗口程序有如下几个步骤:

  • 注册窗口类,包括WNDCLASS结构体的赋值以及RegisterClass注册窗口类
  • 使用CreateWindow创建窗口以及ShowWindowUpdateWindow更新显示窗口
  • 使用GetMessageDispatchMessage建立消息循环
  • 完成处理消息的WndProc回调函数
#include 

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nCmdShow)
{
    char *lpClassName = "FirstWin", *lpWindowName = "Title";
    HWND hwnd;
    MSG msg;
    WNDCLASSEX wndclass;

    wndclass.cbSize = sizeof(wndclass);       // 指定该结构体的大小
    wndclass.style = CS_HREDRAW | CS_VREDRAW; // 宽度高度变化时重绘
    wndclass.lpfnWndProc = WndProc;           // 窗口回调函数
    wndclass.cbClsExtra = 0;
    wndclass.cbWndExtra = 0;
    wndclass.hInstance = hInstance;
    wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);    // NULL表示系统图标,默认图标
    wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);      // 默认光标
    wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); // 使用画刷填充背景色,还可以(HBRUSH)GetStockObject(BLACK_BRUSH)
    wndclass.lpszMenuName = NULL;
    wndclass.lpszClassName = lpClassName;
    wndclass.hIconSm = NULL;

    if (!RegisterClassEx(&wndclass))
    {
        MessageBox(NULL, "Register Failed", "Tips", MB_ICONERROR);
        return 0;
    }

    hwnd = CreateWindow(lpClassName,
                        lpWindowName,
                        WS_OVERLAPPEDWINDOW, //style
                        CW_USEDEFAULT,       // x
                        CW_USEDEFAULT,       // y
                        600,                 // width
                        400,                 // height
                        NULL,                // hWndParent
                        NULL,                // hMenu
                        hInstance,           // hInstance
                        NULL);
    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd); // 发送 WM_PAINT,保证窗口一定可以刷新显示

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;
    PAINTSTRUCT ps;
    RECT rect;

    switch (message)
    {
    case WM_CREATE:
        MessageBox(NULL, "Create Windows Success", "Tips", MB_OK);
        break;
    case WM_PAINT:
        hdc = BeginPaint(hwnd, &ps);
        GetClientRect(hwnd, &rect);
        DrawText(hdc, "HelloWorld", -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        EndPaint(hwnd, &ps);
        break;
    case WM_CLOSE:
        DestroyWindow(hwnd);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}

使用gcc -m32 -mwindows win1.c -o win1.exe编译

运行结果


END

你可能感兴趣的:(windows,win32,win32api,c,消息)