Windows零基础入门:2.6 Win32第一个程序和计时文字闪烁

5145 人浏览 | 时间: 2015-08-12 14:15:36 | 作者: codexia 会员文章,禁止转载

    本节课提供了Win32第一个程序的完整的源代码,且加入了计时和文字闪烁功能,对这个程序的整体思路做了简单的介绍。详细的介绍就是后面我们要学习的东西。

    程序截图如下:

  闪烁文字未显示,只更新计时

#include <Windows.h>
#include <tchar.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrev, PSTR szCmdLine, int iCmdShow)
{
    static TCHAR szExeName[] = _T("Win32");
    HWND hwnd;
    MSG  msg;
    WNDCLASS 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);
    wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wndclass.lpszMenuName = NULL;
    wndclass.lpszClassName = szExeName;

    if (!RegisterClass(&wndclass))
    {
        MessageBox(NULL, _T("注册窗口类失败,此程序需要运行在Windows NT平台下。"), szExeName, MB_ICONERROR);
        return 0;
    }

    hwnd = CreateWindow(szExeName, _T("我的窗口标题_C++技术网"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);

    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    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;
    static int i = 0;
    WCHAR szTip[100] = { 0 };
    switch (message)
    {
    case WM_CREATE:
        MessageBox(NULL, _T("窗口正在创建"), _T("win32"), MB_ICONINFORMATION);
        SetTimer(hwnd, 0, 1000, NULL);
        return 0;
    case WM_PAINT:
        hdc = BeginPaint(hwnd, &ps);
        GetClientRect(hwnd, &rect);
        if (i % 2)
            DrawText(hdc, _T("第一个Win32程序,终于见到了。 【程序代码见C++技术网的Windows零基础入门课程文章2.6节】"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        swprintf(szTip, _T("计时:%d"), i);
        DrawText(hdc, szTip, -1, &rect, DT_SINGLELINE | DT_CENTER);
        EndPaint(hwnd, &ps);
        return 0;
    case WM_DESTROY:
        MessageBox(NULL, _T("程序即将结束!"), _T("win32"), MB_ICONINFORMATION);
        KillTimer(hwnd, 0);
        PostQuitMessage(0);
        return 0;
    case WM_TIMER:
        GetClientRect(hwnd, &rect);
        InvalidateRect(hwnd, &rect, true);
        i++;
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
当前文章为会员文章,请前往[用户中心]开通会员后继续阅读。

Win32课程菜单