您的位置:首页 > 其它

windows API 生成一个窗口简单例子

2015-06-05 23:55 471 查看
这是一个利用windows里的API所创建的一个窗口例子,

我碰到的问题:

1.WinMain相当于 main 函数

2. LRESULT CALLBACK WinSunProc(),CALLBACK是回调的意思。这个函数是用来调用RegisterClass注册过的窗口,然后处理窗口消息。

3.HDC,MFC中的设备上下文句柄,HDC设备上下文是一种包含有关某个设备(如显示器或打印机)的绘制属性信息的 Windows 数据结构。

#include <windows.h>
#include <stdio.h>

//函数声明
LRESULT CALLBACK WinSunProc(
HWND hwnd,      // handle to window
UINT uMsg,      // message identifier
WPARAM wParam,  // first message parameter
LPARAM lParam   // second message parameter
);

int WINAPI WinMain(
HINSTANCE hInstance,      // handle to current instance   当前实例句柄
HINSTANCE hPrevInstance,  // handle to previous instance	先前实例句柄
LPSTR lpCmdLine,          // command line					命令行
int nCmdShow              // show state					呈现方式 cmd窗口
)
{
WNDCLASS wndcls;													//先创建一个窗口类
wndcls.cbClsExtra=0;												//窗口扩展
wndcls.cbWndExtra=0;												//窗口实例扩展
wndcls.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);			//窗口背景色 要转换成HBRUSH型的 所以要加
wndcls.hCursor=LoadCursor(NULL,IDC_ARROW);							//光标
wndcls.hIcon=LoadIcon(NULL,IDI_ERROR);								//图标
wndcls.hInstance=hInstance;											//句柄实例
wndcls.lpfnWndProc=WinSunProc;										//窗口处理函数
wndcls.lpszClassName="xiaoout";										//窗口类名
wndcls.lpszMenuName=NULL;											//窗口菜单
wndcls.style=CS_HREDRAW | CS_VREDRAW;								//窗口风格
RegisterClass(&wndcls);												//注册窗口

HWND hwnd;															//窗口句柄
hwnd=CreateWindow("xiaoout","第一次编",WS_OVERLAPPEDWINDOW,
200,100,600,400,NULL,NULL,hInstance,NULL);						//创建窗口函数

ShowWindow(hwnd,SW_SHOWNORMAL);										//展现窗口函数
UpdateWindow(hwnd);													//刷新窗口函数

MSG msg;															//消息类
while(GetMessage(&msg,NULL,0,0))									//循环获取消息
{
TranslateMessage(&msg);		//该函数将虚拟键消息转换为字符消息。字符消息被寄送到调用线程的消息队列里,当下一次线程调用函数GetMessage或PeekMessage时被读出。
DispatchMessage(&msg);		//该函数分发一个消息给窗口程序
}
return 0;
}

LRESULT CALLBACK WinSunProc(
HWND hwnd,      // handle to window
UINT uMsg,      // message identifier
WPARAM wParam,  // first message parameter
LPARAM lParam   // second message parameter
)
{
switch(uMsg)
{
case WM_CHAR:                     //处理按键所对应字符的消息,只能处理ASCII字符码值中0-127的码按键
char szChar[20];
sprintf(szChar,"char is %d",wParam);
MessageBox(hwnd,szChar,"xiao",0);
break;
case WM_LBUTTONDOWN:				//鼠标左键按下响应
MessageBox(hwnd,"mouse clicked","out",MB_OK);
HDC hdc;				//device context 设备描述表 设备上下文
hdc=GetDC(hwnd);
TextOut(hdc,100,100,"xiaoout",strlen("xiaoout"));
//TextOut 文本输出函数 hdc x坐标 y坐标 内容 内容长度
ReleaseDC(hwnd,hdc);
break;
case WM_PAINT:
HDC hDC;
PAINTSTRUCT ps;
hDC=BeginPaint(hwnd,&ps);
TextOut(hDC,0,0,"xiaoout",strlen("xiaoout"));
EndPaint(hwnd,&ps);
break;
case WM_CLOSE:
//常量写前面 容易找错
if(IDYES==MessageBox(hwnd,"是否真的结束?","xiaoout",MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}


有兴趣和我一起做c++小项目,可以加群457555870一起交流。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: