Windows 应用程序的入口函数编写

写任何一个函数当然应该有一个该函数的入口了。我们知道c语言里的入口函数是main()函数,那么在写Windows应用程序也是main()吗?回答当然不是了。我们用的是WinMain()函数,不过我们在写MFC程序的时候好象没有看到该函数,其实这是微软为了帮助我们快速写一个基于Windows应用程序,而把它封装起来了,当然我们也是可以找到的。在这里,我们试着自己编写一个WinMain()函数。好了,我们进入主题吧!首先,我们要包含一些库。 
#include <windows.h>
#include <stdio.h>

还有,我们应该学会使用msdn快速查找到我们所需要的信息。
这里,windows是基于消息的应用程序,我们应该先编写一个消息响应函数,即一个回调函数。LRESULT CALLBACK WinMYProc(
  HWND hWnd, // handle to window
  UINT uMsg, // message identifier
  WPARAM wParam, // first message parameter
  LPARAM lParam // second message parameter
);

接下来是WinMain int WINAPI WinMain(
  HINSTANCE hInstance, // handle to current instance
  HINSTANCE hPrevInstance, // handle to previous instance
  LPSTR lpCmdLine, // command line
  int nCmdShow // show state
)
{
WNDCLASS wndcls;//注册窗口类
wndcls.cbClsExtra=0;
 wndcls.cbWndExtra=0;
 wndcls.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);//窗口画刷
 wndcls.hCursor=LoadCursor(NULL,IDC_ARROW);//鼠标
 wndcls.hIcon=LoadIcon(NULL,IDI_WINLOGO);//图标
 wndcls.hInstance=hInstance;//窗口实例
 wndcls.lpfnWndProc=WinMYProc;//窗口函数
 wndcls.lpszClassName="BEYOND";//窗口类名
 wndcls.lpszMenuName=NULL;//菜单名(这里为空)
 wndcls.style=CS_HREDRAW | CS_VREDRAW;//窗口风格(水平重绘和垂直重绘)
 RegisterClass(&wndcls);//注册窗口

//注册完窗口,接着是创建和显示窗口了
HWND hWnd;
hWnd=CreateWindow("BEYOND",lovebeyond",WS_OVERLAPPEDWINDOW,
  0,0,600,400,NULL,NULL,hInstance,NULL);
 ShowWindow(hwnd,SW_SHOWNORMAL);//显示
 UpdateWindow(hWnd);//更新

//接下来是消息循环了
 MSG msg;
 while(GetMessage(&msg,NULL,0,0))//当不为WM_QUIT时,继续消息循环
 {
  TranslateMessage(&msg);//用于翻译消息
  DispatchMessage(&msg);//发送消息
 }
 return msg.wParam;//返回一个参数
}


//消息响应函数
LRESULT CALLBACK WinMYProc(
  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 szChar[20];
  sprintf(szChar,"char is %d",wParam);
  MessageBox(hWnd,szChar,"char",0);
  break;
 case WM_LBUTTONDOWN://鼠标左键按下
  MessageBox(hWnd,"mouse clicked","message",0);
  break;
 case WM_PAINT://窗口重绘消息
  HDC hDC;
  PAINTSTRUCT ps;
  hDC=BeginPaint(hWnd,&ps);
  TextOut(hDC,0,0,"lovebeyond",strlen("lovebeyond"));
  EndPaint(hwnd,&ps);
  break;
 case WM_CLOSE://关闭消息
  if(IDYES==MessageBox(hWnd,"想要结束吗?","message",MB_YESNO))
  {
  DestroyWindow(hWnd);
  }
  break;
 case WM_DESTROY://销毁窗口消息
  PostQuitMessage(0);
  break;
 default://默认窗口消息处理
  return DefWindowProc(hWnd,uMsg,wParam,lParam);
 }
 return 0;
}

posted @ 2009-07-31 23:49  Dick.Gu  阅读(532)  评论(0编辑  收藏  举报