当前位置:编程学习 > C/C++ >>

Win32窗口程序(C++)

编者按:MFC替我们做了很多工作,学习下详细流程还是很必要的。

效果图:

// Win32对话框.cpp : Defines the entry point for the application.

//

 

#include "stdafx.h"

 

//定义窗口消息响应函数

LRESULT CALLBACK WndProc(HWND hwnd,

UINT uMsg,

WPARAM wParam,

LPARAM lParam)

{

HDC hdc;

RECT rect;

PAINTSTRUCT ps; //接收BeginPaint返回的客户区绘图信息

switch(uMsg)//接收GetClientRect返回的客户区坐标

{

case WM_PAINT:

{

//指针参数一般代表接收函数的返回值,即_out

hdc = BeginPaint(hwnd, &ps);

GetClientRect(hwnd, &rect);

DrawText(hdc, "http://hi.baidu.com/darks00n", -1, &rect, DT_SINGLELINE|DT_CENTER|DT_VCENTER);

EndPaint(hwnd, &ps);

break;

}

case WM_DESTROY: //窗口被关闭后终止对应线程

{

PostQuitMessage(0);

}

default:

break;

}

 

return DefWindowProc(hwnd, uMsg, wParam, lParam); //未处理的消息发给默认消息处理函数

}

 

int APIENTRY WinMain(HINSTANCE hInstance,

HINSTANCE hPrevInstance,

LPSTR lpCmdLine,

int nCmdShow)

{

//第一步.填充WNDCLASS结构体

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(BLACK_BRUSH);

wndclass.lpszMenuName = NULL;

wndclass.lpszClassName = "WND";

 

//第二步.注册窗口类

RegisterClass(&wndclass);

 

//第三步.创建窗口

HWND hwnd = CreateWindow("WND", "Win32对话框", WS_OVERLAPPEDWINDOW , CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

 

//第四步.指定显示窗口状态

ShowWindow(hwnd, nCmdShow);

 

//第五步.显示窗口(发送WM_PAINT消息)

UpdateWindow(hwnd);

 

//第六步.消息循环(不断从窗口线程消息队列中获取并处理消息)

MSG msg;

//返回值0代表WM_QUIT退出程序,-1代表获取消息失败

while (GetMessage(&msg, NULL, 0, 0) > 0 )

{

//翻译消息(将虚拟键消息转换为字符消息后,再放回窗口消息队列中)

TranslateMessage(&msg);//注意区分MFC中的PreTranslateMessage函数

//把消息发往消息响应函数(本例中即WndProc)

DispatchMessage(&msg);

}

 

return msg.wParam;

}

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,