lap trinh windows voi vc.mfc [dh ktcn]

Upload: dang-nguyen

Post on 06-Apr-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    1/272

    Trng i hc K Thut Cng nghKhoa Cng ngh Thng tin

    GIO TRNH MN HC

    LP TRNH WINDOWS

    VI VC/MFC

    Bin son: Nguyn Chnh Thnh

    Thng 03 nm 2006

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    2/272

    Lp trnh Windows vi VC/MFC

    Trang 1

    TI LIU THAM KHO Sch:

    o Cc sch ting Vit v Visual C++ /lp trnh Windows (ca SAMIS, ca nhm tc giELICOM, hay ca cc tc gi khc)

    o Sch ting Anh: Beginning Visual C++ 6 Professional Visual C++ 6 (ca nh xut bn WROX)

    o Cc eBook ting Anh v Visual C++ hay lp trnh Windows nh: Programming Microsoft C++, 5th Edition eBook (ca Microsoft Press) Programming Windows with MFC, 2nd Edition eBook (ca Microsoft Press)

    Chng trnh tham kho:o MSDN (ba CD ti liu tham kho ca Mircosoft)o Source code mu website:

    http://www.wrox.como Cc v dc bit website:

    http://www.codeguru.com http://www.codeproject.com

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    3/272

    Lp trnh Windows vi VC/MFC

    Trang 2

    CHNG 0. N TP L THUYT C/C++0.1 n tp C0.1.1 Kiu dliu, bin v chuyn i kiu

    0.2 Hm v li gi hm0.2.1 Pht biu iu khin

    0.2.2 Array

    0.2.3 Pointer

    0.2.4 File

    0.2.5 Debug by li

    0.3 n tp C++0.3.1 Class

    0.3.2 Cu trc tha k0.3.3 Tm vc truy xut

    0.3.4 Object

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    4/272

    Lp trnh Windows vi VC/MFC

    Trang 3

    CHNG 1. CC VN CBN CA NG DNGWINDOWS V MFC

    1.1 GII THIU KHUNG NG DNG WINDOWS (WINDOWSAPPLICATION) V XY DNG CHNG TRNH MU VI MFCAPP FRAMEWORK

    1.1.1 Lp trnh WindowsLp trnh Windows l k thut lp trnh s dng cc hm Windows API xy dng cc trnh ng dng trongWindows (Window App) v cc dng ng dng khc nh DLL, ActiveX, Tuy l k thut lp trnh mnh mnhng i hi tnh chuyn nghip cao ca lp trnh vin, gii quyt k tha km, kh pht trin nhanh mt ngdng.

    1.1.2 M hnh lp trnh WindowsK thut lp trnh s dng cc hm Windows API cn gi l lp trnh Windows SDK. Mt ng dng xy dngtheo k thut ny cha ng hm WinMain (x l cc thng bo (message) nhn c/gi i nhm p ng yucu tng tc ca ngi dng v ca h thng cng nh ca ng dng khc) v hm DefWinProc (iu phi

    hot ng tng ng vi cc thng bo nhn c). T chc h thng ca ng dng Windows dng SDK nhsau:

    V d:#include

    LONG WINAPI WndProc(HWND, UINT, WPARAM, LPARAM);

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,

    LPSTR lpszCmdLine, int nCmdShow)

    {

    WNDCLASS wc;

    HWND hwnd;

    MSG msg;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    5/272

    Lp trnh Windows vi VC/MFC

    Trang 4

    wc.style = 0; // Class style

    wc.lpfnWndProc = (WNDPROC) WndProc; // Window procedure address

    wc.cbClsExtra = 0; // Class extra bytes

    wc.cbWndExtra = 0; // Window extra bytes

    wc.hInstance = hInstance; // Instance handle

    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Icon handle

    wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Cursor handle

    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); // Background color

    wc.lpszMenuName = NULL; // Menu name

    wc.lpszClassName = "MyWndClass"; // WNDCLASS name

    RegisterClass(&wc);

    hwnd = CreateWindow(

    "MyWndClass", // WNDCLASS name

    "SDK Application", // Window title

    WS_OVERLAPPEDWINDOW, // Window style

    CW_USEDEFAULT, // Horizontal positionCW_USEDEFAULT, // Vertical position

    CW_USEDEFAULT, // Initial width

    CW_USEDEFAULT, // Initial height

    HWND_DESKTOP, // Handle of parent window

    NULL, // Menu handle

    hInstance, // Application's instance handle

    NULL // Window-creation data

    );

    ShowWindow(hwnd, nCmdShow);

    UpdateWindow(hwnd);

    while(GetMessage(&msg, NULL, 0, 0)) {

    TranslateMessage(&msg);

    DispatchMessage(&msg);

    }

    return msg.wParam;

    }

    LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam,

    LPARAM lParam)

    {

    PAINTSTRUCT ps;

    HDC hdc;

    switch(message) {

    case WM_PAINT:

    hdc = BeginPaint(hwnd, &ps);

    Ellipse(hdc, 0, 0, 200, 100);

    EndPaint(hwnd, &ps);

    return 0;

    case WM_DESTROY:

    PostQuitMessage(0);

    return 0;

    }

    return DefWindowProc(hwnd, message, wParam, lParam);}

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    6/272

    Lp trnh Windows vi VC/MFC

    Trang 5

    1.1.3 Lp trnh Windows vi MFCLp trnh Windows vi MFC l k thut lp trnh s dng b th vin MFC ca Microsoft xy dng cc trnhng dng trong Windows (Window App) v cc dng ng dng khc nh DLL, COM, ActiveX

    MFC (Microsoft Foundation Classes) l th vin cscha cc lp (class) C++ do Microsoft cung cp nhmt mt trnh bao bc cho Windows API to s thun li cao cho ngi dng trong vic pht trin ng dng.Ngoi ra, MFC cn cung cp kin trc View/Document gip nh ngha cu trc chng trnh v cu trc tiliu cho trnh ng dng n gin, uyn chuyn v d pht trin hn. Do MFC cn c xem l mt khungng dng (application framework)

    Vic h trlp tha k v cc hm AFX cng nh cc lp tin ch ca MFC gip ngi dng thun tin hnvic pht trin ng dng to nhanh cc iu khin (control) trong Windows v truy xut chng nhanh chng vd dng.

    1.1.4 Mi trng lp trnh MS Visual C++Mi trng lp trnh Visual C++ bao gm:

    1.1.4.1 Min lm vic

    Khi khi ng ln u tin, vng bn tri Developer Studion c gi l min lm vic, y chnh l vng iu hnh cc phn khc nhau ca cc d n php trin (project). Min lm vic ny cho php xem cc phn cang dng theo ba cc khc nhau (nh cc hnh di y):

    Class View: cho php iu hnh v thao tc m ngun trn mc lp (class) C++

    Resource View: cho php tm v chn lc cc ti nguyn khc nhau trong ng dng nh thit k ca s hithoi, biu tng, menu, toolbar...

    File View: cho php xem v iu hnh tt c cc file trong ng dng.

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    7/272

    Lp trnh Windows vi VC/MFC

    Trang 6

    1.1.4.2 Ca sxut (output pane)

    Ca s ny nm phn di cng trong ca sng Visual C++, thng c th khng hin trn mn hnh khikhi ng ng dng Visual C++ ln u tin m s xut hin sau khi thc hin bin dch ng dng ln u tin.Phn ca s ny l ni cung cp tt c thng tin cn thit cho ngi dng nh: cc cu lnh, li cnh bo vthng bo li ca trnh bin dch, ng thi l ni chng trnh gri hin th tt c cc in vi nhng gi trhin hnh trong thi gian thc thi trong m ngun.

    1.1.4.3 Vng son tho

    y l vng bn phi ca mi trng ngi dng thc hin tt c thao tc son tho chng trnh khi sdng Visual C++, ni cc ca s son tho chng trnh hin th, ng thi l ni ca s v hin th khi ngidng thit k hp thoi.

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    8/272

    Lp trnh Windows vi VC/MFC

    Trang 7

    1.1.4.4 Thanh thc n (menu)

    Ln u tin chy Visual C++, c ba thanh cng c hin th ngay di thanh menu (menu bar). Trong VisualC++ c sn nhiu thanh cng c khc nhau, ngi dng c th ty bin to cc thanh cng c ph hp nht choring mnh.

    1.1.4.5 Thanh cng c

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    9/272

    Lp trnh Windows vi VC/MFC

    Trang 8

    1.1.5 Cc thnh phn ca ng dng pht trin vi MS Visual C++Cc thnh phn ca ng dng bao gm cc loi file lin kt nh sau:

    Cc loi file lin quan n ng dng VC++:Phn mrng Din giiAPS Supports ResourceViewBSC Browser information fileCLW Supports ClassWizardDEP Dependency fileDSP Project file*DSW Workspace file*MAK External makefile NCB Supports ClassViewOPT Holds workspace configurationPLG Builds log file

    V d tng hp:

    Hello.hclass CMyApp : public CWinApp

    {

    public:

    virtual BOOL InitInstance();

    };

    class CMainWindow : public CFrameWnd{

    public:

    CMainWindow();

    protected:

    afx_msg void OnPaint();

    DECLARE_MESSAGE_MAP()

    };

    Hello.cpp#include

    #include "Hello.h"

    CMyApp myApp;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    10/272

    Lp trnh Windows vi VC/MFC

    Trang 9

    /////////////////////////////////////////////////////////////////////////

    // CMyApp member functions

    BOOL CMyApp::InitInstance()

    {

    m_pMainWnd = new CMainWindow;

    m_pMainWnd->ShowWindow(m_nCmdShow);

    m_pMainWnd->UpdateWindow();

    return TRUE;

    }

    /////////////////////////////////////////////////////////////////////////

    // CMainWindow message map and member functions

    BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)

    ON_WM_PAINT()

    END_MESSAGE_MAP()

    CMainWindow::CMainWindow()

    {

    Create(NULL, _T("The Hello Application"));}

    void CMainWindow::OnPaint()

    {

    CPaintDC dc(this);

    CRect rect;

    GetClientRect(&rect);

    dc.DrawText(_T("Hello, MFC"), -1, &rect,

    DT_SINGLELINE DT_CENTER DT_VCENTER);

    }

    Mn hnh kt qu nh sau:

    Mt ng dng pht trin da trn tp th vin csMFC bao gm mt si tng v qu trnh x l nh sau::1.1.5.1 i tngng dng (Application)

    Trung tm ca mt ng dng MFC l i tng (application) da trn lp CWinApp. CWinApp cung cp mtvng lp thng bo nhn cc thng bo v phn phi chng cho ca sng dng. N cng bao gm cc hmo chnh yu (n m c th b khai bo v iu chnh li cc hnh vi ca ng dng). CWinApp v cc lp MFCkhc c a vo trong ng dng khi chng ta gn kt (include) file tiu Afxwin.h. ng dng MFC c thc duy nht mt i tng ng dng v i tng ng dng ny cn c khai bo vi phm vi ton cc ckhi to trong b nht lc khi im ca chng trnh.

    CMyApp (trong v d trn) khai bo khng c bin thnh vin v khai bo li (overrides) mt hm k tha tlp cha CWinApp. Hm InitInstance c gi t rt sm trong thi gian sng ca ng dng, ngay sau khi ngdng bt u thc thi nhng trc khi ca sng dng c to ra. Thc t, ngoi tr vic hm InitInstance tomt ca s cho ng dng th ng dng khng h c mt ca s. y chnh l l do thm ch mt ng dng MFC

    mc ti thiu cng cn k tha mt lp t CWinApp v khai bo li hm CWinApp::InitInstance.

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    11/272

    Lp trnh Windows vi VC/MFC

    Trang 10

    1.1.5.2 i tng Khung Ca s(Frame Window)

    Lp CWnd v cc pht sinh ca n cung cp mt giao din hng i tng cho mt hay nhiu ca s do ngdng to ra. Lp ca s chnh ca ng dng, CMainWindow, c k tha t lp CFrameWnd (cng c ktha t CWnd). Lp CFrameWnd m hnh ho cc hnh vi ca khung ca s, ng thi n l ca s mc caonht phc v nh mt giao din ch yu ca ng dng vi th gii bn ngoi. Trong ng cnh l tng ca kintrc document/view, ca s khung ng vai tr nh l mt lp cha thng minh cho cc views, toolbars, status

    bars, v cc i tng giao din ngi s dng (user-interface, UI) khc.Mt ng dng MFC to mt ca s thng qua vic to mt i tng ca s v gi hm Create hay CreateExca n c dng nh sau:

    BOOL Create (LPCTSTR lpszClassName,

    LPCTSTR lpszWindowName,

    DWORD dwStyle = WS_OVERLAPPEDWINDOW,

    const RECT& rect = rectDefault,

    CWnd* pParentWnd = NULL,

    LPCTSTR lpszMenuName = NULL,

    DWORD dwExStyle = 0,

    CCreateContext* pContext = NULL)

    1.1.5.3 Qu trnh lm vic ca cc nh x thng bo (Message Map)

    Qu trnh lm vic ny kho st cc macro DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, vEND_MESSAGE_MAP trong Afxwin.h v m lnh cho hm CWnd::WindowProc trong Wincore.cpp

    // In the class declaration

    DECLARE_MESSAGE_MAP()

    // In the class implementation

    BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)

    ON_WM_PAINT()

    END_MESSAGE_MAP()

    phn phi thng bo, khung ng dng gi hm o WindowProc (m lp CMainWindow k tha t CWnd).Hm WindowProc gi OnWndMsg m trong gi ti p hm GetMessageMap ly con tr ch nCMainWindow::messageMap v tm kim CMainWindow::_messageEntries cho nhng thng bo c ID trngvi ID ca cc thng bo ang chx l. Nu kt qu tm thy, lp CMainWindow tng ng (ca nhng achc lu trong dy _messageEntries vi ID ca thng bo) c gi. Ngc li, OnWndMsg tham khoCMainWindow::messageMap cho mt con tr ch ti CFrameWnd::messageMap v lp li qu trnh cho lp cs. Nu lp cskhng c mt iu khin (handler) cho thng bo, khung ng dng the framework pht trinln mc khc v tham kho n lp cscha.

    Cc nh x thng bo CMainWindow th hin dng s nh hnh di y v th hin cc nhnh truy

    xut/tm kim cho mt iu khin trng vi ID ca thng bo cho, bt u vi cc nh x thng bo choCMainWindow.

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    12/272

    Lp trnh Windows vi VC/MFC

    Trang 11

    Hnh. Qu trnh x l thng bo

    1.1.5.4 Windows, Character Sets, v _T Macro

    Windows 98 v Windows NT s dng hai tp k t khc nhau t cc dng k t v chui. Windows 98 v ccphin bn trc s dng tp k t ANSI 8 bit tng t vi tp k t ASCII thn thin vi cc lp trnh vin.Windows NT v Windows 2000 s dng tp k t Unicode 16 bit bao trm c tp k t ANSI nhm phc vcho cc ng dng quc t (c th khng s dng bng mu t ting Anh).

    Cc chng trnh c bin dch vi k t ANSI s hot ng c trn Windows NT and Windows 2000,nhng cc chng trnh dng Unicode s c th thc thi nhanh hn v Windows NT v Windows 2000 khngh trvic chuyn i t ANSI sang Unicode cho tt c k t. Ngc li, ng dng dng Unicode khng thcthi trn Windows 98 ngoi tr khi thc hin vic chuyn i mi chui k t t Unicode sang dng ANSI.

    Nu mt chui nh: "Hello" th trnh bin dch s th hin dng chui k t ANSI.

    Nu khai bo chui trn theo dng L"Hello" th trnh bin dch s th hin dng chui k t Unicode.

    Nhng nu dng macro _T (ca MFC) cho chui trn theo dng _T ("Hello") th kt qu sc th hin dngUnicode nu k hiu tin x l _UNICODE c nh ngha, v mc nh l dng ANSI.

    1.1.5.5 Hm UpdateData

    Hm c dng UpdateData(tham_s) vi:

    tham_s l TRUE: hm s thc hin vic cp nht d liu trong cc iu khin vo cc bin lin kttng ng.

    tham_sl FALSE: hm s thc hin vic cp nht d liu t cc bin lin kt vo trong cc iu khintng ng v hin th trn giao din chng trnh.

    Mt slu : Nn khai bo k t kiu TCHAR thay cho kiu char. Nu k hiu _UNICODE c nh ngha,

    TCHAR xc nh kiu wchar_t (k t Unicode 16 bit). Nu _UNICODE khng c nh ngha thTCHAR trthnh k hiu thng thng.

    Khng nn dng char* hay wchar_t* khai bo con tr kiu chui TCHAR. Nn dng TCHAR* hayLPTSTR (con tr ch ti chui TCHAR) v LPCTSTR (con tr ch ti chui hng TCHAR).

    Khng nn ginh l k t ch c rng 8 bit. chuyn mt di ca bm nhanh dng bytesang dng k t, nn dng sizeof(TCHAR).

    Thay cc vic gi hm chui trong th vic C-trong thi gian thc thi (v d strcpy) vi cc macrostng ng trong file tiu Tchar.h (v d, _tcscpy).

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    13/272

    Lp trnh Windows vi VC/MFC

    Trang 12

    1.1.6 To ng dng vi MS Visual C++T menu File, ngi dng chn lnh New... to mi mt d n (project), mt tp tin (file) hay mt khnggian lm vic (workspace), khi hp thoi xut hin nh hnh sau:

    Trong hp thoi ny, ngi dng c nhiu loi trnh ng dng c th to vi MS Visual C++:

    To ng dng thc thi trong Windows (dng EXE file) vi MFC c h tr t vn vi MFCAppWizard (exe)

    To th vin trong Windows (dng DLL file) vi MFC c h trt vn vi MFC AppWizard (dll) To ng dng thc thi trong Windows (dng EXE file) dng thng thng s dng API vi Win32

    Application

    To ng dng thc thi trong DOS (dng EXE file) dng thng thng vi Win32 ConsoleApplication...

    c bit, khi ngi dng chn cch to ng dng dng ca s vi MFC AppWizard (exe), ngi dng c thto trnh ng dng dng hp thoi (dialog), ng dng n ti liu (Single Document Interface - SDI), ng dnga ti liu (Multi Document Interface - MDI)

    Nu to ng dng dng hp thoi (dialog), ngi dng cn lm nhsau:

    Bc khi u:

    Bc 1:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    14/272

    Lp trnh Windows vi VC/MFC

    Trang 13

    Bc 2:

    Bc 3:

    Bc 4:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    15/272

    Lp trnh Windows vi VC/MFC

    Trang 14

    Bc kt thc:

    Nu to ng dng dngn ti liu hay a ti liu, ngi dng cn lm nhsau:

    Bc khi u:

    Bc 1:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    16/272

    Lp trnh Windows vi VC/MFC

    Trang 15

    Bc 2:

    Bc 3:

    Bc 4:

    Bc 5:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    17/272

    Lp trnh Windows vi VC/MFC

    Trang 16

    Bc 6:

    Bc kt thc:

    1.2 XL V HNH TRONG NG DNG WINDOWS1.2.1 Vn quan tm

    Tm hiu v ng cnh thit b v giao din thit b ho. S h trca MFC v cc lp cng c v (CPen, CBrush)

    1.2.2 Gii thiuHiu hnh Windows cung cp thit b hoo (Graphics Device Interface - GDI) gip ngi dng thchin cc thao tc v ho d dng hn v thit b ny khng ph thuc vo phn cng ho ca h thng.

    Mt chng trnh ng dng (WindowsApp) khng v trc tip ra mn hnh, my in m ch v trn b mtlun l th hin bi ng cnh thit b (Device Context DC). Ng cnh thit b cha cc thng tin v h thng,ng dng v ca s ca WindowsApp cng nh cc i tng hoang c v trong WindowApp .Thc cht ng cnh thit b dng hin th ho l ng cnh o ca ca s.

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    18/272

    Lp trnh Windows vi VC/MFC

    Trang 17

    1.2.3 Truy xut ngcnh thit bMFC cung cp mt s lp ng cnh thit b (k tha t lp CDC) nh:Class M tCPaintDC S dng cho vic v trong vng ng dng ca ca s (ch thao tc vi s kin

    OnPaint)CClientDC S dng cho vic v trong vng ng dng ca ca s (v bt c ni no nhng ch

    thao tc vi s kin OnPaint)CWindowDC S dng cho vic v trong ca s, bao gm c vng khng l vng ng dng ca

    ca sCMetaFileDC S dng cho vic v mt GDI metafile

    ly ng cnh thit b, dng:

    CDC dc(this);

    hay

    CDC* pDC = GetDC();

    gii phng ng cnh thit b, dng:

    ReleaseDC(pDC);

    delete pDC;

    Ng cnh thit b dng bt v (pen) v cc ng thng/hnh dng, v c v (brush) t y cc vngca hnh v trn mn hnh.

    V d:CRect rect;

    GetClientRect(&rect);

    CClientDC dc(this);

    dc.MoveTo(rect.left, rect.top);

    dc.LineTo(rect.right, rect.bottom);

    dc.Ellipse(0, 0, 100, 100);

    hay:CRect rect;

    GetClientRect(&rect);

    CDC* pDC = GetDC();

    pDC->MoveTo(rect.left, rect.top);

    pDC->LineTo(rect.right, rect.bottom);

    pDC->Ellipse(0, 0, 100, 100);

    1.2.3.1 Xc nh cho lng

    Ch lin kt Khong cch tng ng vi mt n v lunl

    Hng ca trc x v y

    MM_TEXT 1 pixel

    MM_LOMETRIC 0.1 mm

    MM_HIMETRIC 0.01 mm

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    19/272

    Lp trnh Windows vi VC/MFC

    Trang 18

    MM_LOENGLISH 0.01 in.

    MM_HIENGLISH 0.001 in.

    MM_TWIPS 1/1440 in. (0.0007 in.)

    MM_ISOTROPIC Ngi dng nh ngha (x v y c t l xcnh)

    Ngi dng nh ngha

    MM_ANISOTROPIC Ngi dng nh ngha (x v y c t l xcnh)

    Ngi dng nh ngha

    1.2.4 Thao tc v vi bt vTrong MFC, lp bt v l CPen, c dng v kiu ng bt k vi mu/ rng xc nh, v d nh sauto bt v mi v chn lm bt v hin thi, dng:

    CDC *pDC = GetDC();

    CPen cp(PS_SOLID, 1, RGB(0,0,0));

    pDC->SelectObject(&cp);

    ...

    to bt v mi ng thi lu li bt v s dng trc :

    CDC *pDC = GetDC();

    CPen pen (PS_SOLID, 10, RGB (255, 0, 0));

    CPen* pOldPen = pDC->SelectObject (&pen);

    ...

    trong hmRGB(r, g, b) to mu chnh da trn 3 mu cbn l R, G, B vi cc tham s r, g v b [0,255] v cc kiu nt nh PS_SOLID, PS_DASH, PS_DOT ... nh sau:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    20/272

    Lp trnh Windows vi VC/MFC

    Trang 19

    trong

    Mt sphng thc vng:Phng thc M tMoveTo Di chuyn bt vn 1 im xc nhLineTo V 1 on thng tim hin hnh ca bt vn 1 im xc nh v di chuyn v tr

    hin hnh n im mi nyPolyline Vng gp khc (tp hp cc an gp khc)PolylineTo Vng gp khc v di chuyn v tr hin hnh n nh cui cng ca ng ny.Arc V cungArcTo V cung v di chuyn v tr hin hnh n nh cui cng ca cung ny.PolyBezier Vng BezierPolyBezierTo Vng Bezier v di chuyn v tr hin hnh n nh cui cng ca ng ny.

    Mt sphng thc vhnh khi:Phng thc M tChord V hnh dng bn cuEllipse V hnh dng ellipsePie V hnh dng bnhPolygon Ni mt tp cc im ca mt a gicRectangle V hnh dng ch nhtRoundRect V hnh dng ch nht trn gc

    Mt sm mu thng dng:Tn mu R G B Tn mu R G B

    Black 0 0 0 Light gray 192 192 192Blue 0 0 192 Bright blue 0 0 255Green 0 192 0 Bright green 0 255 0Cyan 0 192 192 Bright cyan 0 255 255Red 192 0 0 Bright red 255 0 0Magenta 192 0 192 Bright magenta 255 0 255

    Yellow 192 192 0 Bright yellow 255 255 0Dark gray 128 128 128 White 255 255 255

    Ch :

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    21/272

    Lp trnh Windows vi VC/MFC

    Trang 20

    Vic x l v c tht trong s kin OnPaint, OnDraw hay cc s kin lin quan n thao tc chut v bnphm.

    V d:

    Vi on chng trnh sau y:POINT aPoint1[4] = { 120, 100, 120, 200, 250, 150, 500, 40 };

    POINT aPoint2[4] = { 120, 100, 50, 350, 250, 200, 500, 40 };

    dc.PolyBezier (aPoint1, 4);

    dc.PolyBezier (aPoint2, 4);

    Mn hnh kt qu l :

    V d:

    Vi on chng trnh sau y:#include

    #define PI 3.1415926

    void CMainWindow::OnPaint()

    {

    CPaintDC dc (this);

    int nRevenues[4] = { 125, 376, 252, 184 };

    CRect rect;

    GetClientRect(&rect);

    dc.SetViewportOrg(rect.Width() / 2, rect.Height() / 2);

    int nTotal = 0;

    for (int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    22/272

    Lp trnh Windows vi VC/MFC

    Trang 21

    1.2.5 Thao tc t mu vi c vLp c v l CBrush, c dng to c v vi mu/mu v xc nh:

    CDC *pDC=GetDC();

    CBrush brush (HS_DIAGCROSS, RGB (255, 255, 255));

    pDC->SelectObject(&brush);

    ...

    to c v mi ng thi lu li c v s dng trc :

    CDC *pDC=GetDC();

    CBrush brush (HS_DIAGCROSS, RGB (255, 255, 255));

    CBrush* pOldBrush = pDC->SelectObject(&brush);

    ...

    trong cc mu v l HS_SOLID, HS_CROSS, HS_DIAGCROSS nh sau:

    V d:CBrush brush (HS_DIAGCROSS, RGB (0, 0, 0));

    pDC->SelectObject (&brush);

    pDC->SetBkMode (TRANSPARENT);

    pDC->Rectangle (0, 0, 100, 100);

    hay:CBrush brush (HS_DIAGCROSS, RGB (255, 255, 255));

    pDC->SelectObject (&brush);

    pDC->SetBkColor (RGB (192, 192, 192));

    pDC->Rectangle (0, 0, 100, 100);

    1.2.6 Hin th vn bn trong mi trng hoNg cnh thit b cung cp mt s hm thc hin vic h trhin th vn bn trong mi trng ho nh sau:

    Hm M tDrawText V mt vn bn trong mt khung ch nht nh dng trcTextOut Xut mt hnh vn bn ti v tr hin hnh hay ti im xc nhTabbedTextOut Xut mt hnh vn bn cha ng cc k hiu tabExtTextOut Xut mt hng vn bn trong mt khung ch nht c mu ty chn hay cc k

    t xen gia khc nhau

    GetTextExtent Ly rng chui vi font s dng hin hnhGetTabbedTextExtent Ly rng chui (c cha ng k hiu tab) vi font s dng hin hnhGetTextMetrics Ly font metrics (chiu cao k t, rng trung bnh) ca font hin hnh

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    23/272

    Lp trnh Windows vi VC/MFC

    Trang 22

    SetTextAlign Canh l ca vn bn cho hm TextOut v cc hm xut ni dung vn bn khcSetTextJustification Canh u vn bnSetTextColor t mu cho vn bn xut raSetBkColor t mu nn

    V d:CString string = _T ("Now is the time");

    CSize size = dc.GetTextExtent (string);

    dc.SetTextJustification (nWidth - size.cx, 3);

    dc.TextOut (0, y, string);

    hay:dc.DrawText (_T ("Hello, MFC"), -1, &rect,

    DT_SINGLELINE DT_CENTER DT_VCENTER);

    1.2.7 GDI Fonts v lp CFontNgoi vic s dng font ch mc nh, ngi dng cn c th to font ch trong ch ho ty chn.

    V d:

    Vi on chng trnh sau y:void CMainWindow::OnPaint ()

    {

    CRect rect;

    GetClientRect (&rect);

    CFont font;

    font.CreatePointFont (720, _T ("Arial"));

    CPaintDC dc (this);

    dc.SelectObject (&font);

    dc.SetBkMode (TRANSPARENT);

    CString string = _T ("Hello, MFC");

    rect.OffsetRect (16, 16);

    dc.SetTextColor (RGB (192, 192, 192));

    dc.DrawText (string, &rect, DT_SINGLELINE

    DT_CENTER DT_VCENTER);

    rect.OffsetRect (-16, -16);

    dc.SetTextColor (RGB (0, 0, 0));

    dc.DrawText (string, &rect, DT_SINGLELINE

    DT_CENTER DT_VCENTER);

    }

    Mn hnh kt qu nh sau:

    V d:

    Vi on chng trnh sau y:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    24/272

    Lp trnh Windows vi VC/MFC

    Trang 23

    void CMainWindow::OnPaint()

    {

    CRect rect;

    GetClientRect(&rect);

    CPaintDC dc(this);

    dc.SetViewportOrg(rect.Width () / 2, rect.Height () / 2);

    dc.SetBkMode(TRANSPARENT);

    for (int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    25/272

    Lp trnh Windows vi VC/MFC

    Trang 24

    int m_nRibbonWidth; // Ribbon width in pixels

    int m_nViewWidth; // Workspace width in pixels

    int m_nViewHeight; // Workspace height in pixels

    int m_nHScrollPos; // Horizontal scroll position

    int m_nVScrollPos; // Vertical scroll position

    int m_nHPageSize; // Horizontal page size

    int m_nVPageSize; // Vertical page size

    public:

    CMainWindow();

    protected:

    afx_msg void OnPaint();

    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);

    afx_msg void OnSize(UINT nType, int cx, int cy);

    afx_msg void OnHScroll(UINT nCode, UINT nPos,

    CScrollBar* pScrollBar);

    afx_msg void OnVScroll(UINT nCode, UINT nPos,

    CScrollBar* pScrollBar);

    DECLARE_MESSAGE_MAP()

    };

    Accel.cpp#include

    #include "Accel.h"

    CMyApp myApp;

    /////////////////////////////////////////////////////////////////////////

    // CMyApp member functions

    BOOL CMyApp::InitInstance(){

    m_pMainWnd = new CMainWindow;

    m_pMainWnd->ShowWindow (m_nCmdShow);

    m_pMainWnd->UpdateWindow();

    return TRUE;

    }

    /////////////////////////////////////////////////////////////////////////

    // CMainWindow message map and member functions

    BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)

    ON_WM_CREATE()

    ON_WM_SIZE()

    ON_WM_PAINT()

    ON_WM_HSCROLL()

    ON_WM_VSCROLL()

    END_MESSAGE_MAP()

    CMainWindow::CMainWindow()

    {

    Create(NULL, _T ("Accel"),

    WS_OVERLAPPEDWINDOW WS_HSCROLL WS_VSCROLL);

    }

    int CMainWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)

    {

    if (CFrameWnd::OnCreate(lpCreateStruct) == -1)return -1;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    26/272

    Lp trnh Windows vi VC/MFC

    Trang 25

    CClientDC dc(this);

    m_nCellWidth = dc.GetDeviceCaps(LOGPIXELSX);

    m_nCellHeight = dc.GetDeviceCaps(LOGPIXELSY) / 4;

    m_nRibbonWidth = m_nCellWidth / 2;

    m_nViewWidth = (26 * m_nCellWidth) + m_nRibbonWidth;

    m_nViewHeight = m_nCellHeight * 100;

    return 0;

    }

    void CMainWindow::OnSize(UINT nType, int cx, int cy)

    {

    CFrameWnd::OnSize(nType, cx, cy);

    //

    // Set the horizontal scrolling parameters.

    //

    int nHScrollMax = 0;

    m_nHScrollPos = m_nHPageSize = 0;

    if (cx < m_nViewWidth) {nHScrollMax = m_nViewWidth - 1;

    m_nHPageSize = cx;

    m_nHScrollPos = min(m_nHScrollPos, m_nViewWidth -

    m_nHPageSize - 1);

    }

    SCROLLINFO si;

    si.fMask = SIF_PAGE SIF_RANGE SIF_POS;

    si.nMin = 0;

    si.nMax = nHScrollMax;

    si.nPos = m_nHScrollPos;

    si.nPage = m_nHPageSize;

    SetScrollInfo(SB_HORZ, &si, TRUE);

    //

    // Set the vertical scrolling parameters.

    //

    int nVScrollMax = 0;

    m_nVScrollPos = m_nVPageSize = 0;

    if (cy < m_nViewHeight) {

    nVScrollMax = m_nViewHeight - 1;

    m_nVPageSize = cy;

    m_nVScrollPos = min(m_nVScrollPos, m_nViewHeight -

    m_nVPageSize - 1);

    }

    si.fMask = SIF_PAGE SIF_RANGE SIF_POS;

    si.nMin = 0;

    si.nMax = nVScrollMax;

    si.nPos = m_nVScrollPos;

    si.nPage = m_nVPageSize;

    SetScrollInfo(SB_VERT, &si, TRUE);

    }void CMainWindow::OnPaint ()

    {

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    27/272

    Lp trnh Windows vi VC/MFC

    Trang 26

    CPaintDC dc (this);

    //

    // Set the window origin to reflect the current scroll positions.

    //

    dc.SetWindowOrg(m_nHScrollPos, m_nVScrollPos);

    //

    // Draw the grid lines.

    //

    CPen pen(PS_SOLID, 0, RGB (192, 192, 192));

    CPen* pOldPen = dc.SelectObject (&pen);

    for (int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    28/272

    Lp trnh Windows vi VC/MFC

    Trang 27

    rect.top++;

    dc.Draw3dRect(rect, RGB (255, 255, 255),

    RGB (128, 128, 128));

    }

    //

    // Add letters and button outlines to the column headers.

    //

    for (j=0; j

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    29/272

    Lp trnh Windows vi VC/MFC

    Trang 28

    nDelta = nMaxPos - m_nHScrollPos;

    if (nDelta != 0) {

    m_nHScrollPos += nDelta;

    SetScrollPos (SB_HORZ, m_nHScrollPos, TRUE);

    ScrollWindow (-nDelta, 0);

    }

    }

    void CMainWindow::OnVScroll(UINT nCode, UINT nPos, CScrollBar* pScrollBar)

    {

    int nDelta;

    switch (nCode) {

    case SB_LINEUP:

    nDelta = -LINESIZE;

    break;

    case SB_PAGEUP:

    nDelta = -m_nVPageSize;break;

    case SB_THUMBTRACK:

    nDelta = (int) nPos - m_nVScrollPos;

    break;

    case SB_PAGEDOWN:

    nDelta = m_nVPageSize;

    break;

    case SB_LINEDOWN:

    nDelta = LINESIZE;

    break;

    default: // Ignore other scroll bar messages

    return;}

    int nScrollPos = m_nVScrollPos + nDelta;

    int nMaxPos = m_nViewHeight - m_nVPageSize;

    if (nScrollPos < 0)

    nDelta = -m_nVScrollPos;

    else if (nScrollPos > nMaxPos)

    nDelta = nMaxPos - m_nVScrollPos;

    if (nDelta != 0) {

    m_nVScrollPos += nDelta;

    SetScrollPos(SB_VERT, m_nVScrollPos, TRUE);

    ScrollWindow(0, -nDelta);

    }

    }

    Mn hnh kt qu nh sau

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    30/272

    Lp trnh Windows vi VC/MFC

    Trang 29

    1.2.8.2 Chng trnh 2

    Ruler.hclass CMyApp : public CWinApp

    {

    public:

    virtual BOOL InitInstance();

    };

    class CMainWindow : public CFrameWnd

    {

    public:

    CMainWindow();

    protected:

    afx_msg void OnPaint();

    DECLARE_MESSAGE_MAP()

    };

    Ruler.cpp#include #include "Ruler.h"

    CMyApp myApp;

    /////////////////////////////////////////////////////////////////////////

    // CMyApp member functions

    BOOL CMyApp::InitInstance()

    {

    m_pMainWnd = new CMainWindow;

    m_pMainWnd->ShowWindow(m_nCmdShow);

    m_pMainWnd->UpdateWindow();

    return TRUE;}

    ////////////////////////////////////////////////////////////////////////

    // CMainWindow message map and member functions

    BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)

    ON_WM_PAINT()

    END_MESSAGE_MAP()

    CMainWindow::CMainWindow()

    {

    Create(NULL, _T ("Ruler"));

    }

    void CMainWindow::OnPaint()

    {

    CPaintDC dc(this);

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    31/272

    Lp trnh Windows vi VC/MFC

    Trang 30

    //

    // Initialize the device context.

    //

    dc.SetMapMode(MM_LOENGLISH);

    dc.SetTextAlign(TA_CENTER TA_BOTTOM);

    dc.SetBkMode(TRANSPARENT);

    //

    // Draw the body of the ruler.

    //

    CBrush brush (RGB (255, 255, 0));

    CBrush* pOldBrush = dc.SelectObject(&brush);

    dc.Rectangle(100, -100, 1300, -200);

    dc.SelectObject(pOldBrush);

    //

    // Draw the tick marks and labels.

    //

    for (int i=125; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    32/272

    Lp trnh Windows vi VC/MFC

    Trang 31

    Nhn bit v x l cc thao tc lin quan n cc s kin ca chut, bn phm.1.3.2 Cc skin ca chutMFC h trthao tc vi chut bng vic lin h cc thng ip v cc s kin nh:Thng i p Macro kt hp S kin Hm iu khinWM_LBUTTONDOWN ON_WM_LBUTTONDOWN Nt tri

    chut cnhn xung.

    OnLButtonDown

    WM_LBUTTONUP ON_WM_LBUTTONUP Nt trichut cnh ra.

    OnLButtonUp

    WM_LBUTTONDBLCLK ON_WM_LBUTTONDBLCLK Nt trichut cnhnkp(double)

    OnLButtonDblClk

    WM_MBUTTONDOWN ON_WM_MBUTTONDOWN Nt giachut cnhn xung.

    OnMButtonDown

    WM_MBUTTONUP ON_WM_MBUTTONUP Nt gia

    chut cnh ra.

    OnMButtonUp

    WM_MBUTTONDBLCLK ON_WM_MBUTTONDBLCLK Nt giachut cnhnkp(double)

    OnMButtonDblClk

    WM_RBUTTONDOWN ON_WM_RBUTTONDOWN Nt phichut cnhn xung.

    OnRButtonDown

    WM_RBUTTONUP ON_WM_RBUTTONUP Nt phichut cnh ra.

    OnRButtonUp

    WM_RBUTTONDBLCLK ON_WM_RBUTTONDBLCLK Nt phi

    chut cnhnkp(double)

    OnRButtonDblClk

    WM_MOUSEMOVE ON_WM_MOUSEMOVE Con trchut dichuyn trongvng hin thca ca s.

    OnMouseMove

    Cc hm iu khin c dng:

    afx_msg void OnMsgName(UINT nFlags, CPoint point)

    Trong nFlags(dng nhn bit nt bm chut v cc phm Ctrl/Shift bi php ton &) c gi tr:

    Mt n (Mask) Nhn bit khiMK_LBUTTON Nt tri chut c nhnMK_MBUTTON Nt gia chut c nhnMK_RBUTTON Nt phi chut c nhnMK_CONTROL Phm Ctrl c nhnMK_SHIFT Phm Shift c nhn

    V d:

    nhn bit phm Ctrl c c nhn km vi chut dng:

    if ((nFlags & MK_CONTROL) == MK_CONTROL) {}

    V d:

    Kt hp x l chut v v hnh:void CVd3aView::OnMouseMove(UINT nFlags, CPoint point)

    {

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    33/272

    Lp trnh Windows vi VC/MFC

    Trang 32

    // TODO: Add your message handler code here and/or call default

    CDC *pDC = GetDC();

    CString szTextOut;

    szTextOut.Format("Current point(%d, %d)", point.x, point.y);

    pDC->TextOut(0, 0, szTextOut);

    if((nFlags & MK_CONTROL)==MK_CONTROL)

    MyDrawFunction(point);

    CView::OnMouseMove(nFlags, point);

    }

    void CVd3aView::OnLButtonDown(UINT nFlags, CPoint point)

    {

    // TODO: Add your message handler code here and/or call default

    MyDrawFunction(point);

    CView::OnLButtonDown(nFlags, point);

    }

    void CVd3aView::MyDrawFunction(CPoint point)

    {

    CDC *pDC = GetDC();if((m_PrevPoint.x == -1)&&(m_PrevPoint.y == -1))

    pDC->MoveTo(point);

    else

    {

    pDC->MoveTo(m_PrevPoint);

    pDC->LineTo(point);

    }

    m_PrevPoint = point;

    }

    1.3.3 Cc skin ca bn phmMFC h trthao tc vi bn phm bng vic lin h cc thng ip v cc s kin nh sau:Thng i p Macro kt hp S kin Hm iu khinWM_KEYDOWN ON_WM_KEYDOWN Phm c

    nhn xung.OnKeyDown

    WM_KEYUP ON_WM_KEYUP Phm cnh ra.

    OnKeyUp

    WM_SYSKEYDOWN ON_WM_SYSKEYDOWN Nt chcnng cnhn xung.

    OnSysKeyDown

    WM_SYSKEYUP ON_WM_SYSKEYUP Phm chcnng cnh ra.

    OnSysKeyUp

    Cc hm iu khin c dng:

    afx_msg void OnMsgName(UINT nChar, UINT nRepCnt, UINT nFlags)

    Trong , ngoi cc k t thng thng, nChar(l Virtual Key Code) cn c gi tr nh:M phm o Phm tng ngVK_F1_VK_F12 Function keys F1_F12VK_NUMPAD0_VK_NUMPAD9 Numeric keypad 0_9 with Num Lock onVK_CANCEL Ctrl-BreakVK_RETURN EnterVK_BACK BackspaceVK_TAB TabVK_CLEAR Numeric keypad 5 with Num Lock offVK_SHIFT Shift

    VK_CONTROL CtrlVK_MENU Alt

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    34/272

    Lp trnh Windows vi VC/MFC

    Trang 33

    VK_PAUSE PauseVK_ESCAPE EscVK_SPACE SpacebarVK_PRIOR Page Up and PgUpVK_NEXT Page Down and PgDnVK_END End

    VK_HOME HomeVK_LEFT Left arrowVK_UP Up arrowVK_RIGHT Right arrowVK_DOWN Down arrowVK_SNAPSHOT Print ScreenVK_INSERT Insert and InsVK_DELETE Delete and DelVK_MULTIPLY Numeric keypad *VK_ADD Numeric keypad +VK_SUBTRACT Numeric keypad -VK_DECIMAL Numeric keypad .

    VK_DIVIDE Numeric keypad /VK_CAPITAL Caps LockVK_NUMLOCK Num LockVK_SCROLL Scroll LockVK_LWIN

    Left Windows keyVK_RWIN

    Right Windows keyVK_APPS Menu key

    V nFlags c dng nhn bit phm Alt c c nhn km hay khng.

    Ngoi ra, c th dng hm:

    void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)

    V d:void CVd3bView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)

    {

    // TODO: Add your message handler code here and/or call default

    if(((nChar >= _T('A')) &&(nChar = _T('a')) &&(nChar = _T('0')) &&(nChar

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    35/272

    Lp trnh Windows vi VC/MFC

    Trang 34

    // Process the Backspace key

    m_szInput = m_szInput.Left(m_szInput.GetLength()-1);

    MyDrawFunction(m_szInput);

    }

    CView::OnChar(nChar, nRepCnt, nFlags);

    }

    void CVd3bView::MyDrawFunction(CString szText)

    {

    CDC *pDC = GetDC();

    CBrush *pCurrentBrush = pDC->GetCurrentBrush();

    CBrush *pNewBrush = new CBrush();

    pNewBrush->CreateSolidBrush(RGB(255, 255, 255));

    CRect rect;

    GetClientRect(&rect);

    pDC->SelectObject(pNewBrush);

    pDC->FillRect(rect, pNewBrush);

    pDC->TextOut(0, 20*m_nLine, szText);

    }

    1.4 CC LP MFC COLLECTION: ARRAY, LIST, MAP*, TYPEPOINTER MAP*

    1.4.1 Vn quan tm Tm hiu cch s dng cc MFC collection classes

    1.4.2 Array collectionMFC cung cp mt s lp h trvic s dng array thun tin hn nh:Tn l p Kiu d liuCArray Lp mng tng qut nhtCByteArray Lp mng kiu s nguyn 8-bit -bytes(BYTEs)

    CWordArray Lp mng kiu s nguyn 16-bit -words(WORDs)CDWordArray Lp mng kiu s nguyn 32-bit -double words(DWORDs)CUIntArray Lp mng kiu s nguyn khng m -unsigned integers(UINTs)CStringArray Lp mng kiu chui CCtringsCPtrArray Lp mng kiu con tr khng kiu -void pointersCObArray Lp mng kiu con tri tng -CObject pointers

    Ch :Ngi dng phi khai bo #include Afxtempl.h khi s dng cc lp ny.

    V d 1:// Add 10 items.

    CUIntArray array;

    array.SetSize(10);

    for(int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    36/272

    Lp trnh Windows vi VC/MFC

    Trang 35

    // Populate the array, growing it as needed.

    for(int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    37/272

    Lp trnh Windows vi VC/MFC

    Trang 36

    szSchools[4] = _T("Kentucky"); szSchools[5] = _T("Mississippi");

    szSchools[6] = _T("Mississippi State"); szSchools[7] = _T("South Carolina");

    szSchools[8] = _T("Tennessee"); szSchools[0] = _T("Vanderbilt") ;

    CStringList list;

    for(int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    38/272

    Lp trnh Windows vi VC/MFC

    Trang 37

    CTypedPtrList Lp qun l danh sch lin kt con trCTypedPtrMap Lp qun l tin con tr

    Ch :Ngi dng phi khai bo #include Afxtempl.h khi s dng cc lp ny.

    V d:

    CTypedPtrList list;// Populate the list.

    for(int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    39/272

    Lp trnh Windows vi VC/MFC

    Trang 38

    V d 1:BYTE buffer[0x1000];

    try

    {

    CFile file(_T("C:\\MyDocument.txt"), CFile::modeReadWrite);

    DWORD dwBytesRemaining = file.GetLength();

    while(dwBytesRemaining)

    {

    DWORD dwPosition = file.GetPosition();

    UINT nBytesRead = file.Read(buffer, sizeof(buffer));

    ::CharLowerBuff((LPTSTR)buffer, nBytesRead);// chuyn sang ch thng

    file.Seek(dwPosition, CFile::begin);

    file.Write(buffer, nBytesRead);

    dwBytesRemaining -= nBytesRead;

    }

    }

    catch(CFileException* e)

    {

    e->ReportError();

    e->Delete();

    }

    file.Close();

    V d 2:

    Lit k tt c cc file trong th mc hin hnh:WIN32_FIND_DATA fd;

    HANDLE hFind = ::FindFirstFile (_T ("*.*"), &fd);

    if (hFind != INVALID_HANDLE_VALUE) {

    do {

    if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))

    TRACE (_T ("%s\n"), fd.cFileName);

    } while (::FindNextFile (hFind, &fd));

    ::FindClose (hFind);

    }

    v lit k tt c th mc con trong th mc hin hnh:WIN32_FIND_DATA fd;

    HANDLE hFind = ::FindFirstFile (_T ("*.*"), &fd);

    if (hFind != INVALID_HANDLE_VALUE) {

    do {

    if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)

    TRACE (_T ("%s\n"), fd.cFileName);

    } while (::FindNextFile (hFind, &fd));

    ::FindClose (hFind);

    }

    1.5.3 Chui ho v CArchiveD lp CFile kh hu ch trong qu trnh xy dng WinApp, nhng MFC cung cp lp CArchive nhm ngin ho vic truy xut vi vic dng ton t >> v

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    40/272

    Lp trnh Windows vi VC/MFC

    Trang 39

    S tng tc v vai tr ca lp CArchive c th hin nh hnh sau y:

    V d 3:void CVd3bDoc::Serialize(CArchive& ar)

    {

    if(ar.IsStoring())

    {

    // TODO: add storing code here

    ar > m_MyVar;

    }

    }

    Hm Serialize c thc t trong bt c class no nhm x l thao tc lu/c cho i tng . x lcho trng hp ny cho class (gi s c tn CMyClass), cn thc thi theo trnh t sau:

    Cho lp CMyClass ny ktha lp CObject. Thm macro DECLARE_SERIAL trong phn khai bo ca l p CMyClass theo dng sau:

    DECLARE_SERIAL(tn class tha k ny). V d: DECLARE_SERIAL(CMyClass)

    Thm hm Serialize vo class CMyClass v khai bo li hm Serialize ny x l chui ho d liuca lp CMyClass

    Thm hm sinh (constructor) cho lp CMyClass nu n cha c. Thm macro IMPLEMENT_SERIAL trong phn thn ca l p CMyClass theo dng sau:

    IMPLEMENT_SERIAL(tn class tha k, tn class cha, s hiu phin bn). V d:IMPLEMENT_SERIAL(CMyClass, CObject, 1)

    V d 4:

    Bc 0:class CLine

    {

    protected:

    CPoint m_ptFrom;CPoint m_ptTo;

    public:

    CLine(CPoint from, CPoint to) { m_ptFrom = from; m_ptTo = to; }

    };

    Bc 1-2:class CLine : public CObject

    {

    DECLARE_SERIAL(CLine)

    protected:

    CPoint m_ptFrom;

    CPoint m_ptTo;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    41/272

    Lp trnh Windows vi VC/MFC

    Trang 40

    public:

    CLine() {} // Required!

    CLine(CPoint from, CPoint to) { m_ptFrom = from; m_ptTo = to; }

    void Serialize(CArchive& ar);

    };

    Bc 3:void CLine::Serialize(CArchive& ar)

    {

    CObject::Serialize(ar);

    if(ar.IsStoring())

    ar m_ptFrom >> m_ptTo;

    }

    Bc 5a:_AFX_INLINE CArchive& AFXAPI operator(CArchive& ar, CObject*& pOb)

    { pOb = ar.ReadObject(NULL); return ar; }

    _AFX_INLINE CArchive& AFXAPI operator>>(CArchive& ar,

    const CObject*& pOb)

    { pOb = ar.ReadObject(NULL); return ar; }

    V c thsdnglu trlp CLine nhsau:

    Lu xung:// Create two CLines and initialize an array of pointers.

    CLine line1(CPoint(0, 0), CPoint(50, 50));

    CLine line2(CPoint(50, 50), CPoint(100, 0));CLine* pLines[2] = { &line1, &line2 };

    int nCount = 2;

    // Serialize the CLines and the CLine count.

    for(int i=0; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    42/272

    Lp trnh Windows vi VC/MFC

    Trang 41

    ar >> pLines[i];

    // c ln s phn t thc c

    ar >> nCount;

    V cch thc thi khc:// Serialize.

    CLine line(CPoint(0, 0), CPoint(100, 50));

    line.Serialize(ar);

    // Deserialize.

    CLine line;

    line.Serialize(ar);

    V d 5:

    Ghi vo file thng qua b x l chui ho:try

    {

    CFile myFile("C:\\myfile.dat", CFile::modeCreate | CFile::modeWrite);

    // Create a storing archive.

    CArchive arStore(&myFile, CArchive::store);////////////////////////////////////

    CString szSize;

    szSize.Format("%d", (m_arrDSSV.GetSize()+1));

    arStore.Write(szSize, 10);

    ////////////////////////////////////

    int nCount;

    ////////////////////////////////////

    for (nCount=0; nCount < m_arrDSSV.GetSize(); nCount++)

    {

    // Write the object to the archive

    arStore.WriteObject( m_arrDSSV[nCount] );

    }

    // Close the storing archive

    arStore.Close();

    return TRUE;

    }

    catch(CException *e)

    {

    return FALSE;

    }

    c t file ln thng qua b x l phi chui hotry

    {////////////////////////////////////////////////

    XoaNoiDung();

    ////////////////////////////////////////////////

    CFile myFile("C:\\myfile.dat", CFile::modeRead);

    // Create a loading archive.

    myFile.SeekToBegin();

    CArchive arLoad(&myFile, CArchive::load);

    CSinhVien* pSV;

    /////////////////////////////////

    char szSize[10];

    arLoad.Read(szSize, 10);

    int nSize = (int) atoi(szSize);

    int nCount;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    43/272

    Lp trnh Windows vi VC/MFC

    Trang 42

    ////////////////////////////////

    for (nCount=0; nCount < nSize; nCount++)

    {

    // Verify the object is in the archive.

    pSV = (CSinhVien*)arLoad.ReadObject(RUNTIME_CLASS(CSinhVien));

    if (pSV)

    m_arrDSSV.Add(pSV);

    }

    ///////////////////////////////

    arLoad.Close();

    return TRUE;

    }

    catch(CException *e)

    {

    return FALSE;

    }

    1.6 CC LP MFC CA CC IU KHIN WINDOWS.1.6.1 Vn quan tm

    Tnh cht/hot ng v x l/thao tc vi cc iu khin Windows (Windows control)1.6.2 Cc loi iu khinMFC cung cp cc lp i din cho cc Windows control nh:Kiu iu khin WNDCLASS MFC ClassButtons "BUTTON" CButtonList boxes "LISTBOX" CListBoxEdit controls "EDIT" CEditCombo boxes "COMBOBOX" CComboBoxScroll bars "SCROLLBAR" CScrollBarStatic controls "STATIC" CStatic

    ng thi vi vic to cc iu khin ny thng qua thanh cng c trong ch Resource View, ngi dngcng c th to cc iu khin ny bng hm thnh vin Create.

    V d 1:CButton myButton1, myButton2, myButton3, myButton4;

    // Create a push button.

    myButton1.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,

    CRect(10,10,100,30), pParentWnd, 1);

    // Create a radio button.

    myButton2.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_RADIOBUTTON,

    CRect(10,40,100,70), pParentWnd, 2);

    // Create an auto 3-state button.

    myButton3.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_AUTO3STATE,

    CRect(10,70,100,100), pParentWnd, 3);

    // Create an auto check box.

    myButton4.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_AUTOCHECKBOX,

    CRect(10,100,100,130), pParentWnd, 4);

    Hay:extern CWnd* pParentWnd;

    // The pointer to my list box.

    extern CListBox* pmyListBox;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    44/272

    Lp trnh Windows vi VC/MFC

    Trang 43

    pmyListBox->Create(WS_CHILD|WS_VISIBLE|LBS_STANDARD|WS_HSCROLL,

    CRect(10,10,200,200), pParentWnd, 1);

    V:

    CEdit* pEdit = new CEdit;

    pEdit->Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER,

    CRect(10, 10, 100, 100), this, 1);

    Ch : Nn s dng cc bin con tri din cho cc iu hin to cc iu khin trong thi gian thc

    thi.

    C th x l vic to cc iu khin ny trong thi gian thc thi bng cch t chng vo trong cchm thnh vin ::OnInitialUpdate() v hm khi to ::PreCreateWindow()

    1.6.3 Loi CButtonKiu M tBS_PUSHBUTTON To mt iu khin nt nhn

    BS_DEFPUSHBUTTON To mt iu khin nt nhn v s dng trong hp thoi vitrng thi mc nh khi nhn phm Enter

    BS_CHECKBOXTo mt iu khin check box

    BS_AUTOCHECKBOX To mt iu khin check box tng chn v b chn khic bm vo

    BS_3STATE To mt iu khin check box 3 trng thi.BS_AUTO3STATE To mt iu khin check box 3 trng thi tng chn v

    b chn khi c bm voBS_RADIOBUTTON To mt iu khin radio buttonBS_AUTORADIOBUTTON To mt iu khin radion button tng chn v b chn

    khi c bm voBS_GROUPBOX To mt nhm cc iu khin

    V cc kiu ring phn:Kiu M t

    BS_LEFTTEXT t vn bn ca cc iu khin radio button hay check box nm bn tri caiu khinBS_RIGHTBUTTON Tng t nh BS_LEFTTEXT nhng v pha phiBS_LEFT Canh l tri vn bn trong iu khinBS_CENTER Canh l gia vn bn trong iu khinBS_RIGHT Canh l phi vn bn trong iu khinBS_TOP Canh l pha nh trn vn bn trong iu khinBS_VCENTER Canh l gia vn bn trong iu khin theo chiu dcBS_BOTTOM Canh l pha di vn bn trong iu khinBS_MULTILINE Xc nh ch nhiu dng

    1.7 DIALOG BOX, COMMON DIALOG V PROPERTY SHEET.1.7.1 Vn quan tm

    Tnh cht/hot ng v x l/thao tc vi cc Dialog Cch to PropertySheet/PropertyPage

    1.7.2 Hp thoi (dialog)C th to cc hp thoi ty bng cch kt hp gia vic to Dialog form (trong ResourceView) v 1 class linkt (to bi ClassWizard)

    Vic to ny theo trnh t sau y:

    Bc 1:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    45/272

    Lp trnh Windows vi VC/MFC

    Trang 44

    Bc 2:

    Bc 3: C th cp nht ID ca hp thoi mi thm ny, v chn Create New Class to mt lp linkt vi hp thoi va to.

    nhp thng tin cn thit:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    46/272

    Lp trnh Windows vi VC/MFC

    Trang 45

    Bc 4:

    Ti file cn s dng hp thoi ny, thm 1 hng#include tn_file.h

    Bc 5:To bin i din cho hp thoi ny v gi hm DoModal() ca hp thoi kch hothp thoi hin th ln.

    1.7.3 Cc hp thoi thng dng (Common Dialog Classes)Cc hp thoi thng dng nh FontDialog, ColorDialog, FileDialog c MFC cung cp cc class i dingip vic s dng d dng hn.

    MFC h trcc lp i din cho cc hp thoi ny nh sau:Tn l p Kiu hp thoiCFileDialog Hp thoi mv lu tr (Open and Save As dialog boxes)CPrintDialog Hp thoi in n v ci t in n (Print and Print Setup dialog boxes)CPageSetupDialog Hp thoi ci t trang (Page Setup dialog boxes)CFindReplaceDialog Hp thoi tm kim v thay th (Find and Replace dialog boxes)CColorDialog Hp thoi chn mu (Color dialog boxes)CFontDialog Hp thoi chn phng ch (Font dialog boxes)

    Cc hp thoi thng dng c giao din nh sau:

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    47/272

    Lp trnh Windows vi VC/MFC

    Trang 46

    V d 1:TCHAR szFilters[] = _T("Text files(*.txt)*.txtAll files *.*)*.*");

    CFileDialog

    dlg(TRUE,_T("txt"),_T("*.txt"),OFN_FILEMUSTEXISTOFN_HIDEREADONLY,zFilters);

    if(dlg.DoModal() == IDOK) {

    filename = dlg.GetPathName();

    // Open the file and read it.

    }

    V d 2:void CChildView::OnFileSaveAs()

    {

    CFileDialog

    dlg(FALSE,_T("phn"),m_strPathName,

    OFN_OVERWRITEPROMPTOFN_PATHMUSTEXISTOFN_HIDEREADONLY,

    m_szFilters);

    if(dlg.DoModal() == IDOK)

    {

    if(SaveFile(dlg.GetPathName()))

    m_strPathName = dlg.GetPathName();

    }

    V d 3:CColorDialog dlg(RGB(255, 0, 0), CC_FULLOPEN);

    if(dlg.DoModal() == IDOK)

    {

    ///////////////////////////////////

    AfxMessageBox("Chon mau", 0, 0);m_oColor = dlg.GetColor();

    }

    1.7.4 Property Sheet/Property PageProperty Sheet cn gi l tab, Property Page cn gi l page.

    PropertySheet c s dng nhm cung cp nhiu s chn la cho ngi dng bng cch tch hp nhiu chnla mi chn la l mt hp thoi (property page).

    to Property Sheet/Property Page, cn lm theo cc bc sau:

    Xc nh s page (property page) cn c trong mt property sheet To (chn) cc class d nh dng lm cc page hin th trong property page k tha t class

    CPropertyPage.

    Thm cc control v cc bin lin kt vo trong tng page v class lin kt bc trn. To class mi cho property sheet bi vic k tha t CPropertySheet class

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    48/272

    Lp trnh Windows vi VC/MFC

    Trang 47

    Kch hot hmDoModal()V d 4:

    To:class CFirstPage :public CPropertyPage

    {

    public:

    CFirstPage() : CPropertyPage(IDD_FIRSTPAGE) {};

    // Declare CFirstPage's data members here.

    protected:

    virtual void DoDataExchange(CDataExchange*);

    };

    class CSecondPage :public CPropertyPage

    {

    public:

    CSecondPage() : CPropertyPage(IDD_SECONDPAGE) {};

    // Declare CSecondPage's data members here.

    protected:

    virtual void DoDataExchange(CDataExchange*);

    };

    class CMyPropertySheet :public CPropertySheet

    {

    public:

    CFirstPage m_firstPage; // First page

    CSecondPage m_secondPage; // Second page

    // Constructor adds the pages automatically.

    CMyPropertySheet(LPCTSTR pszCaption,

    CWnd* pParentWnd = NULL) :

    CPropertySheet(pszCaption, pParentWnd, 0)

    {

    AddPage(&m_firstPage);

    AddPage(&m_secondPage);

    }

    };

    S dng:CMyPropertySheet ps(_T("Properties"));

    ps.DoModal();

    Nu mun nhng property sheet vo ca s chng trnh hin hnh th cp nhp bi cc lnhCMyPropertySheet *ps = new CMyPropertySheet(_T("Properties"));

    ps->Create(this, WS_CHILD);

    ps->ShowWindow(SW_SHOW);

    ps->MoveWindow(0,0,800,600);

    V d tng hp:

    MainFrm.h// MainFrm.h : interface of the CMainFrame class

    //

    ///////////////////////////////////////////////////////////////////////////

    #if !defined(AFX_MAINFRM_H__9CE2B4A8_9067_11D2_8E53_006008A82731__INCLUDED_)

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    49/272

    Lp trnh Windows vi VC/MFC

    Trang 48

    #define AFX_MAINFRM_H__9CE2B4A8_9067_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    #include "ChildView.h"

    class CMainFrame : public CFrameWnd

    {

    public:

    CMainFrame();

    protected:

    DECLARE_DYNAMIC(CMainFrame)

    // Attributes

    public:

    // Operations

    public:

    // Overrides// ClassWizard generated virtual function overrides

    //{{AFX_VIRTUAL(CMainFrame)

    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

    virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra,

    AFX_CMDHANDLERINFO* pHandlerInfo);

    //}}AFX_VIRTUAL

    // Implementation

    public:

    virtual ~CMainFrame();

    #ifdef _DEBUG

    virtual void AssertValid() const;

    virtual void Dump(CDumpContext& dc) const;#endif

    CChildView m_wndView;

    // Generated message map functions

    protected:

    //{{AFX_MSG(CMainFrame)

    afx_msg void OnSetFocus(CWnd *pOldWnd);

    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);

    //}}AFX_MSG

    afx_msg LRESULT OnApply (WPARAM wParam, LPARAM lParam);

    DECLARE_MESSAGE_MAP()

    };

    ///////////////////////////////////////////////////////////////////////////

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations immediately

    // before the previous line.

    #endif

    // !defined(AFX_MAINFRM_H__9CE2B4A8_9067_11D2_8E53_006008A82731__INCLUDED_)

    MainFrm.cpp// MainFrm.cpp : implementation of the CMainFrame class

    //

    #include "stdafx.h"

    #include "PropDemo.h"

    #include "MainFrm.h"#ifdef _DEBUG

    #define new DEBUG_NEW

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    50/272

    Lp trnh Windows vi VC/MFC

    Trang 49

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CMainFrame

    IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)

    BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)

    //{{AFX_MSG_MAP(CMainFrame)

    ON_WM_SETFOCUS()

    ON_WM_CREATE()

    //}}AFX_MSG_MAP

    ON_MESSAGE (WM_USER_APPLY, OnApply)

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CMainFrame construction/destruction

    CMainFrame::CMainFrame()

    {

    }CMainFrame::~CMainFrame()

    {

    }

    BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)

    {

    if( !CFrameWnd::PreCreateWindow(cs) )

    return FALSE;

    cs.dwExStyle &= ~WS_EX_CLIENTEDGE;

    cs.lpszClass = AfxRegisterWndClass(0);

    return TRUE;

    }

    ///////////////////////////////////////////////////////////////////////////// CMainFrame diagnostics

    #ifdef _DEBUG

    void CMainFrame::AssertValid() const

    {

    CFrameWnd::AssertValid();

    }

    void CMainFrame::Dump(CDumpContext& dc) const

    {

    CFrameWnd::Dump(dc);

    }

    #endif //_DEBUG

    ///////////////////////////////////////////////////////////////////////////

    // CMainFrame message handlers

    void CMainFrame::OnSetFocus(CWnd* pOldWnd)

    {

    // forward focus to the view window

    m_wndView.SetFocus();

    }

    BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra,

    AFX_CMDHANDLERINFO* pHandlerInfo)

    {

    // let the view have first crack at the command

    if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))return TRUE;

    // otherwise, do default handling

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    51/272

    Lp trnh Windows vi VC/MFC

    Trang 50

    return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);

    }

    int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)

    {

    if (CFrameWnd::OnCreate(lpCreateStruct) == -1)

    return -1;

    if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,

    CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))

    return -1;

    return 0;

    }

    LRESULT CMainFrame::OnApply (WPARAM wParam, LPARAM lParam)

    {

    m_wndView.SendMessage (WM_USER_APPLY, wParam, lParam);

    return 0;

    }

    ChildView.h// ChildView.h : interface of the CChildView class//

    ///////////////////////////////////////////////////////////////////////////

    #if !defined(AFX_CHILDVIEW_H__9CE2B4AA_9067_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_CHILDVIEW_H__9CE2B4AA_9067_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    ///////////////////////////////////////////////////////////////////////////

    // CChildView windowclass CChildView : public CWnd

    {

    // Construction

    public:

    CChildView();

    // Attributes

    public:

    // Operations

    public:

    // Overrides

    // ClassWizard generated virtual function overrides

    //{{AFX_VIRTUAL(CChildView)

    protected:

    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

    //}}AFX_VIRTUAL

    // Implementation

    public:

    virtual ~CChildView();

    // Generated message map functions

    protected:

    int m_nUnits;

    int m_nHeight;

    int m_nWidth;int m_nColor;

    //{{AFX_MSG(CChildView)

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    52/272

    Lp trnh Windows vi VC/MFC

    Trang 51

    afx_msg void OnPaint();

    afx_msg void OnFileProperties();

    //}}AFX_MSG

    afx_msg LRESULT OnApply (WPARAM wParam, LPARAM lParam);

    DECLARE_MESSAGE_MAP()

    };

    ///////////////////////////////////////////////////////////////////////////

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations immediately

    // before the previous line.

    #endif

    //!defined(AFX_CHILDVIEW_H__9CE2B4AA_9067_11D2_8E53_006008A82731__INCLUDED_)

    ChildView.cpp// ChildView.cpp : implementation of the CChildView class

    //

    #include "stdafx.h"

    #include "PropDemo.h"

    #include "ChildView.h"#include "MyPropertySheet.h"

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CChildView

    CChildView::CChildView()

    {

    m_nWidth = 4;m_nHeight = 2;

    m_nUnits = 0;

    m_nColor = 0;

    }

    CChildView::~CChildView()

    {

    }

    BEGIN_MESSAGE_MAP(CChildView,CWnd )

    //{{AFX_MSG_MAP(CChildView)

    ON_WM_PAINT()

    ON_COMMAND(ID_FILE_PROPERTIES, OnFileProperties)

    //}}AFX_MSG_MAP

    ON_MESSAGE (WM_USER_APPLY, OnApply)

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CChildView message handlers

    BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs)

    {

    if (!CWnd::PreCreateWindow(cs))

    return FALSE;

    cs.dwExStyle = WS_EX_CLIENTEDGE;

    cs.style &= ~WS_BORDER;cs.lpszClass = AfxRegisterWndClass(CS_HREDRAWCS_VREDRAWCS_DBLCLKS,

    ::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1), NULL);

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    53/272

    Lp trnh Windows vi VC/MFC

    Trang 52

    return TRUE;

    }

    void CChildView::OnPaint()

    {

    CPaintDC dc(this); // Device context for painting.

    CBrush brush (CColorPage::m_clrColors[m_nColor]);

    CBrush* pOldBrush = dc.SelectObject (&brush);

    switch (m_nUnits) {

    case 0: // Inches.

    dc.SetMapMode (MM_LOENGLISH);

    dc.Ellipse (0, 0, m_nWidth * 100, -m_nHeight * 100);

    break;

    case 1: // Centimeters.

    dc.SetMapMode (MM_LOMETRIC);

    dc.Ellipse (0, 0, m_nWidth * 100, -m_nHeight * 100);break;

    case 2: // Pixels.

    dc.SetMapMode (MM_TEXT);

    dc.Ellipse (0, 0, m_nWidth, m_nHeight);

    break;

    }

    dc.SelectObject (pOldBrush);

    }

    void CChildView::OnFileProperties()

    {

    CMyPropertySheet ps (_T ("Properties"));

    ps.m_sizePage.m_nWidth = m_nWidth;ps.m_sizePage.m_nHeight = m_nHeight;

    ps.m_sizePage.m_nUnits = m_nUnits;

    ps.m_colorPage.m_nColor = m_nColor;

    if (ps.DoModal () == IDOK) {

    m_nWidth = ps.m_sizePage.m_nWidth;

    m_nHeight = ps.m_sizePage.m_nHeight;

    m_nUnits = ps.m_sizePage.m_nUnits;

    m_nColor = ps.m_colorPage.m_nColor;

    Invalidate ();

    }

    }

    LRESULT CChildView::OnApply (WPARAM wParam, LPARAM lParam)

    {

    ELLPROP* pep = (ELLPROP*) lParam;

    m_nWidth = pep->nWidth;

    m_nHeight = pep->nHeight;

    m_nUnits = pep->nUnits;

    m_nColor = pep->nColor;

    Invalidate ();

    return 0;

    }

    MyPropertySheet.h

    #if!defined(AFX_MYPROPERTYSHEET_H__418271A3_90D4_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_MYPROPERTYSHEET_H__418271A3_90D4_11D2_8E53_006008A82731__INCLUDED_

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    54/272

    Lp trnh Windows vi VC/MFC

    Trang 53

    #include "SizePage.h" // Added by ClassView

    #include "ColorPage.h" // Added by ClassView

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    // MyPropertySheet.h : header file

    //

    ///////////////////////////////////////////////////////////////////////////

    // CmyPropertySheet

    class CMyPropertySheet : public CPropertySheet

    {

    DECLARE_DYNAMIC(CMyPropertySheet)

    // Construction

    public:

    CMyPropertySheet(UINT nIDCaption, CWnd* pParentWnd = NULL,

    UINT iSelectPage = 0);CMyPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd = NULL,

    UINT iSelectPage = 0);

    // Attributes

    public:

    CColorPage m_colorPage;

    CSizePage m_sizePage;

    // Operations

    public:

    // Overrides

    // ClassWizard generated virtual function overrides

    //{{AFX_VIRTUAL(CMyPropertySheet)

    //}}AFX_VIRTUAL// Implementation

    public:

    virtual ~CMyPropertySheet();

    // Generated message map functions

    protected:

    //{{AFX_MSG(CMyPropertySheet)

    // NOTE - the ClassWizard will add and remove

    // member functions here.

    //}}AFX_MSG

    afx_msg void OnApply ();

    DECLARE_MESSAGE_MAP()

    };

    ///////////////////////////////////////////////////////////////////////////

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations immediately

    // before the previous line.

    #endif

    // !defined(

    // AFX_MYPROPERTYSHEET_H__418271A3_90D4_11D2_8E53_006008A82731__INCLUDED_)

    MyPropertySheet.cpp// MyPropertySheet.cpp : implementation file

    //

    #include "stdafx.h"#include "PropDemo.h"

    #include "MyPropertySheet.h"

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    55/272

    Lp trnh Windows vi VC/MFC

    Trang 54

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CMyPropertySheet

    IMPLEMENT_DYNAMIC(CMyPropertySheet, CPropertySheet)

    CMyPropertySheet::CMyPropertySheet(UINT nIDCaption, CWnd* pParentWnd,

    UINT iSelectPage) : CPropertySheet(nIDCaption, pParentWnd, iSelectPage)

    {

    AddPage (&m_sizePage);

    AddPage (&m_colorPage);

    }

    CMyPropertySheet::CMyPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd,

    UINT iSelectPage) : CPropertySheet(pszCaption, pParentWnd, iSelectPage){

    AddPage (&m_sizePage);

    AddPage (&m_colorPage);

    }

    CMyPropertySheet::~CMyPropertySheet()

    {

    }

    BEGIN_MESSAGE_MAP(CMyPropertySheet, CPropertySheet)

    //{{AFX_MSG_MAP(CMyPropertySheet)

    // NOTE - the ClassWizard will add and remove mapping macros here.

    //}}AFX_MSG_MAP

    ON_BN_CLICKED (ID_APPLY_NOW, OnApply)END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CMyPropertySheet message handlers

    void CMyPropertySheet::OnApply ()

    {

    GetActivePage ()->UpdateData (TRUE);

    ELLPROP ep;

    ep.nWidth = m_sizePage.m_nWidth;

    ep.nHeight = m_sizePage.m_nHeight;

    ep.nUnits = m_sizePage.m_nUnits;

    ep.nColor = m_colorPage.m_nColor;

    GetParent ()->SendMessage (WM_USER_APPLY, 0, (LPARAM) &ep);

    m_sizePage.SetModified (FALSE);

    m_colorPage.SetModified (FALSE);

    }

    SizePage.h#if !defined(AFX_SIZEPAGE_H__418271A1_90D4_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_SIZEPAGE_H__418271A1_90D4_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000#pragma once

    #endif // _MSC_VER > 1000

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    56/272

    Lp trnh Windows vi VC/MFC

    Trang 55

    // SizePage.h : header file

    //

    ///////////////////////////////////////////////////////////////////////////

    // CSizePage dialog

    class CSizePage : public CPropertyPage

    {

    DECLARE_DYNCREATE(CSizePage)

    // Construction

    public:

    CSizePage();

    ~CSizePage();

    // Dialog Data

    //{{AFX_DATA(CSizePage)

    enum { IDD = IDD_SIZE_PAGE };

    int m_nWidth;

    int m_nHeight;int m_nUnits;

    //}}AFX_DATA

    // Overrides

    // ClassWizard generate virtual function overrides

    //{{AFX_VIRTUAL(CSizePage)

    protected:

    virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support

    //}}AFX_VIRTUAL

    // Implementation

    protected:

    // Generated message map functions

    //{{AFX_MSG(CSizePage)// NOTE: the ClassWizard will add member functions here

    //}}AFX_MSG

    afx_msg void OnChange ();

    DECLARE_MESSAGE_MAP()

    };

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations immediately

    // before the previous line.

    #endif

    //!defined(AFX_SIZEPAGE_H__418271A1_90D4_11D2_8E53_006008A82731__INCLUDED_)

    SizePage.cpp// SizePage.cpp : implementation file//

    #include "stdafx.h"

    #include "PropDemo.h"

    #include "SizePage.h"

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CSizePage property page

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    57/272

    Lp trnh Windows vi VC/MFC

    Trang 56

    IMPLEMENT_DYNCREATE(CSizePage, CPropertyPage)

    CSizePage::CSizePage() : CPropertyPage(CSizePage::IDD)

    {

    //{{AFX_DATA_INIT(CSizePage)

    m_nWidth = 0;

    m_nHeight = 0;

    m_nUnits = -1;

    //}}AFX_DATA_INIT

    }

    CSizePage::~CSizePage()

    {

    }

    void CSizePage::DoDataExchange(CDataExchange* pDX)

    {

    CPropertyPage::DoDataExchange(pDX);

    //{{AFX_DATA_MAP(CSizePage)DDX_Text(pDX, IDC_WIDTH, m_nWidth);

    DDV_MinMaxInt(pDX, m_nWidth, 1, 128);

    DDX_Text(pDX, IDC_HEIGHT, m_nHeight);

    DDV_MinMaxInt(pDX, m_nHeight, 1, 128);

    DDX_Radio(pDX, IDC_INCHES, m_nUnits);

    //}}AFX_DATA_MAP

    }

    BEGIN_MESSAGE_MAP(CSizePage, CPropertyPage)

    //{{AFX_MSG_MAP(CSizePage)

    // NOTE: the ClassWizard will add message map macros here

    //}}AFX_MSG_MAP

    ON_EN_CHANGE (IDC_WIDTH, OnChange)ON_EN_CHANGE (IDC_HEIGHT, OnChange)

    ON_BN_CLICKED (IDC_INCHES, OnChange)

    ON_BN_CLICKED (IDC_CENTIMETERS, OnChange)

    ON_BN_CLICKED (IDC_PIXELS, OnChange)

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CSizePage message handlers

    void CSizePage::OnChange ()

    {

    SetModified (TRUE);

    }

    ColorPage.h#if !defined(AFX_COLORPAGE_H__418271A2_90D4_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_COLORPAGE_H__418271A2_90D4_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    // ColorPage.h : header file

    //

    ///////////////////////////////////////////////////////////////////////////

    // CColorPage dialog

    class CColorPage : public CPropertyPage{

    DECLARE_DYNCREATE(CColorPage)

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    58/272

    Lp trnh Windows vi VC/MFC

    Trang 57

    // Construction

    public:

    CColorPage();

    ~CColorPage();

    static const COLORREF m_clrColors[3];

    // Dialog Data

    //{{AFX_DATA(CColorPage)

    enum { IDD = IDD_COLOR_PAGE };

    int m_nColor;

    //}}AFX_DATA

    // Overrides

    // ClassWizard generate virtual function overrides

    //{{AFX_VIRTUAL(CColorPage)

    protected:

    virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support

    //}}AFX_VIRTUAL

    // Implementationprotected:

    // Generated message map functions

    //{{AFX_MSG(CColorPage)

    // NOTE: the ClassWizard will add member functions here

    //}}AFX_MSG

    afx_msg void OnChange ();

    DECLARE_MESSAGE_MAP()

    };

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations immediately

    // before the previous line.

    #endif//defined(AFX_COLORPAGE_H__418271A2_90D4_11D2_8E53_006008A82731__INCLUDED_)

    ColorPage.cpp// ColorPage.cpp : implementation file

    //

    #include "stdafx.h"#include "PropDemo.h"

    #include "ColorPage.h"

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CColorPage property page

    IMPLEMENT_DYNCREATE(CColorPage, CPropertyPage)

    const COLORREF CColorPage::m_clrColors[3] = {

    RGB (255, 0, 0), // Red

    RGB ( 0, 255, 0), // Green

    RGB ( 0, 0, 255) // Blue

    };

    CColorPage::CColorPage() : CPropertyPage(CColorPage::IDD)

    {//{{AFX_DATA_INIT(CColorPage)

    m_nColor = -1;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    59/272

    Lp trnh Windows vi VC/MFC

    Trang 58

    //}}AFX_DATA_INIT

    }

    CColorPage::~CColorPage()

    {

    }

    void CColorPage::DoDataExchange(CDataExchange* pDX)

    {

    CPropertyPage::DoDataExchange(pDX);

    //{{AFX_DATA_MAP(CColorPage)

    DDX_Radio(pDX, IDC_RED, m_nColor);

    //}}AFX_DATA_MAP

    }

    BEGIN_MESSAGE_MAP(CColorPage, CPropertyPage)

    //{{AFX_MSG_MAP(CColorPage)

    // NOTE: the ClassWizard will add message map macros here

    //}}AFX_MSG_MAP

    ON_BN_CLICKED (IDC_RED, OnChange)

    ON_BN_CLICKED (IDC_GREEN, OnChange)ON_BN_CLICKED (IDC_BLUE, OnChange)

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CColorPage message handlers

    void CColorPage::OnChange ()

    {

    SetModified (TRUE);

    }

    Mn hnh kt qu nh sau:

    1.8 Mt siu khin trong Windows 9.x*1.8.1 Cc loi iu khinCc iu khin c pht sinh thm trong hiu hnh Windows 95 (hay cc hiu hnh Windows mi hn)c cc lp tng ng trong MFC nh sau:

    Control Type WNDCLASS WNDCLASS Alias MFC ClassAnimation "SysAnimate32" ANIMATE_CLASS CAnimateCtrlComboBoxEx* "ComboBoxEx32" WC_COMBOBOXEX CComboBoxExDate-Time* "SysDateTimePick32" DATETIMEPICK_CLASS CDateTimeCtrl

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    60/272

    Lp trnh Windows vi VC/MFC

    Trang 59

    Header "SysHeader32" WC_HEADER CHeaderCtrlHotkey "msctls_hotkey32" HOTKEY_CLASS CHotKeyCtrlImage list N/A N/A CImageListIP address** "SysIPAddress32" WC_IPADDRESS CIPAddressCtrlList view "SysListView32" WC_LISTVIEW CListCtrlMonth calendar* "SysMonthCal32" MONTHCAL_CLASS CMonthCalCtrlProgress "msctls_progress32" PROGRESS_CLASS CProgressCtrlProperty sheet N/A N/A CPropertySheetRebar* "ReBarWindow32" REBARCLASSNAME CReBarCtrlRich edit "RichEdit20A" (ANSI) or

    "RichEdit20W" (Unicode)RICHEDIT_CLASS CRichEditCtrl

    Slider "msctls_trackbar32" TRACKBAR_CLASS CSliderCtrlSpin button "msctls_updown32" UPDOWN_CLASS CSpinButtonCtrlStatus bar "msctls_statusbar32" STATUSCLASSNAME CStatusBarCtrlTab "SysTabControl32" WC_TABCONTROL CTabCtrlToolbar "ToolbarWindow32" TOOLBARCLASSNAME CToolBarCtrlToolTip "tooltips_class32" TOOLTIPS_CLASS CToolTipCtrlTree view "SysTreeView32" WC_TREEVIEW CTreeCtrl1.8.2 V d tng hp:

    1.8.2.1 Chng trnh 1:ChildView.h// ChildView.h : interface of the CChildView class

    //

    ///////////////////////////////////////////////////////////////////////////

    #if !defined(

    AFX_CHILDVIEW_H__A4559BAA_ABE5_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_CHILDVIEW_H__A4559BAA_ABE5_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    ///////////////////////////////////////////////////////////////////////////

    // CChildView window

    class CChildView : public CWnd

    {

    // Construction

    public:

    CChildView();

    // Attributes

    public:

    // Operations

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    61/272

    Lp trnh Windows vi VC/MFC

    Trang 60

    public:

    // Overrides

    // ClassWizard generated virtual function overrides

    //{{AFX_VIRTUAL(CChildView)

    protected:

    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

    //}}AFX_VIRTUAL

    // Implementation

    public:

    virtual ~CChildView();

    // Generated message map functions

    protected:

    int m_nWeight;

    int m_cy;

    int m_cx;//{{AFX_MSG(CChildView)

    afx_msg void OnPaint();

    afx_msg void OnOptionsGridSettings();

    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()

    };

    ///////////////////////////////////////////////////////////////////////////

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations

    // immediately before the previous line.

    #endif

    // !defined(// AFX_CHILDVIEW_H__A4559BAA_ABE5_11D2_8E53_006008A82731__INCLUDED_)

    ChildView.cpp// ChildView.cpp : implementation of the CChildView class

    //

    #include "stdafx.h"

    #include "GridDemo.h"

    #include "ChildView.h"

    #include "SettingsDialog.h"

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CChildView

    CChildView::CChildView()

    {

    m_cx = 8;

    m_cy = 8;

    m_nWeight = 4;

    }

    CChildView::~CChildView(){

    }

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    62/272

    Lp trnh Windows vi VC/MFC

    Trang 61

    BEGIN_MESSAGE_MAP(CChildView,CWnd )

    //{{AFX_MSG_MAP(CChildView)

    ON_WM_PAINT()

    ON_COMMAND(ID_OPTIONS_GRID_SETTINGS, OnOptionsGridSettings)

    //}}AFX_MSG_MAP

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CChildView message handlers

    BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs)

    {

    if (!CWnd::PreCreateWindow(cs))

    return FALSE;

    cs.dwExStyle |= WS_EX_CLIENTEDGE;

    cs.style &= ~WS_BORDER;

    cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,

    ::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1), NULL);

    return TRUE;

    }

    void CChildView::OnPaint()

    {

    CRect rect;

    GetClientRect (&rect);

    int nShade = m_nWeight * 32;

    if (nShade != 0)

    nShade- -;

    CPaintDC dc (this);CPen pen (PS_SOLID, 1, RGB (nShade, nShade, nShade));

    CPen* pOldPen = dc.SelectObject (&pen);

    int x;

    for (int i=1; i

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    63/272

    Lp trnh Windows vi VC/MFC

    Trang 62

    dlg.m_nWeight = m_nWeight;

    if (dlg.DoModal () == IDOK) {

    m_cx = dlg.m_cx;

    m_cy = dlg.m_cy;

    m_nWeight = dlg.m_nWeight;

    Invalidate ();

    }

    }

    SettingsDialog.h#if !defined(

    AFX_SETTINGSDIALOG_H__A4559BB0_ABE5_11D2_8E53_006008A82731__INCLUDED_)

    #define

    AFX_SETTINGSDIALOG_H__A4559BB0_ABE5_11D2_8E53_006008A82731__INCLUDED_

    #include "MyToolTipCtrl.h" // Added by ClassView

    #if _MSC_VER > 1000

    #pragma once#endif // _MSC_VER > 1000

    // SettingsDialog.h : header file

    //

    ///////////////////////////////////////////////////////////////////////////

    // CSettingsDialog dialog

    class CSettingsDialog : public CDialog

    {

    // Construction

    public:

    int m_nWeight;

    CSettingsDialog(CWnd* pParent = NULL); // standard constructor

    // Dialog Data

    //{{AFX_DATA(CSettingsDialog)

    enum { IDD = IDD_SETTINGDLG };

    CSpinButtonCtrl m_wndSpinVert;

    CSpinButtonCtrl m_wndSpinHorz;

    CSliderCtrl m_wndSlider;

    int m_cx;

    int m_cy;

    //}}AFX_DATA

    // Overrides

    // ClassWizard generated virtual function overrides

    //{{AFX_VIRTUAL(CSettingsDialog)

    protected:

    virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support

    //}}AFX_VIRTUAL

    // Implementation

    protected:

    CMyToolTipCtrl m_ctlTT;

    // Generated message map functions

    //{{AFX_MSG(CSettingsDialog)

    virtual BOOL OnInitDialog();virtual void OnOK();

    //}}AFX_MSG

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    64/272

    Lp trnh Windows vi VC/MFC

    Trang 63

    DECLARE_MESSAGE_MAP()

    };

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations

    // immediately before the previous line.

    #endif

    // !defined(

    // AFX_SETTINGSDIALOG_H__A4559BB0_ABE5_11D2_8E53_006008A82731__INCLUDED_)

    SettingsDialog.cpp// SettingsDialog.cpp : implementation file

    //

    #include "stdafx.h"

    #include "GridDemo.h"

    #include "MyToolTipCtrl.h"

    #include "SettingsDialog.h"

    #ifdef _DEBUG#define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CSettingsDialog dialog

    CSettingsDialog::CSettingsDialog(CWnd* pParent /*=NULL*/)

    : CDialog(CSettingsDialog::IDD, pParent)

    {

    //{{AFX_DATA_INIT(CSettingsDialog)

    m_cx = 0;

    m_cy = 0;//}}AFX_DATA_INIT

    }

    void CSettingsDialog::DoDataExchange(CDataExchange* pDX)

    {

    CDialog::DoDataExchange(pDX);

    //{{AFX_DATA_MAP(CSettingsDialog)

    DDX_Control(pDX, IDC_SPINVERT, m_wndSpinVert);

    DDX_Control(pDX, IDC_SPINHORZ, m_wndSpinHorz);

    DDX_Control(pDX, IDC_SLIDER, m_wndSlider);

    DDX_Text(pDX, IDC_EDITHORZ, m_cx);

    DDX_Text(pDX, IDC_EDITVERT, m_cy);

    //}}AFX_DATA_MAP

    }

    BEGIN_MESSAGE_MAP(CSettingsDialog, CDialog)

    //{{AFX_MSG_MAP(CSettingsDialog)

    //}}AFX_MSG_MAP

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CSettingsDialog message handlers

    BOOL CSettingsDialog::OnInitDialog()

    {

    CDialog::OnInitDialog();

    //// Initialize the slider control.

    //

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    65/272

    Lp trnh Windows vi VC/MFC

    Trang 64

    m_wndSlider.SetRange (0, 8);

    m_wndSlider.SetPos (m_nWeight);

    //

    // Initialize the spin button controls.

    //

    m_wndSpinHorz.SetRange (2, 64);

    m_wndSpinVert.SetRange (2, 64);

    //

    // Create and initialize a tooltip control.

    //

    m_ctlTT.Create (this);

    m_ctlTT.AddWindowTool (GetDlgItem (IDC_SLIDER),

    MAKEINTRESOURCE (IDS_SLIDER));

    m_ctlTT.AddWindowTool (GetDlgItem (IDC_EDITHORZ),

    MAKEINTRESOURCE (IDS_EDITHORZ));

    m_ctlTT.AddWindowTool (GetDlgItem (IDC_EDITVERT),

    MAKEINTRESOURCE (IDS_EDITVERT));

    return TRUE;}

    void CSettingsDialog::OnOK()

    {

    //

    // Read the slider control's thumb position

    // before dismissing the dialog.

    //

    m_nWeight = m_wndSlider.GetPos ();

    CDialog::OnOK();

    }

    MyToolTipCtrl.h#if !defined(

    AFX_MYTOOLTIPCTRL_H__A4559BB1_ABE5_11D2_8E53_006008A82731__INCLUDED_)

    #define

    AFX_MYTOOLTIPCTRL_H__A4559BB1_ABE5_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    // MyToolTipCtrl.h : header file

    //

    ///////////////////////////////////////////////////////////////////////////

    // CMyToolTipCtrl window

    class CMyToolTipCtrl : public CToolTipCtrl

    {

    // Construction

    public:

    CMyToolTipCtrl();

    // Attributes

    public:

    // Operations

    public:

    // Overrides

    // ClassWizard generated virtual function overrides

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    66/272

    Lp trnh Windows vi VC/MFC

    Trang 65

    //{{AFX_VIRTUAL(CMyToolTipCtrl)

    //}}AFX_VIRTUAL

    // Implementation

    public:

    BOOL AddRectTool (CWnd* pWnd, LPCTSTR pszText, LPCRECT pRect,

    UINT nIDTool);

    BOOL AddWindowTool (CWnd* pWnd, LPCTSTR pszText);

    virtual ~CMyToolTipCtrl();

    // Generated message map functions

    protected:

    //{{AFX_MSG(CMyToolTipCtrl)

    // NOTE - the ClassWizard will add and remove member functions here.

    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()

    };///////////////////////////////////////////////////////////////////////////

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations

    // immediately before the previous line.

    #endif

    // !defined(

    // AFX_MYTOOLTIPCTRL_H__A4559BB1_ABE5_11D2_8E53_006008A82731__INCLUDED_)

    MyToolTipCtrl.cpp// MyToolTipCtrl.cpp : implementation file

    //

    #include "stdafx.h"

    #include "GridDemo.h"#include "MyToolTipCtrl.h"

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CMyToolTipCtrl

    CMyToolTipCtrl::CMyToolTipCtrl()

    {

    }

    CMyToolTipCtrl::~CMyToolTipCtrl()

    {

    }

    BEGIN_MESSAGE_MAP(CMyToolTipCtrl, CToolTipCtrl)

    //{{AFX_MSG_MAP(CMyToolTipCtrl)

    // NOTE - the ClassWizard will add and remove mapping macros here.

    //}}AFX_MSG_MAP

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CMyToolTipCtrl message handlers

    BOOL CMyToolTipCtrl::AddWindowTool(CWnd *pWnd, LPCTSTR pszText){

    TOOLINFO ti;

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    67/272

    Lp trnh Windows vi VC/MFC

    Trang 66

    ti.cbSize = sizeof (TOOLINFO);

    ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;

    ti.hwnd = pWnd->GetParent ()->GetSafeHwnd ();

    ti.uId = (UINT) pWnd->GetSafeHwnd ();

    ti.hinst = AfxGetInstanceHandle ();

    ti.lpszText = (LPTSTR) pszText;

    return (BOOL) SendMessage (TTM_ADDTOOL, 0, (LPARAM) &ti);

    }

    BOOL CMyToolTipCtrl::AddRectTool(CWnd *pWnd, LPCTSTR pszText,

    LPCRECT pRect, UINT nIDTool)

    {

    TOOLINFO ti;

    ti.cbSize = sizeof (TOOLINFO);

    ti.uFlags = TTF_SUBCLASS;

    ti.hwnd = pWnd->GetSafeHwnd ();

    ti.uId = nIDTool;

    ti.hinst = AfxGetInstanceHandle ();

    ti.lpszText = (LPTSTR) pszText;::CopyRect (&ti.rect, pRect);

    return (BOOL) SendMessage (TTM_ADDTOOL, 0, (LPARAM) &ti);

    }

    Mn hnh kt qu nh sau:

    1.8.2.2 Chng trnh 2:

    PathListDlg.h// PathListDlg.h : header file

    //

    #if !defined(

    AFX_PATHLISTDLG_H__710413E6_AC66_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_PATHLISTDLG_H__710413E6_AC66_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    ///////////////////////////////////////////////////////////////////////////

    // CPathListDlg dialog

    class CPathListDlg : public CDialog

    {

    // Construction

    public:

    CPathListDlg(CWnd* pParent = NULL); // standard constructor

    // Dialog Data

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    68/272

    Lp trnh Windows vi VC/MFC

    Trang 67

    //{{AFX_DATA(CPathListDlg)

    enum { IDD = IDD_PATHLIST_DIALOG };

    CPathComboBox m_wndCBEx;

    //}}AFX_DATA

    // ClassWizard generated virtual function overrides

    //{{AFX_VIRTUAL(CPathListDlg)

    protected:

    virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support

    //}}AFX_VIRTUAL

    // Implementation

    protected:

    HICON m_hIcon;

    // Generated message map functions

    //{{AFX_MSG(CPathListDlg)

    virtual BOOL OnInitDialog();afx_msg void OnPaint();

    afx_msg HCURSOR OnQueryDragIcon();

    afx_msg void OnSelEndOK();

    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()

    };

    //{{AFX_INSERT_LOCATION}}

    // Microsoft Visual C++ will insert additional declarations

    // immediately before the previous line.

    #endif

    // !defined(

    // AFX_PATHLISTDLG_H__710413E6_AC66_11D2_8E53_006008A82731__INCLUDED_)

    PathListDlg.cpp// PathListDlg.cpp : implementation file

    //

    #include "stdafx.h"

    #include "PathList.h"

    #include "PathComboBox.h"

    #include "PathListDlg.h"

    #ifdef _DEBUG

    #define new DEBUG_NEW

    #undef THIS_FILE

    static char THIS_FILE[] = __FILE__;

    #endif

    ///////////////////////////////////////////////////////////////////////////

    // CPathListDlg dialog

    CPathListDlg::CPathListDlg(CWnd* pParent /*=NULL*/)

    : CDialog(CPathListDlg::IDD, pParent)

    {

    //{{AFX_DATA_INIT(CPathListDlg)

    //}}AFX_DATA_INIT

    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

    }

    void CPathListDlg::DoDataExchange(CDataExchange* pDX)

    {CDialog::DoDataExchange(pDX);

    //{{AFX_DATA_MAP(CPathListDlg)

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    69/272

    Lp trnh Windows vi VC/MFC

    Trang 68

    DDX_Control(pDX, IDC_CBEX, m_wndCBEx);

    //}}AFX_DATA_MAP

    }

    BEGIN_MESSAGE_MAP(CPathListDlg, CDialog)

    //{{AFX_MSG_MAP(CPathListDlg)

    ON_WM_PAINT()

    ON_WM_QUERYDRAGICON()

    ON_CBN_SELENDOK(IDC_CBEX, OnSelEndOK)

    //}}AFX_MSG_MAP

    END_MESSAGE_MAP()

    ///////////////////////////////////////////////////////////////////////////

    // CPathListDlg message handlers

    BOOL CPathListDlg::OnInitDialog()

    {

    CDialog::OnInitDialog();

    SetIcon(m_hIcon, TRUE);

    SetIcon(m_hIcon, FALSE);//

    // Initialize the ComboBoxEx control.

    //

    TCHAR szPath[MAX_PATH];

    ::GetCurrentDirectory (sizeof (szPath) / sizeof (TCHAR), szPath);

    m_wndCBEx.SetPath (szPath);

    return TRUE;

    }

    void CPathListDlg::OnPaint()

    {

    if (IsIconic())

    {CPaintDC dc(this); // device context for painting

    SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

    // Center icon in client rectangle

    int cxIcon = GetSystemMetrics(SM_CXICON);

    int cyIcon = GetSystemMetrics(SM_CYICON);

    CRect rect;

    GetClientRect(&rect);

    int x = (rect.Width() - cxIcon + 1) / 2;

    int y = (rect.Height() - cyIcon + 1) / 2;

    // Draw the icon

    dc.DrawIcon(x, y, m_hIcon);

    }

    else

    {

    CDialog::OnPaint();

    }

    }

    HCURSOR CPathListDlg::OnQueryDragIcon()

    {

    return (HCURSOR) m_hIcon;}

    void CPathListDlg::OnSelEndOK()

  • 8/2/2019 Lap Trinh Windows Voi VC.mfc [DH KTCN]

    70/272

    Lp trnh Windows vi VC/MFC

    Trang 69

    {

    //

    // Display the path just selected from the ComboBoxEx control.

    //

    MessageBox (m_wndCBEx.GetPath ());

    }

    PathComboBox.h#if !defined(

    AFX_PATHCOMBOBOX_H__710413F1_AC66_11D2_8E53_006008A82731__INCLUDED_)

    #define AFX_PATHCOMBOBOX_H__710413F1_AC66_11D2_8E53_006008A82731__INCLUDED_

    #if _MSC_VER > 1000

    #pragma once

    #endif // _MSC_VER > 1000

    // PathComboBox.h : header file

    //

    ///////////////////////////////////////////////////////////////////