Sunday, October 26, 2008

UsingWin32Api----most simple window

#include < windows.h>
LRESULT CALLBACK myWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
  WNDCLASS wc;
  HWND hwnd;
  MSG msg;
  wc.cbClsExtra=0;
  wc.cbWndExtra=0;
  wc.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
  wc.hCursor=LoadCursor(NULL,IDC_ARROW);
  wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
  wc.hInstance=hInstance;
  wc.lpfnWndProc=myWindowProc;
  wc.lpszClassName="myClass";
  wc.lpszMenuName=NULL;
  wc.style=CS_HREDRAW|CS_VREDRAW;
  RegisterClass(&wc);
  hwnd=CreateWindow("myClass", "myWindow", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 600, 400, NULL, NULL, hInstance, 0);
  ShowWindow(hwnd,nShowCmd);
  UpdateWindow(hwnd);
  while(GetMessage(&msg, NULL, 0, 0))
  {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  return msg.wParam;
}
LRESULT CALLBACK myWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch(msg)
  {
  case WM_CREATE:
    MessageBox(hwnd, "this is WM_CREATE message", "Message", 0);
    break;
  case WM_LBUTTONDOWN:
    MessageBox(hwnd, "this is WM_LBUTTONDOWN message", "Message", 0);
    break;
  case WM_DESTROY:
    MessageBox(hwnd, "this is WM_DESTROY message", "Message", 0);
    PostQuitMessage(0);
    break;
  default:
    return DefWindowProc(hwnd, msg, wParam, lParam);
  }
  return 0;
}

--------------------------------------------------------------------------------

This is the most simple window.

function "myWindowProc" which called callback funtion, is called by OS, so we don't have to invoke it. but we have to design it for processes messages which is sent to a window.

"WNDCLASS" is a struct contains the window class attributes. after you set up it, don't forget using "RegisterClass" to register it.

for this program, when "CreateWindow" is called, OS will send a WM_CREATE message to the window procedure. so if we have defined some activities for it, then the activities will be executed when callback funtion get it, just like what i do for WM_CREATE, WM_LBUTTONDOWN and WM_DESTROY.

after you create your window which is mean you call "CreateWindow" function, your window will not show itself immediately. you still have to call "ShowWindow" to show it.

after all of them, you program will go into a message loop. at this time, your program will be waiting for message until it get WM_QUIT. all message will be executed in callback function. and that is the system that the program has. taking care, WM_DESTROY is just destory the window that you see, and the program is still running on your computer.

at last, don't forget to return a "DefWindowProc", so that the message you don't care about will be done in a default way.

No comments:

Post a Comment