37
Win32 Programing 2007. 5. 25 ( 금 ) 금 금 금 [email protected]

Win32 Programing

  • Upload
    lali

  • View
    103

  • Download
    5

Embed Size (px)

DESCRIPTION

Win32 Programing. 2007. 5. 25 ( 금 ) 김 희 준 [email protected]. Contents. Window Programming Architecture 메시지 처리와 창 출력 자식 창 처리 리소스 처리. Window Programming Architecture. API(Appication Programming Interface) 예제프로젝트 윈도우 프로그램 구조의 특징 SDK61.cpp 파일 분석. API (Appication Programming Interface). - PowerPoint PPT Presentation

Citation preview

Page 1: Win32 Programing

Win32 Programing

2007. 5. 25 ( 금 )김 희 준

[email protected]

Page 2: Win32 Programing

Contents

Window Programming Architecture

메시지 처리와 창 출력

자식 창 처리

리소스 처리

Page 3: Win32 Programing

Window Programming Architecture

API(Appication Programming Interface)

예제프로젝트

윈도우 프로그램 구조의 특징

SDK61.cpp 파일 분석

Page 4: Win32 Programing

API (Appication Programming Interface) 자원 사용을 위해 운영체제에게 서비스를 요청할 때 서비스 요청과

관련하여 응용 프로그램에서 지켜야 할 규칙

DOS / UNIX : 자신만의 API 를 지원하는 OS 로 설계

윈도우계열 OS : 여러 API 를 지원하는 OS 로 설계▲ Windows NT : DOS API, Win16 API, Win32 API,

POSIX(Portable Operating System Interface)

OS/2 Console API 등 여러 종류의 API 들을 지원

주의사항 : 프로그램 내에서는 한가지 API 만으로 응용프로그램을 작성해야 함

Page 5: Win32 Programing

Example Project

Win32 API 함수를 사용하여 응용프로그램 작성

Example

▲ 프로그램은 창을 가지며 , 창 중앙에 "Hello! Win32 API Program" 라는 문자열을

출력

Page 6: Win32 Programing

Example Project

개발과정

Prototype ModificationPrototype ModificationPrototype ModificationPrototype Modification

Prototype CreationPrototype Creation

▲( APPlication 선택 대화상자 A Typical “Hello World!” application 선택 )

Prototype CreationPrototype Creation

▲( APPlication 선택 대화상자 A Typical “Hello World!” application 선택 )

Page 7: Win32 Programing

Example Project

File 메뉴에서 New -> Projects(Win32 Application )▲ Name 및 Location 입력

▲클 릭

Page 8: Win32 Programing

Example Project

Win32 Application 대화상자에서 A Typical "Hello World!" application 를 선택

▲클 릭

Page 9: Win32 Programing

Example Project

New Project Information 대화상자에서 OK 버튼을 클릭

▲클 릭

Page 10: Win32 Programing

Example Project

Build 메뉴의 Rebuild All 서브메뉴 선택▲ Execute 서브메뉴 선택

Page 11: Win32 Programing

Example Project

Workspace Window

Dialog 목록대화상자 자원

Dialog 목록대화상자 자원

Icon 목록아이콘으로 사용되는 아이콘 비트맵 자원

Icon 목록아이콘으로 사용되는 아이콘 비트맵 자원

Menu 목록메뉴 자원

Menu 목록메뉴 자원

String Table 목록프로젝트에서 사용되는 문자열 자원

String Table 목록프로젝트에서 사용되는 문자열 자원

Resource Files 목록프로젝트에 사용되는 자원 파일

Resource Files 목록프로젝트에 사용되는 자원 파일

External Dependencies 목록프로젝트에서 사용되는 프로젝트 바깥의 파일 목록

External Dependencies 목록프로젝트에서 사용되는 프로젝트 바깥의 파일 목록

프로그램을 실제로 진행시키는 응용 프로그램의 소스 파일

Page 12: Win32 Programing

Example Project

SDK61.cpp// SDK61.cpp : Defines the entry point for the application.//#include "stdafx.h"#include "resource.h"

#define MAX_LOADSTRING 100

// Global Variables:HINSTANCE hInst; // current instanceTCHAR szTitle[MAX_LOADSTRING]; // The title bar textTCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text

// Foward declarations of functions included in this code module:ATOM MyRegisterClass(HINSTANCE hInstance);BOOL InitInstance(HINSTANCE, int);LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){ // TODO: Place code here.

MSG msg;HACCEL hAccelTable;

Page 13: Win32 Programing

Example Project// Initialize global stringsLoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);LoadString(hInstance, IDC_SDK61, szWindowClass,

MAX_LOADSTRING);MyRegisterClass(hInstance);// Perform application initialization:if (!InitInstance (hInstance, nCmdShow)) {

return FALSE;}hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_SDK61);

// Main message loop:while (GetMessage(&msg, NULL, 0, 0)) {

if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {

TranslateMessage(&msg);DispatchMessage(&msg);

}}

return msg.wParam;}//// FUNCTION: MyRegisterClass()// PURPOSE: Registers the window class.//

Page 14: Win32 Programing

Example Project// COMMENTS:// This function and its usage is only necessary if you want this code// to be compatible with Win32 systems prior to the 'RegisterClassEx'// function that was added to Windows 95. It is important to call this function// so that the application will get 'well formed' small icons associated// with it.ATOM MyRegisterClass(HINSTANCE hInstance){

WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW;wcex.lpfnWndProc = (WNDPROC)WndProc;wcex.cbClsExtra = 0;wcex.cbWndExtra = 0;wcex.hInstance = hInstance;wcex.hIcon = LoadIcon(hInstance,(LPCTSTR)IDI_SDK61);wcex.hCursor = LoadCursor(NULL, IDC_ARROW);wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);wcex.lpszMenuName = (LPCSTR)IDC_SDK61;wcex.lpszClassName = szWindowClass;wcex.hIconSm = LoadIcon(wcex.hInstance,(LPCTSTR)IDI_SMALL);

return RegisterClassEx(&wcex);}

// FUNCTION: InitInstance(HANDLE, int)// PURPOSE: Saves instance handle and creates main window//// COMMENTS:

Page 15: Win32 Programing

Example Project// In this function, we save the instance handle in a global variable and// create and display the main program window.BOOL InitInstance(HINSTANCE hInstance, int nCmdShow){ HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL,

hInstance, NULL); if (!hWnd) { return FALSE; }ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE;}// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)// PURPOSE: Processes messages for the main window.// WM_COMMAND- process the application menu// WM_PAINT - Paint the main window// WM_DESTROY - post a quit message and returnLRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){

int wmId, wmEvent;

Page 16: Win32 Programing

Example ProjectPAINTSTRUCT ps;HDC hdc;TCHAR szHello[MAX_LOADSTRING];LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);switch (message) { case WM_COMMAND: wmId = LOWORD(wParam);

wmEvent = HIWORD(wParam); // Parse the menu selections:switch (wmId){case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX,

hWnd, (DLGPROC)About); break;case IDM_EXIT: DestroyWindow(hWnd); break;default: return DefWindowProc(hWnd, message, wParam, lParam);}break;case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... RECT rt; GetClientRect(hWnd, &rt);

Page 17: Win32 Programing

Example Project DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER ); EndPaint(hWnd, &ps); break;case WM_DESTROY: PostQuitMessage(0); break;default: return DefWindowProc(hWnd, message,wParam, lParam);

} return 0;}// Mesage handler for about box.LRESULT CALLBACK About(HWND hDlg, UINT message,

WPARAM wParam, LPARAM lParam){

switch (message){ case WM_INITDIALOG: return TRUE;

case WM_COMMAND:if (LOWORD(wParam) == IDOK

| | LOWORD(wParam) == IDCANCEL) {

EndDialog(hDlg, LOWORD(wParam));return TRUE;

}break;

} return FALSE;}

Page 18: Win32 Programing

Example Project

Prototype Modification

▲ SDK61.cpp 파일의 메인 창인 윈도우 Procedure Wnd_Proc 함수의 WM_PAINT case 레이블에서 문자열을 출력하는 부분 변경

▲ 출력되는 문자열의 내용을 “Hello! Win32 API program” 으로 변경

DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER ) ;DrawText(hdc, szHello, strlen(szHello), &rt, DT_SINGLELINE | DT_CENTER | DT_VCENTER ) ;

Hello! Win32 API program

ID 가 IDS_HELLO인자원을 더블 클릭

Caption : 상자의 내용을 원하는 문자열로

편집

리소스 뷰 페이지의 String Table

목록

Page 19: Win32 Programing

Example Project

Build 메뉴의 Rebuild All 서브메뉴 선택▲ Execute 서브메뉴 선택

Page 20: Win32 Programing

윈도우 프로그램의 구조의 특징 윈도우 프로그램은 WinMain 함수와 나머지 구성 요소들로 이루어짐

대부분의 윈도우 프로그램은 자신의 창을 가지는 데 , 이때의 창은 보통 메인 창과 여러 개의 자식 창으로 구성됨

메인 창의 경우 창의 속성을 운영체제에게 등록한 후 사용하여야 함

자식 창들 중에서 메뉴바 , 툴바 , 대화상자 등은 창의 모습을 리소스로 처리

창의 제어와 관련하여 프로그램 소스는 창의 모습을 관리하는 부분과 창을 통해 이루어지는 입력과 출력을 수행하는 부분 나뉨

응용프로그램은 입력 장치를 공유해야 하기 때문에 사건중심으로 작성 되어야 함 ( 즉 윈도우 프로그램의 수행 흐름의 논리적인 구조는메시지 루프와 윈도우 프로 시듀어로 구성됨 )

출력 장치를 공유 하여야 하므로 GDI(Graphic Device Interface) 서비스를 사용하여 출력을 수행

Page 21: Win32 Programing

SDK61.cpp 파일 분석

프로그램은 WinMain 함수와 나머지 함수 즉 MyRegisterClass, InitInstance, WndProc, About 등 4 개의 함수로 구성

MyRegisterClass 함수▲ 프로그램이 사용하는 메인 창의 속성을 운영체제에게 등록하는 함수

· // FUNCTION: MyRegisterClass()· // PURPOSE: Registers the window class.· // COMMENTS:· // This function and its usage is only necessary if you want this code· // to be compatible with Win32 systems prior to the 'RegisterClassEx'· // function that was added to Windows 95. It is important to call this function· // so that the application will get 'well formed' small icons associated

· // with it.

· ATOM MyRegisterClass(HINSTANCE hInstance)· {· WNDCLASSEX wcex;· wcex.cbSize = sizeof(WNDCLASSEX); · wcex.style = CS_HREDRAW | CS_VREDRAW;

· wcex.lpfnWndProc = (WNDPROC)WndProc;· wcex.cbClsExtra = 0;· wcex.cbWndExtra = 0;· wcex.hInstance = hInstance;· wcex.hIcon = LoadIcon(hInstance,(LPCTSTR)IDI_SDK61);· wcex.hCursor = LoadCursor(NULL, IDC_ARROW);· wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);· wcex.lpszMenuName = (LPCSTR)IDC_SDK61;· wcex.lpszClassName = szWindowClass;· wcex.hIconSm = LoadIcon(wcex.hInstance,(LPCTSTR)IDI_SMALL);· return RegisterClassEx(&wcex);· }

(1) WNDCLASS(EX) 구 조 형 변 수 를 준비하고 , 이 변수에 메인 창의 속성 정보들을 기록한다 .

(2) RegisterClass(EX) API 함 수 를 사 용 하 여 속 성 정보 를 운 영 체제 에게 등록하는 데 , (1) 에서 준비된 구조체를 사용하여야 한다 .

(3) WNDCLASSEX 구 조 체 의 멤 버 중 에 서 lpfnWndProc 멤 버 는 메 인 창에서 발생하는 메시지에 대한 메시지 처리루틴의 주소를 가지고 있어야 한다 .

Page 22: Win32 Programing

SDK61.cpp 파일 분석

InitInstance 함수▲ 창을 만들고 이를 화면에 띄우고 그리고 창의 내용을 조정하는 작업

· // FUNCTION: InitInstance(HANDLE, int)· // PURPOSE: Saves instance handle and creates main window· // COMMENTS:· // In this function, we save the instance handle in a global variable and· // create and display the main program window.

· BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)· {· HWND hWnd;

· hInst = hInstance; // Store instance handle in our global variable· hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,· CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, · hInstance, NULL);· if (!hWnd)· {· return FALSE;· }· ShowWindow(hWnd, nCmdShow);· UpdateWindow(hWnd);· return TRUE;· }

Page 23: Win32 Programing

SDK61.cpp 파일 분석

CreateWindow API 함수의 주요 매개변수

HWND CreateWindow(LPCTSTR lpClassName, // : RegisterClass // lpszClassName // : ( ) // ( ) "button", "edit", "scrollbar" LPCTSTR lpWindowName,

// DWORD dwStyle, // int x, // ( )int y, // ( )int nWidth, // int nHeight, // HWND hWndParent, // HMENU hMenu, // : // : idHANDLE hInstance, // LPVOID lpParam// point to a value passed to the window

) ;

Page 24: Win32 Programing

SDK61.cpp 파일 분석

WndProc 함수와 About 함수▲ 메인 창과 대화상자 창에 대한 메시지 처리루틴 ( 윈도우 프로시듀어 )

(1) 창의 핸들 , 메시지 id, 메시지의 wParam, 메시지의 IParam 등을 매개변수로 가져야 한다 .

(2) 창이 만들려 질 때 해당 함수의 주소가 창의 속성 정보들 중의 1 개로 반드시 등록되어야 한다 .

Page 25: Win32 Programing

SDK61.cpp 파일 분석

Main Window 의 Message 처리 루틴// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)//// PURPOSE: Processes messages for the main window.// WM_COMMAND- process the application menu// WM_PAINT - Paint the main window// WM_DESTROY - post a quit message and returnLRESULT CALLBACK WndProc(HWND hWnd, UINT message,

WPARAM wParam, LPARAM lParam){

int wmId, wmEvent;PAINTSTRUCT ps;HDC hdc;TCHAR szHello[MAX_LOADSTRING];LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);switch (message) {

case WM_COMMAND:wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections:

switch (wmId) {

case IDM_ABOUT:DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break;case IDM_EXIT: DestroyWindow(hWnd);break;default: return DefWindowProc(hWnd, message, wParam, lParam);

} break;case WM_PAINT:

hdc = BeginPaint(hWnd, &ps); RECT rt;GetClientRect(hWnd, &rt);DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER );EndPaint(hWnd, &ps);break;case WM_DESTROY:

PostQuitMessage(0);break;

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

Page 26: Win32 Programing

SDK61.cpp 파일 분석

About 대화상자 창의 메시지 처리 루틴// Mesage handler for about box.LRESULT CALLBACK About(HWND hDlg, UINT message,

WPARAM wParam, LPARAM lParam){ switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND:

if (LOWORD(wParam) == IDOK | | LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break;

} return FALSE;}

Page 27: Win32 Programing

SDK61.cpp 파일 분석

WinMain 함수▲ 문자중심 프로그램의 main 함수와 비슷한 역할을 수행하는 함수▲ 메시지 루프 (Message Loop) 를 구현하여 프로그램 수행의 흐름을 주도

Page 28: Win32 Programing

메시지 처리와 창 출력

예제 프로젝트 실습▲ 입력 처리

▲ 출력처리

▲ SDK62.cpp

Page 29: Win32 Programing

Example Project

메인 창의 상단에 사각형이 그려지고 창 중앙에 문자열이 출력

마우스 왼쪽 버튼과 오른쪽 버튼 입력 그리고 키 입력 등 외부 입력 장치로부터의 입력에 대한 이를 알리는 메시지들이 출력됨

또한 이러한 문자열은 Shift 키를 누르면 조금 뒤에 사라지는 데 , Shift 키의 이와 같은 기능을 알리는 문자열도 창에 출력됨

Page 30: Win32 Programing

Example Project

입력 처리▲ WndProc 함수에서 처리

· case WM_LBUTTONDOWN : // · wsprintf(m_str, " .") ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;

· case WM_RBUTTONDOWN : // · wsprintf(m_str, " .") ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;

· case WM_CHAR : // · wsprintf(m_str, "%c ", wParam) ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;

· case WM_TIMER : // · wsprintf(m_str, "") ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;

· case WM_KEYDOWN : // Shift Esacpe · switch(LOWORD(wParam))· { · case VK_ESCAPE : PostQuitMessage(0);· break;· case VK_SHIFT : SetTimer(hWnd, 1, 5000, NULL) ; // · break ; · }

Page 31: Win32 Programing

Example Project

출력처리▲ GDI 서비스를 사용하여 WndProc 함수의 WM_PAINT case

레이블에서 수행

▲ 창에 출력을 수행할 DC(Device Context) 장치를 생성 하고 이전 DC 가 사용하던 환경들을 저장

▲ 출력에 사용될 글꼴 , 펜 , 붓 , 비트맵 등등의 출력 도구들을 생성

hdc = BeginPaint(hWnd, &ps) ;

· // · Font = CreateFont(15, 7, 0, 0, 0, FAFSE, FALSE, 0,· DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,· CLIP_DEFAULT_PRECIS, DEFAULT_QUALUTY,· DEFAULT_PITCH, “ ”) ;· // · Pen = CreatePen(PS_SOLID, 2, RGB(255,0,0)) ; · // · Brush = CreateSolidBrush(RGB(0,0,200)) ;

Page 32: Win32 Programing

Example Project

출력처리▲ 기타 출력 환경들을 세팅

▲ 출력 도구들을 DC 에게 연결

SetTextColor(hdc, RGB(0,0,10)) ; // 글자 색 세팅

SetBkColor(hdc, RGB(0,255,1)) ; // 배경 색 세팅

// 출력 도구들을 DC(Device Context) 에게 전달SelectObject(hdc, Font) ;SelectObject(hdc, Pen) ; SelectObject(hdc, Brush) ;

Page 33: Win32 Programing

SDK62.cpp· // SDK62.cpp : Defines the entry point for the application.· //· #include "stdafx.h"· #include "resource.h"

· #define MAX_LOADSTRING 100

· // Global Variables:· HINSTANCE hInst; // current instance· TCHAR szTitle[MAX_LOADSTRING]; // The title bar text· TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text

· // Foward declarations of functions included in this code module:· ATOM MyRegisterClass(HINSTANCE hInstance);· BOOL InitInstance(HINSTANCE, int);· LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);· LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

· int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,· LPSTR lpCmdLine, int nCmdShow)· {· // TODO: Place code here.· MSG msg;· HACCEL hAccelTable;

· // Initialize global strings· LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);· LoadString(hInstance, IDC_SDK62, szWindowClass, MAX_LOADSTRING);· MyRegisterClass(hInstance);

· // Perform application initialization:· if (!InitInstance (hInstance, nCmdShow)) · {· return FALSE;· }· hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_SDK62);

· // Main message loop:· while (GetMessage(&msg, NULL, 0, 0)) · {· if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) · {· TranslateMessage(&msg);· DispatchMessage(&msg);· }· }· return msg.wParam;· }

· //· // FUNCTION: MyRegisterClass()· //· // PURPOSE: Registers the window class.· // COMMENTS:

Page 34: Win32 Programing

SDK62.cpp· // This function and its usage is only necessary if you want this code· // to be compatible with Win32 systems prior to the 'RegisterClassEx'· // function that was added to Windows 95. It is important to call this function· // so that the application will get 'well formed' small icons associated· // with it.· //

· ATOM MyRegisterClass(HINSTANCE hInstance)· {· WNDCLASSEX wcex;

· wcex.cbSize = sizeof(WNDCLASSEX);

· wcex.style = CS_HREDRAW | CS_VREDRAW;· wcex.lpfnWndProc = (WNDPROC)WndProc;· wcex.cbClsExtra = 0;· wcex.cbWndExtra = 0;· wcex.hInstance = hInstance;· wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_SDK62);· wcex.hCursor = LoadCursor(NULL, IDC_ARROW);· wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);· wcex.lpszMenuName = (LPCSTR)IDC_SDK62;· wcex.lpszClassName = szWindowClass;· wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

· return RegisterClassEx(&wcex);· }

· //· // FUNCTION: InitInstance(HANDLE, int)· //· // PURPOSE: Saves instance handle and creates main window· //· // COMMENTS:· //· // In this function, we save the instance handle in a global variable and· // create and display the main program window.· //

· BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)· {· HWND hWnd;· hInst = hInstance; // Store instance handle in our global variable· hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,· CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, · hInstance, NULL);· if (!hWnd)· { · return FALSE;· } · ShowWindow(hWnd, nCmdShow);· UpdateWindow(hWnd);

· return TRUE;· }

Page 35: Win32 Programing

SDK62.cpp· // FUNCTION: WndProc(HWND, unsigned, WORD, LONG)· // PURPOSE: Processes messages for the main window.· // WM_COMMAND - process the application menu· // WM_PAINT - Paint the main window

· // WM_DESTROY - post a quit message and return

· LRESULT CALLBACK WndProc(HWND hWnd, UINT message, · WPARAM wParam, LPARAM lParam)· {· int wmId, wmEvent;· PAINTSTRUCT ps;· HDC hdc;· TCHAR szHello[MAX_LOADSTRING];· LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

· static char* m_str ; // · RECT rect1 ; // · HPEN Pen ; // · HBRUSH Brush ; // · HFONT Font ; // · switch (message) · {· case WM_COMMAND:· wmId = LOWORD(wParam); · wmEvent = HIWORD(wParam); · // Parse the menu selections:· switch (wmId)· {

· case IDM_ABOUT:· DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, · hWnd, (DLGPROC)About);· break;· case IDM_EXIT:· DestroyWindow(hWnd);· break;· default:· return DefWindowProc(hWnd, message, · wParam, lParam);· }· break;

· case WM_PAINT:· // · rect1.left = 100 ;· rect1.top = 10 ;· rect1.right = 300 ;· rect1.bottom = 100 ;

· hdc = BeginPaint(hWnd, &ps);// · // TODO: Add any drawing code here...· RECT rt;· GetClientRect(hWnd, &rt);//

· SetTextColor(hdc, RGB(0,0,10)) ; // · SetBkColor(hdc, RGB(0,255,0)) ; //

Page 36: Win32 Programing

SDK62.cpp· // · Font = CreateFont(15,7,0,0,0, FALSE, FALSE,0,· DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,· CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,· DEFAULT_PITCH, " ") ;· // · Pen = CreatePen(PS_SOLID, 2, RGB(255,0,0)) ;· // · Brush = CreateSolidBrush(RGB(0,0,200)) ;

· // DC(Device Context) · SelectObject(hdc, Font) ;· SelectObject(hdc, Pen) ;· SelectObject(hdc, Brush) ;· // · DrawText(hdc, m_str, - 1, &rt, DT_SINGLELINE | · DT_CENTER | DT_VCENTER);· // · Rectangle(hdc, rect1.left, rect1.top, rect1.right, rect1.bottom) ;· // · TextOut(hdc, 50, 150, "Shift 5 .", 44) ;· KillTimer(hWnd, 1) ; // · // · DeleteObject(Font) ;· DeleteObject(Pen) ;· DeleteObject(Brush) ;· EndPaint(hWnd, &ps); // · break;

· case WM_LBUTTONDOWN : // · wsprintf(m_str, " .") ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;· case WM_RBUTTONDOWN : // · wsprintf(m_str, " .") ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;· case WM_CHAR : // · wsprintf(m_str, "%c ", wParam) ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;· case WM_DESTROY:· PostQuitMessage(0);· break;· case WM_TIMER : // · wsprintf(m_str, "") ;· InvalidateRgn(hWnd, NULL, TRUE) ;· break ;· case WM_KEYDOWN : // Shift Esacpe · switch(LOWORD(wParam))· {· case VK_ESCAPE :· PostQuitMessage(0);· break;· case VK_SHIFT :· etTimer(hWnd, 1, 5000, NULL) ; // · break ;· }

Page 37: Win32 Programing

SDK62.cpp· default :· return DefWindowProc(hWnd, message, wParam, lParam);· }· return 0;· }

· // Mesage handler for about box.

· LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, · LPARAM lParam)

· switch (message)· {· case WM_INITDIALOG:· return TRUE;· case WM_COMMAND:· if (LOWORD(wParam) == IDOK · | | LOWORD(wParam) == IDCANCEL) · {· EndDialog(hDlg, LOWORD(wParam));· return TRUE;· }· break;· }· return FALSE;· }