您的位置:首页 > 编程语言

windows编程之自己动手写WinMain函数

2013-12-03 17:57 357 查看
这是我参考msdn和书本自己写的窗口程序,

WinMain函数式所有windows应用程序的入口,类似C语言里的main函数,其功能是:完成一系列的定义及初始化工作,并产生消息循环。消息循环是整个程序运行的核心 。

WinMain函数主要实现以下功能:

1.注册窗口类,建立窗口,执行其他必要的初始化的操作;

2.进入消息循环,根据从应用程序消息队列接受的消息,调用相应的处理过程;

3.当消息循环检索到WM_QUIT消息时,终止程序运行。

代码如下:

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

LRESULT CALLBACK WndProc(
  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
)
{
	WNDCLASS wndclass;

	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hInstance = hInstance;
	wndclass.lpfnWndProc = WndProc;
	wndclass.lpszClassName = "我的窗口";
	wndclass.lpszMenuName = NULL;
	wndclass.style = CS_HREDRAW | CS_VREDRAW;
	RegisterClass(&wndclass); //注册窗口类

	HWND hwnd;
	hwnd = CreateWindow("我的窗口", "窗口", WS_OVERLAPPEDWINDOW, 
		0, 0, 640, 480, NULL, NULL, hInstance, NULL);

	ShowWindow(hwnd, SW_SHOWNORMAL);
	UpdateWindow(hwnd);

	MSG Msg;
	while(GetMessage(&Msg, NULL, 0, 0))
	{
		TranslateMessage(&Msg); 
        DispatchMessage(&Msg); 
	}

	return 0;
}

LRESULT CALLBACK WndProc(
  HWND hwnd,      // handle to window
  UINT uMsg,      // message identifier
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
)
{
	switch(uMsg)
	{
	case WM_CHAR:
		char strChar[20];
		sprintf(strChar, "char is %d", wParam);
		MessageBox(hwnd, strChar, "window", MB_OK);
		break;

	case WM_LBUTTONDOWN:
		MessageBox(hwnd, "mouse left-click", "window", MB_OK);
		HDC hdc;
		hdc = GetDC(hwnd);
		TextOut(hdc, 0, 50, "hello mouse left-click", strlen("hello mouse left-click"));
		ReleaseDC(hwnd, hdc);
		break;

	case WM_RBUTTONUP:
		MessageBox(hwnd, "release mouse", "window", MB_OK);
		hdc = GetDC(hwnd);
		TextOut(hdc, 0, 80, "hello release mouse", strlen("hello release mouse"));
		ReleaseDC(hwnd, hdc);
		break;

	case WM_CLOSE:
		PostQuitMessage(0);
		break;

	case WM_DESTROY:
		DestroyWindow(hwnd);
	break;

	default:
		return DefWindowProc(hwnd, uMsg, wParam, lParam);
	}

	return 0;
}


总结:

感觉自己动手写窗口是有点难度的,因为写的不多,很多东西没记住,都要自己去查资料。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: