WindowsAPI笔记(二)---动手写第一个Windows程序

#include <windows.h>
#include <iostream>
#include <stdio.h>
using namespace std;

const string ProgramTitle = "Hello Windows";


LRESULT CALLBACK WinProc(HWND hWnd,
						 UINT message, 
						 WPARAM wParam,
						 LPARAM lParam)
{
	string text = "Hello Windows!";
	switch (message)
	{
		case WM_CHAR:
			char szChar[20];
			sprintf(szChar,"char code is %d",wParam);
			MessageBox(hWnd,szChar,"char",0);
			break;

		case WM_CLOSE:
			if(IDYES==MessageBox(hWnd,"是否真的结束?","message",MB_YESNO))
				{
					 DestroyWindow(hWnd);
				}
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
	}

	return 0;
}


//设置程序所需的主窗口类的值。
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wc;

	wc.cbSize			= sizeof(WNDCLASSEX);
	wc.style			= CS_HREDRAW | CS_VREDRAW;			//窗口样式
	wc.lpfnWndProc    	= (WNDPROC)WinProc;					//指向一个回调函数的长指针
	wc.cbClsExtra		= 0;
	wc.cbWndExtra		= 0;								//增加一些额外的内存空间
	wc.hInstance		= hInstance;						//传递给MyRegisterClass的hInstance参数值。主窗口需要知道正在使用的是哪个实例。
	wc.hIcon			= NULL;								
	wc.hCursor		    = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground	= (HBRUSH)GetStockObject(WHITE_BRUSH);//用于绘制程序窗口背景的一个刷子句柄。
	wc.lpszMenuName 	= 0;								//程序菜单名称
	wc.lpszClassName	= ProgramTitle.c_str();				//给窗口指定特定的类名称。
	wc.hIconSm		    = NULL;

	return RegisterClassEx(&wc);
}


//用于创立程序,基本上只创建程序窗口。
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd = CreateWindow(
		ProgramTitle.c_str(),
		ProgramTitle.c_str(),
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,CW_USEDEFAULT,
		640,480,
		NULL,
		NULL,
		hInstance,
		NULL);

   if (hWnd==0)
   {
      return 0;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return 1;
}



int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	MyRegisterClass(hInstance);
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	MSG msg;
	BOOL bRet;
	// 主消息循环:
	while ((bRet=GetMessage(&msg, NULL, 0, 0))!=0)
	{
		if (bRet==-1) break;
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return (int) msg.wParam;
}


posted on 2013-02-12 23:26  电子幼体  阅读(296)  评论(0编辑  收藏  举报

导航