Professional Documents
Culture Documents
LT Windows MFCVC
LT Windows MFCVC
GIO TRNH MN HC
Thng 03 nm 2006
Trang 1
0.2 Hm v li gi hm
0.3 n tp C++
Trang 2
1.1.2
K thut lp trnh s dng cc hm Windows API cn gi l lp trnh Windows SDK. Mt ng dng xy dng theo k thut ny cha ng hm WinMain (x l cc thng bo (message) nhn c/gi i nhm p ng yu cu 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 nh sau:
V d:
#include <windows.h> LONG WINAPI WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { WNDCLASS wc; HWND hwnd; MSG msg;
Trang 3
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", "SDK Application", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL ); 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); }
// // // // // // // // // // //
WNDCLASS name Window title Window style Horizontal position Vertical position Initial width Initial height Handle of parent window Menu handle Application's instance handle Window-creation data
Trang 4
1.1.3
Lp trnh Windows vi MFC l k thut lp trnh s dng b th vin MFC ca Microsoft xy dng cc trnh ng dng trong Windows (Window App) v cc dng ng dng khc nh DLL, COM, ActiveX MFC (Microsoft Foundation Classes) l th vin c s cha cc lp (class) C++ do Microsoft cung cp nhm t 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 ti liu cho trnh ng dng n gin, uyn chuyn v d pht trin hn. Do MFC cn c xem l mt khung ng dng (application framework) Vic h tr lp tha k v cc hm AFX cng nh cc lp tin ch ca MFC gip ngi dng thun tin hn vic pht trin ng dng to nhanh cc iu khin (control) trong Windows v truy xut chng nhanh chng v d dng.
1.1.4
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 ca ng 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 hi thoi, biu tng, menu, toolbar...
Trang 5
1.1.4.2 Ca s xut (output pane) Ca s ny nm phn di cng trong ca s ng Visual C++, thng c th khng hin trn mn hnh khi khi 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 v thng bo li ca trnh bin dch, ng thi l ni chng trnh g ri hin th tt c cc in vi nhng gi tr hin 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 s dng Visual C++, ni cc ca s son tho chng trnh hin th, ng thi l ni ca s v hin th khi ngi dng thit k hp thoi.
Trang 6
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 Visual C++ c sn nhiu thanh cng c khc nhau, ngi dng c th ty bin to cc thanh cng c ph hp nht cho ring mnh.
1.1.4.5
Thanh cng c
Trang 7
1.1.5
Cc loi file lin quan n ng dng VC++: Phn m rng Din gii APS Supports ResourceView BSC Browser information file CLW Supports ClassWizard DEP Dependency file DSP Project file* DSW Workspace file* MAK External makefile NCB Supports ClassView OPT Holds workspace configuration PLG Builds log file V d tng hp: Hello.h
class CMyApp : public CWinApp { public: virtual BOOL InitInstance(); }; class CMainWindow : public CFrameWnd { public: CMainWindow(); protected: afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() };
Hello.cpp
#include <afxwin.h> #include "Hello.h" CMyApp myApp;
Trang 8
Mn hnh kt qu nh sau:
Mt ng dng pht trin da trn tp th vin c s MFC bao gm mt s i tng v qu trnh x l nh sau:: 1.1.5.1 i tng ng dng (Application) Trung tm ca mt ng dng MFC l i tng (application) da trn lp CWinApp. CWinApp cung cp mt vng lp thng bo nhn cc thng bo v phn phi chng cho ca s ng dng. N cng bao gm cc hm o chnh yu (n m c th b khai bo v iu chnh li cc hnh vi ca ng dng). CWinApp v cc lp MFC khc c a vo trong ng dng khi chng ta gn kt (include) file tiu Afxwin.h. ng dng MFC c th c duy nht mt i tng ng dng v i tng ng dng ny cn c khai bo vi phm vi ton cc c khi to trong b nh t 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 t lp cha CWinApp. Hm InitInstance c gi t rt sm trong thi gian sng ca ng dng, ngay sau khi ng dng bt u thc thi nhng trc khi ca s ng dng c to ra. Thc t, ngoi tr vic hm InitInstance to mt 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.
Trang 9
Lp trnh Windows vi VC/MFC 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 ng dng to ra. Lp ca s chnh ca ng dng, CMainWindow, c k tha t lp CFrameWnd (cng c k tha t CWnd). Lp CFrameWnd m hnh ho cc hnh vi ca khung ca s, ng thi n l ca s mc cao nht phc v nh mt giao din ch yu ca ng dng vi th gii bn ngoi. Trong ng cnh l tng ca kin trc 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 CreateEx ca 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, v END_MESSAGE_MAP trong Afxwin.h v m lnh cho hm CWnd::WindowProc trong Wincore.cpp
// In the class declaration DECLARE_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 tip hm GetMessageMap ly con tr ch n CMainWindow::messageMap v tm kim CMainWindow::_messageEntries cho nhng thng bo c ID trng vi ID ca cc thng bo ang ch x l. Nu kt qu tm thy, lp CMainWindow tng ng (ca nhng a ch c lu trong dy _messageEntries vi ID ca thng bo) c gi. Ngc li, OnWndMsg tham kho CMainWindow::messageMap cho mt con tr ch ti CFrameWnd::messageMap v lp li qu trnh cho lp c s. Nu lp c s khng c mt iu khin (handler) cho thng bo, khung ng dng the framework pht trin ln mc khc v tham kho n lp c s cha. 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 cho CMainWindow.
Trang 10
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 cc phin 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 v cho 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 khng h tr vic chuyn i t ANSI sang Unicode cho tt c k t. Ngc li, ng dng dng Unicode khng thc thi 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 s c th hin dng Unicode 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 kt tng ng. tham_s l FALSE: hm s thc hin vic cp nht d liu t cc bin lin kt vo trong cc iu khin tng ng v hin th trn giao din chng trnh. 0 Mt s lu : 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 th TCHAR tr thnh k hiu thng thng. Khng nn dng char* hay wchar_t* khai bo con tr kiu chui TCHAR. Nn dng TCHAR* hay LPTSTR (con tr ch ti chui TCHAR) v LPCTSTR (con tr ch ti chui hng TCHAR). Khng nn gi nh l k t ch c rng 8 bit. chuyn mt di ca b m nhanh dng byte sang 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 macros tng ng trong file tiu Tchar.h (v d, _tcscpy).
Trang 11
1.1.6
T menu File, ngi dng chn lnh New... to mi mt d n (project), mt tp tin (file) hay mt khng gian 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 MFC AppWizard (exe) To th vin trong Windows (dng DLL file) vi MFC c h tr t 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 Console Application... c bit, khi ngi dng chn cch to ng dng dng ca s vi MFC AppWizard (exe), ngi dng c th to trnh ng dng dng hp thoi (dialog), ng dng n ti liu (Single Document Interface - SDI), ng dng a ti liu (Multi Document Interface - MDI) Nu to ng dng dng hp thoi (dialog), ngi dng cn lm nh sau: Bc khi u:
Bc 1:
Trang 12
Bc 2:
Bc 3:
Bc 4:
Trang 13
Bc kt thc:
Bc 1:
Trang 14
Bc 3:
Bc 4:
Bc 5:
Trang 15
Bc 6:
Bc kt thc:
Vn quan tm
Tm hiu v ng cnh thit b v giao din thit b ho. S h tr ca MFC v cc lp cng c v (CPen, CBrush)
1.2.2
Gii thiu
H iu hnh Windows cung cp thit b ho o (Graphics Device Interface - GDI) gip ngi dng thc hin 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 mt lun 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 ho ang c v trong WindowApp . Thc cht ng cnh thit b dng hin th ho l ng cnh o ca ca s. Trang 16
1.2.3
MFC cung cp mt s lp ng cnh thit b (k tha t lp CDC) nh: Class M t CPaintDC 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 s CMetaFileDC S dng cho vic v mt GDI metafile ly ng cnh thit b, dng:
CDC dc(this);
hay
CDC* pDC = GetDC();
Ng cnh thit b dng bt v (pen) v cc ng thng/hnh dng, v c v (brush) t y cc vng ca 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
MM_TEXT
MM_LOMETRIC
0.1 mm
MM_HIMETRIC
0.01 mm
Trang 17
MM_HIENGLISH
0.001 in.
MM_TWIPS
MM_ISOTROPIC MM_ANISOTROPIC
1.2.4
Thao tc v vi bt v
Trong MFC, lp bt v l CPen, c dng v kiu ng bt k vi mu/ rng xc nh, v d nh sau to 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); ...
trong hm RGB(r, g, b) to mu ch nh da trn 3 mu c bn 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:
Trang 18
trong
Mt s phng thc v ng: Phng thc M t MoveTo Di chuyn bt v n 1 im xc nh LineTo V 1 on thng t im hin hnh ca bt v n 1 im xc nh v di chuyn v tr hin hnh n im mi ny Polyline V ng gp khc (tp hp cc an gp khc) PolylineTo V ng gp khc v di chuyn v tr hin hnh n nh cui cng ca ng ny. Arc V cung ArcTo V cung v di chuyn v tr hin hnh n nh cui cng ca cung ny. PolyBezier V ng Bezier PolyBezierTo V ng Bezier v di chuyn v tr hin hnh n nh cui cng ca ng ny. Mt s phng thc v hnh khi: Phng thc M t Chord V hnh dng bn cu Ellipse V hnh dng ellipse Pie V hnh dng bnh Polygon Ni mt tp cc im ca mt a gic Rectangle V hnh dng ch nht RoundRect V hnh dng ch nht trn gc Mt s m mu thng dng: Tn mu R Black 0 Blue 0 Green 0 Cyan 0 Red 192 Magenta 192 Yellow 192 Dark gray 128 G 0 0 192 192 0 0 192 128 B 0 192 0 192 0 192 0 128 Tn mu Light gray Bright blue Bright green Bright cyan Bright red Bright magenta Bright yellow White R 192 0 0 0 255 255 255 255 G 192 0 255 255 0 0 255 255 B 192 255 0 255 0 255 0 255 Trang 19
0 Ch :
Lp trnh Windows vi VC/MFC Vic x l v c th t trong s kin OnPaint, OnDraw hay cc s kin lin quan n thao tc chut v bn phm. 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 :
Mn hnh kt qu l
Trang 20
1.2.5
Thao tc t mu vi c v
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
Ng cnh thit b cung cp mt s hm thc hin vic h tr hin th vn bn trong mi trng ho nh sau: Hm M t DrawText V mt vn bn trong mt khung ch nht nh dng trc TextOut Xut mt hnh vn bn ti v tr hin hnh hay ti im xc nh TabbedTextOut Xut mt hnh vn bn cha ng cc k hiu tab ExtTextOut 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 hnh GetTabbedTextExtent Ly rng chui (c cha ng k hiu tab) vi font s dng hin hnh GetTextMetrics Ly font metrics (chiu cao k t, rng trung bnh) ca font hin hnh Trang 21
hay:
dc.DrawText (_T ("Hello, MFC"), -1, &rect, DT_SINGLELINE DT_CENTER DT_VCENTER);
1.2.7
Ngoi 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:
Mn hnh kt qu nh sau:
1.2.8
1.2.8.1 Accel.h
V d tng hp
Chng trnh 1
#define LINESIZE 8 class CMyApp : public CWinApp { public: virtual BOOL InitInstance(); }; class CMainWindow : public CFrameWnd { protected: int m_nCellWidth; // Cell width in pixels int m_nCellHeight; // Cell height in pixels
Trang 23
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 <afxwin.h> #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;
Trang 24
Trang 25
Trang 26
Trang 27
Mn hnh kt qu nh sau
Trang 28
1.2.8.2 Ruler.h
Chng trnh 2
class CMyApp : public CWinApp { public: virtual BOOL InitInstance(); }; class CMainWindow : public CFrameWnd { public: CMainWindow(); protected: afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() };
Ruler.cpp
#include <afxwin.h> #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);
Trang 29
Mn hnh kt qu nh sau:
Vn quan tm
Cc thng ip (message) v s kin ca chut, bn phm
Trang 30
Lp trnh Windows vi VC/MFC Nhn bit v x l cc thao tc lin quan n cc s kin ca chut, bn phm.
1.3.2
Cc s kin ca chut
Hm iu khin OnLButtonDown OnLButtonUp OnLButtonDblClk
MFC h tr thao tc vi chut bng vic lin h cc thng ip v cc s kin nh: Thng ip Macro kt hp S kin WM_LBUTTONDOWN ON_WM_LBUTTONDOWN Nt tri chut c nhn xung. WM_LBUTTONUP ON_WM_LBUTTONUP Nt tri chut c nh ra. WM_LBUTTONDBLCLK ON_WM_LBUTTONDBLCLK Nt tri chut c nhn kp(double) WM_MBUTTONDOWN ON_WM_MBUTTONDOWN Nt gia chut c nhn xung. WM_MBUTTONUP ON_WM_MBUTTONUP Nt gia chut c nh ra. WM_MBUTTONDBLCLK ON_WM_MBUTTONDBLCLK Nt gia chut c nhn kp(double) WM_RBUTTONDOWN ON_WM_RBUTTONDOWN Nt phi chut c nhn xung. WM_RBUTTONUP ON_WM_RBUTTONUP Nt phi chut c nh ra. WM_RBUTTONDBLCLK ON_WM_RBUTTONDBLCLK Nt phi chut c nhn kp(double) WM_MOUSEMOVE ON_WM_MOUSEMOVE Con tr chut di chuyn trong vng hin th ca ca s. Cc hm iu khin c dng:
afx_msg void OnMsgName(UINT nFlags, CPoint point)
OnMouseMove
Trong nFlags(dng nhn bit nt bm chut v cc phm Ctrl/Shift bi php ton &) c gi tr: Mt n (Mask) Nhn bit khi MK_LBUTTON Nt tri chut c nhn MK_MBUTTON Nt gia chut c nhn MK_RBUTTON Nt phi chut c nhn MK_CONTROL Phm Ctrl c nhn MK_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) {
Trang 31
1.3.3
Cc s kin ca bn phm
MFC h tr thao tc vi bn phm bng vic lin h cc thng ip v cc s kin nh sau: Thng ip Macro kt hp S kin Hm iu khin WM_KEYDOWN ON_WM_KEYDOWN Phm c OnKeyDown nhn xung. WM_KEYUP ON_WM_KEYUP Phm c OnKeyUp nh ra. WM_SYSKEYDOWN ON_WM_SYSKEYDOWN Nt chc OnSysKeyDown nng c nhn xung. WM_SYSKEYUP ON_WM_SYSKEYUP Phm chc OnSysKeyUp nng c nh ra. 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 ng VK_F1_VK_F12 Function keys F1_F12 VK_NUMPAD0_VK_NUMPAD9 Numeric keypad 0_9 with Num Lock on VK_CANCEL Ctrl-Break VK_RETURN Enter VK_BACK Backspace VK_TAB Tab VK_CLEAR Numeric keypad 5 with Num Lock off VK_SHIFT Shift VK_CONTROL Ctrl VK_MENU Alt Trang 32
Lp trnh Windows vi VC/MFC VK_PAUSE VK_ESCAPE VK_SPACE VK_PRIOR VK_NEXT VK_END VK_HOME VK_LEFT VK_UP VK_RIGHT VK_DOWN VK_SNAPSHOT VK_INSERT VK_DELETE VK_MULTIPLY VK_ADD VK_SUBTRACT VK_DECIMAL VK_DIVIDE VK_CAPITAL VK_NUMLOCK VK_SCROLL VK_LWIN VK_RWIN VK_APPS Pause Esc Spacebar Page Up and PgUp Page Down and PgDn End Home Left arrow Up arrow Right arrow Down arrow Print Screen Insert and Ins Delete and Del Numeric keypad * Numeric keypad + Numeric keypad Numeric keypad . Numeric keypad / Caps Lock Num Lock Scroll Lock Left Windows key Right Windows key 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('Z'))) || ((nChar >= _T('a')) &&(nChar <= _T('z')))) { // Display the character m_szInput += _T(nChar); MyDrawFunction(m_szInput); } else if((nChar >= _T('0')) &&(nChar <= _T('9'))) { // Display the character m_szInput += _T(nChar); MyDrawFunction(m_szInput); } else if(nChar == VK_SPACE) { // Display the character m_szInput += _T(' '); MyDrawFunction(m_szInput); } else if(nChar == VK_RETURN) { // Process the Enter key m_nLine++; } else if(nChar == VK_BACK) {
Trang 33
Vn quan tm
Tm hiu cch s dng cc MFC collection classes
1.4.2
Array collection
MFC cung cp mt s lp h tr vic s dng array thun tin hn nh: Tn lp Kiu d liu CArray Lp mng tng qut nht CByteArray 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 CCtrings CPtrArray Lp mng kiu con tr khng kiu -void pointers CObArray Lp mng kiu con tr i tng -CObject pointers
0 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<10; i++) array[i] = i + 1; // Remove the item at index 0. array.RemoveAt(0); TRACE(_T("Count = %d\n"), array.GetSize()); // 9 left. // Remove items 0, 1, and 2. array.RemoveAt(0, 3); TRACE(_T("Count = %d\n"), array.GetSize()); // 6 left. // Empty the array. array.RemoveAll(); TRACE(_T("Count = %d\n"), array.GetSize()); // 0 left.
V d 2:
CArray<CPoint, CPoint&> array;
Trang 34
V d 3:
class CProduct { public : CString m_szProductName; CString m_szCategoryName; }
....
CArrar <CProduct, CProduct&> arrayProductList ; CProduct oProduct ; oProduct.m_szProductName = product 1; oProduct.m_ szCategoryName = category 1; arrayProductList.Add(oProduct) ; oProduct.m_szProductName = product 2; oProduct.m_ szCategoryName = category 2; arrayProductList.Add(oProduct) ;
...
oProduct = arrayProductList.GetAt(0); AfxMessageBox(oProduct.m_szProductName);
0 Ch :
nh ngha mng kiu i tng cn phi c k hiu & trong thnh phn th hai trong nh ngha.
CArray <kiu_i_tng, kiu_i_tng&> array;
nh ngha mng kiu c s khng c k hiu & trong thnh phn th hai trong nh ngha.
CArray <kiu_c_s, kiu_c_s> array;
1.4.3
List collection
MFC cung cp cc lp h tr truy xut danh sch lin kt nh sau: Tn lp Kiu d liu CList Lp danh sch lin kt tng qut nht CObList Lp danh sch lin kt kiu con tr i tng -CObject pointers CPtrList Lp danh sch lin kt kiu con tr khng kiu-void pointers CStringList Lp danh sch lin kt kiu CString
Trang 35
V d 2:
CList <CPoint, CPoint&> list; // Populate the list. for(int i=0; i<10; i++) list.AddTail(CPoint(i*10, 0)); // Enumerate the items in the list. POSITION pos = list.GetHeadPosition(); While (pos != NULL) { CPoint point = list.GetNext(pos); TRACE(_T("x=%d, y=%d\n"), point.x, point.y); }
1.4.4
Map
Mt map, c xem nh mt dictionary, l mt bng gm nhiu phn t c xc nh bi kho. MFC cung cp tp cc lp h tr s dng map nh: Tn lp M t CMap Lp t in tng qut nht. CMapWordToPtr Lp t in kiu nh x WORD vi con tr CMapPtrToWord Lp t in kiu nh x con tr vi WORD CMapPtrToPtr Lp t in kiu nh x con tr vi con tr khc CMapWordToOb Lp t in kiu nh x WORD vi con tr i tng CMapStringToOb Lp t in kiu nh x CString vi con tr i tng CMapStringToPtr Lp t in kiu nh x CString vi con tr CMapStringToString Lp t in kiu nh x CString vi String
0 Ch :
Ngi dng phi khai bo #include Afxtempl.h khi s dng cc lp ny. V d:
CMapStringToString map; map[_T("Sunday")] = _T("Dimanche"); map[_T("Monday")] = _T("Lundi"); map[_T("Tuesday")] = _T("Mardi"); map[_T("Wednesday")] = _T("Mercredi"); map[_T("Thursday")] = _T("Jeudi"); map[_T("Friday")] = _T("Vendredi"); map[_T("Saturday")] = _T("Samedi"); POSITION pos = map.GetStartPosition(); while(pos != NULL) { CString strKey, strItem; map.GetNextAssoc(pos, strKey, strItem); TRACE(_T("Key=%s, Item=%s\n"), strKey, strItem); }
1.4.5
Tn lp CTypedPtrArray Trang 36
Lp trnh Windows vi VC/MFC CTypedPtrList CTypedPtrMap Lp qun l danh sch lin kt con tr Lp qun l t in con tr
Vn quan tm
Lp CFile v thao tc truy xut file Lp CArchive cc thao tc chui ho i tng lu tr.
1.5.2
Lp CFile
MFC cung cp lp CFile h tr cc thao tc truy xut file nh: to mi file, c/ghi file T chc tha k lp CFile v cc lp con nh sau:
Vic truy xut file lin quan n chn la chia s quyn truy cp nh: Kiu chia s M t CFile::shareDenyNone M mt file khng ngn cm vic loi tr CFile::shareDenyRead Cm chng trnh khc truy xut c CFile::shareDenyWrite Cm chng trnh khc truy xut ghi CFile::shareExclusive Cm chng trnh khc truy xut c ln ghi V chn la kiu truy xut nh: Kiu truy xut CFile::modeReadWrite CFile::modeRead CFile::modeWrite M t Yu cu truy xut c v ghi Yu cu truy xut ch c Yu cu truy xut ch ghi Trang 37
1.5.3
Chui ho v CArchive
D lp CFile kh hu ch trong qu trnh xy dng WinApp, nhng MFC cung cp lp CArchive nhm n gin ho vic truy xut vi vic dng ton t >> v << Chui ho l mt phn kh quan trng trong lp trnh MFC v n gip chuyn i cc i tng sang dng dng (stream) d liu thun li hn trong qu trnh lu tr/truy cp. Lp CArchive c s dng trong hm Serialize trn cc i tng d liu v ti liu trong ng dng. Trong hm Serialize, xc nh i tng cn lu tr hin ti ang c lu xung a hay ang c c ln t a, cn s dng hm thnh phn IsStoring() v IsLoading(). Trang 38
V d 3:
void CVd3bDoc::Serialize(CArchive& ar) { if(ar.IsStoring()) { // TODO: add storing code here ar << m_MyVar; } else { // TODO: add loading code here ar >> m_MyVar; } }
Hm Serialize c th c t trong bt c class no nhm x l thao tc lu/c cho i tng . x l cho trng hp ny cho class (gi s c tn CMyClass), cn thc thi theo trnh t sau: Cho lp CMyClass ny k tha lp CObject. Thm macro DECLARE_SERIAL trong phn khai bo ca lp 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 liu ca lp CMyClass Thm hm sinh (constructor) cho lp CMyClass nu n cha c. Thm macro IMPLEMENT_SERIAL trong phn thn ca lp 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;
Trang 39
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; else // Loading, not storing ar >> m_ptFrom >> m_ptTo; }
Bc 5a:
_AFX_INLINE CArchive& AFXAPI operator<<(CArchive& ar, const CObject* pOb) { ar.WriteObject(pOb); return ar; } Bc 5b: _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; }
c ln:
int nCount; ar >> nCount; CLine* pLines = new CLine[nCount]; for(int i=0; i<nCount; i++)
Trang 40
Trang 41
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 khin
MFC cung cp cc lp i din cho cc Windows control nh: Kiu iu khin WNDCLASS MFC Class Buttons "BUTTON" CButton List boxes "LISTBOX" CListBox Edit controls "EDIT" CEdit Combo boxes "COMBOBOX" CComboBox Scroll bars "SCROLLBAR" CScrollBar Static controls "STATIC" CStatic ng thi vi vic to cc iu khin ny thng qua thanh cng c trong ch Resource View, ngi dng cng 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;
Trang 42
0 Ch :
Nn s dng cc bin con tr i 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 cc hm thnh vin ::OnInitialUpdate() v hm khi to ::PreCreateWindow()
1.6.3
Loi CButton
M t To mt iu khin nt nhn To mt iu khin nt nhn v s dng trong hp thoi vi trng thi mc nh khi nhn phm Enter To mt iu khin check box To mt iu khin check box t ng chn v b chn khi c bm vo To mt iu khin check box 3 trng thi. To mt iu khin check box 3 trng thi t ng chn v b chn khi c bm vo To mt iu khin radio button To mt iu khin radion button t ng chn v b chn khi c bm vo To mt nhm cc iu khin M t t vn bn ca cc iu khin radio button hay check box nm bn tri ca iu khin Tng t nh BS_LEFTTEXT nhng v pha phi Canh l tri vn bn trong iu khin Canh l gia vn bn trong iu khin Canh l phi vn bn trong iu khin Canh l pha nh trn vn bn trong iu khin Canh l gia vn bn trong iu khin theo chiu dc Canh l pha di vn bn trong iu khin Xc nh ch nhiu dng
Kiu BS_PUSHBUTTON
BS_DEFPUSHBUTTON BS_CHECKBOX
BS_AUTOCHECKBOX BS_3STATE BS_AUTO3STATE BS_RADIOBUTTON BS_AUTORADIOBUTTON BS_GROUPBOX V cc kiu ring phn: Kiu BS_LEFTTEXT BS_RIGHTBUTTON BS_LEFT BS_CENTER BS_RIGHT BS_TOP BS_VCENTER BS_BOTTOM BS_MULTILINE
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 lin kt (to bi ClassWizard) Vic to ny theo trnh t sau y: Bc 1:
Trang 43
Bc 2:
Bc 3: C th cp nht ID ca hp thoi mi thm ny, v chn Create New Class to mt lp lin kt vi hp thoi va to.
Trang 44
Bc 5:
To bin i din cho hp thoi ny v gi hm DoModal() ca hp thoi kch hot hp thoi hin th ln.
1.7.3
Cc hp thoi thng dng nh FontDialog, ColorDialog, FileDialog c MFC cung cp cc class i din gip vic s dng d dng hn. MFC h tr cc lp i din cho cc hp thoi ny nh sau: Tn lp Kiu hp thoi CFileDialog Hp thoi m v 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:
Trang 45
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 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 chn la 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 Trang 46
S dng:
Nu mun nhng property sheet vo ca s chng trnh hin hnh th cp nhp bi cc lnh
Trang 47
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "PropDemo.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW
Trang 48
Trang 49
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 window class 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)
Trang 50
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);
Trang 51
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_
Trang 52
#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"
Trang 53
#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
Trang 54
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
Trang 55
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)
Trang 56
// 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 // Implementation protected: // 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;
Trang 57
Mn hnh kt qu nh sau:
Header Hotkey Image list IP address** List view Month calendar* Progress Property sheet Rebar* Rich edit Slider Spin button Status bar Tab Toolbar ToolTip Tree view
"SysHeader32" "msctls_hotkey32" N/A "SysIPAddress32" "SysListView32" "SysMonthCal32" "msctls_progress32" N/A "ReBarWindow32" "RichEdit20A" (ANSI) or "RichEdit20W" (Unicode) "msctls_trackbar32" "msctls_updown32" "msctls_statusbar32" "SysTabControl32" "ToolbarWindow32" "tooltips_class32" "SysTreeView32"
WC_HEADER HOTKEY_CLASS N/A WC_IPADDRESS WC_LISTVIEW MONTHCAL_CLASS PROGRESS_CLASS N/A REBARCLASSNAME RICHEDIT_CLASS TRACKBAR_CLASS UPDOWN_CLASS STATUSCLASSNAME WC_TABCONTROL TOOLBARCLASSNAME TOOLTIPS_CLASS WC_TREEVIEW
CHeaderCtrl CHotKeyCtrl CImageList CIPAddressCtrl CListCtrl CMonthCalCtrl CProgressCtrl CPropertySheet CReBarCtrl CRichEditCtrl CSliderCtrl CSpinButtonCtrl CStatusBarCtrl CTabCtrl CToolBarCtrl CToolTipCtrl CTreeCtrl
1.8.2
V d tng hp:
Trang 59
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() { }
Trang 60
Trang 61
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
Trang 62
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. //
Trang 63
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
Trang 64
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;
Trang 65
Mn hnh kt qu nh sau:
Trang 66
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)
Trang 67
Trang 68
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 // /////////////////////////////////////////////////////////////////////////// // CPathComboBox window class CPathComboBox : public CComboBoxEx { // Construction public: CPathComboBox(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPathComboBox) //}}AFX_VIRTUAL // Implementation public: CString GetPath(); BOOL SetPath (LPCTSTR pszPath); virtual ~CPathComboBox(); // Generated message map functions protected: void GetSubstring (int& nStart, CString& string, CString& result); int m_nIndexEnd; int m_nIndexStart; BOOL m_bFirstCall; CImageList m_il; //{{AFX_MSG(CPathComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations
Trang 69
PathComboBox.cpp
// PathComboBox.cpp : implementation file // #include "stdafx.h" #include "PathList.h" #include "PathComboBox.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CPathComboBox CPathComboBox::CPathComboBox() { m_bFirstCall = TRUE; m_nIndexStart = -1; m_nIndexEnd = -1; } CPathComboBox::~CPathComboBox() { } BEGIN_MESSAGE_MAP(CPathComboBox, CComboBoxEx) //{{AFX_MSG_MAP(CPathComboBox) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CPathComboBox message handlers BOOL CPathComboBox::SetPath(LPCTSTR pszPath) { if (m_bFirstCall) { m_bFirstCall = FALSE; // // Add an image list containing drive and folder images. // m_il.Create (IDB_IMAGES, 16, 1, RGB (255, 0, 255)); SetImageList (&m_il); // // Add icons representing the drives on the host system. // int nPos = 0; int nCount = 0; CString string = _T ("?:\\"); DWORD dwDriveList = ::GetLogicalDrives (); while (dwDriveList) { if (dwDriveList & 1) { string.SetAt (0, _T (`A') + nPos); CString strDrive = string.Left (2);
Trang 70
Trang 71
Trang 72
Mn hnh kt qu nh sau:
Trang 73
Vn quan tm
Hiu v cc class thnh phn trong 1 project. Bit v s dng ng chc nng ca cc class v View, Document.
2.1.2
Gii thiu
Kt cu ca ng dng dng SDI v MDI c hp thnh bi thnh phn CView v CDocument, chnh l cu trc Document/View. Khung ng dng dng SDI nh sau:
Trong qu trnh to ng dng dng SDI v MDI, cc class c to ra hu ht c k tha (dn xut) t cc class nh: Vi dng SDI, cc class ny l CWinApp, CFrameWnd, CDocument, CView Vi dng MDI, cc class ny l: CWinApp, CMDIFrameWnd, CMDIChildWnd, CDocument, CView Vai tr ca mi class c m t nh sau: Lp Vai tr CWinApp To tt c thnh phn khc trong ng dng. y l lp nhn thng bo s kin v truyn ti lp CView v CDocument CFrameWnd - To v qun l khung ca s, cha menu, toolbar, scrollbar v cc i tng nhn thy c gn vo ca s. Trang 74
Lp trnh Windows vi VC/MFC - Xc nh s ti liu nhn thy c trong mt thi im bt k - (th hin bi CMainFrame trong project) l khung chnh ca ng dng - Cung cp khng gian bao bc trn mn hnh nn din ra ton b tng tc ng dng. - Ca s ny l khung c gn menu v thanh cng c - (th hin bi CChildFrame trong project) l khung cha lp CView - L lp truyn thng ip (message) v s kin (event) ti cc lp hin th x l hay hin th. - Cha ti liu ca ng dng. y l ni s lu tr cu trc d liu cn thit cha v thao tc d liu to nn ti liu. - Lp ny nhn d liu t lp CView v truyn thng tin sang lp CView. - Lu gi v ly d liu v ti liu t cc file - Qun l phn hin th phn trnh by nhn thy ca ti liu cho ngi dng xem. - Truyn thng tin vo lp CDocument v nhn thng tin t lp CDocument.
CMDIFrameWnd
CMDIChildFrameWnd CDocument
CView
Vic tng tc v trao i thng tin gia CView v CDocument c th hin nh sau:
hay:
c bit, lp CView cung cp mt s dng giao din ho thng qua cc lp con nh: CEditView: cung cp giao din dng editor son tho CFormView: cung cp giao din dng form gn thm cc iu khin CHtmlView: cung cp giao din dng trnh duyt web CListView: cung cp giao din dng danh sch CRichEditView: cung cp giao din dng editor son tho c nhiu h tr CScrollView: cung cp giao din c thanh cun CTreeView: cung cp giao din dng cy
2.1.3
Cu trc Document/View
2.1.4
Vi c 2 dng SDI v MDI, s lin kt th hin thng qua 1 bin pointer kiu CDocument (bin ny thng c tn l pDoc). Thng qua bin ny, chng ta c th iu khin thao tc chuyn thng tin (t lp CView sang CDocument) hay ly thng tin v (t lp CDocument sang lp CView). Thng thng, vi c ng dng dng SDI hay MDI th trong lp CView lun c hm GetDocument nhm h tr vic ly bin con tr ny. V d 1:
CVd5bDoc* CVd5bView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CVd5bDoc))); return(CVd5bDoc*)m_pDocument; }
Vn quan tm
Hiu v vai tr ca cc lp con ca CView.
Trang 76
2.2.2
Gii thiu
MFC cung cp lp CView v cc lp con h tr vn xy dng giao din nh: Tn lp M t CView Lp c s CCtrlView Dng lm lp c s cho cc dng view khc CEditView Cung cp giao din dng editor CRichEditView Cung cp giao din dng editor c nhiu h tr CListView Cung cp giao din dng danh sch CTreeView Cung cp giao din dng cy CHtmlView Cung cp giao din dng trnh duyt web CScrollView Cung cp giao din c thanh cun CFormView Cung cp giao din dng form gn cc iu khin CRecordView Cung cp giao din c tng tc iu khin d liu CDaoRecordView Cung cp giao din c tng tc iu khin d liu (dng DAO) COleDBRecordView Cung cp giao din c tng tc iu khin d liu (dng OLE) c th s dng cc lp ny trong vic th hin giao din ca ng dng, chng ta s chn chng l lp c s trong bc 6 ca qu trnh to project.
2.2.3
Lp CScrollView v ng dng
CScrollView c s dng trong trng hp cn c giao din h tr scrollbar. xc nh kch thc ca vng kch thc lun l ca ca s, s dng hm o (virtual function) OnInitialUpdate v hm SetScrollSizes. V d 1:
void CMyView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); SetScrollSizes(MM_TEXT, CSize(1280, 1024)); }
hay
void CMyView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); SetScrollSizes(MM_LOENGLISH, CSize(850, 1100)); }
Ngoi ra, c th nhn bit c v tr ca scrollbar hin hnh hay n nh v tr ca scrollbar bi hm GetScrollPosition() v ScrollToPosition() Trang 77
SetScaleToFitSize(GetTotalSize()); // thay i t l & kch thc SetScrollSizes(); // khi phc kch thc ca s
chuyn i t dng CView sang dng CScrollView, cn thc thi theo 2 bc sau: Tm trong file .h v .cpp v thay th CView bi CScrollView Trong hm OnInitialUpdate gi SetScrollSize xc nh kch thc ca s. V d tng hp: ScrollDemoView.h
// ScrollDemoView.h : interface of the CScrollDemoView class // ////////////////////////////////////////////////////////////////////////// #if !defined(AFX_SCROLLDEMOVIEW_H__DCCF4E0D_9735_11D2_8E53_006008A82731__INCLUDED_) #define AFX_SCROLLDEMOVIEW_H__DCCF4E0D_9735_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CScrollDemoView : public CScrollView { protected: // create from serialization only CScrollDemoView(); DECLARE_DYNCREATE(CScrollDemoView) // Attributes public: CScrollDemoDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CScrollDemoView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // called first time after construct //}}AFX_VIRTUAL // Implementation public: virtual ~CScrollDemoView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected:
Trang 78
ScrollDemoView.cpp
// ScrollDemoView.cpp : implementation of the CScrollDemoView class // #include "stdafx.h" #include "ScrollDemo.h" #include "ScrollDemoDoc.h" #include "ScrollDemoView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CScrollDemoView IMPLEMENT_DYNCREATE(CScrollDemoView, CScrollView) BEGIN_MESSAGE_MAP(CScrollDemoView, CScrollView) //{{AFX_MSG_MAP(CScrollDemoView) ON_WM_LBUTTONDOWN() //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CScrollDemoView construction/destruction CScrollDemoView::CScrollDemoView() { m_font.CreatePointFont (80, _T ("MS Sans Serif")); } CScrollDemoView::~CScrollDemoView()
Trang 79
pDC->SetBkMode (TRANSPARENT); // // Add numbers and button outlines to the row headers. // for (i=0; i<99; i++) { int y = (i * m_nCellHeight) + m_nCellHeight; pDC->MoveTo (0, y); pDC->LineTo (m_nRibbonWidth, y);
Trang 80
Trang 81
Trang 82
2.2.4
Lp CHtmlView v ng dng
CHtmlView c s dng trong trng hp cn c giao din h tr hin th trang web. CHtmlView c xy dng t mt s hm tng tc vi WebBrower control Hm M t GetBusy Tr v trng thi chng trnh c download no ang hot ng khng GetLocationName Tr v ta nu l trang web; tr v tn file/th mc nu l ng dn vt l GetLocationURL Tr v a ch URL dng http://.... hay file://... GoBack Quay v trang trc GoForward i ti trang k Navigate Hin th ni dung ca a ch URL xc nh Refresh Ti v hin th li ni dung ca a ch URL hin hnh Stop Ngng vic ti d liu V d 1:
// In CMyView's message map ON_COMMAND(ID_BACK, OnBack) ON_COMMAND(ID_FORWARD, OnForward) ON_COMMAND(ID_REFRESH, OnRefresh) ON_COMMAND(ID_STOP, OnStop) void CMyView::OnBack() {
Trang 83
v:
Navigate(_T("http://www.microsoft.com")); Navigate(_T("file://c:/my documents/budget.xls"));
Hm OnNavigateComplete2 OnBeforeNavigate2 OnProgressChange OnDownloadBegin OnDownloadComplete OnTitleChange OnDocumentComplete V d tng hp: HtmlClockView.h
M t c gi sau khi truy xut mt file c gi sau khi truy xut mt file c gi khi cung cp trng thi ca qu trnh ti d liu c gi khi qu trnh ti d liu bt u c gi khi qu trnh ti d liu hon tt c gi khi ta thay i c gi khi ti liu c ti hon tt
// HtmlClockView.h : interface of the CHtmlClockView class // /////////////////////////////////////////////////////////////////////////// #if !defined( // AFX_HTMLCLOCKVIEW_H__D39825ED_99C0_11D2_8E53_006008A82731__INCLUDED_) #define AFX_HTMLCLOCKVIEW_H__D39825ED_99C0_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CHtmlClockView : public CHtmlView { protected: // create from serialization only CHtmlClockView(); DECLARE_DYNCREATE(CHtmlClockView) // Attributes public: CHtmlClockDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CHtmlClockView) public:
Trang 84
HtmlClockView.cpp
// HtmlClockView.cpp : implementation of the CHtmlClockView class // #include "stdafx.h" #include "HtmlClock.h" #include "HtmlClockDoc.h" #include "HtmlClockView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CHtmlClockView IMPLEMENT_DYNCREATE(CHtmlClockView, CHtmlView) BEGIN_MESSAGE_MAP(CHtmlClockView, CHtmlView) //{{AFX_MSG_MAP(CHtmlClockView)
Trang 85
Trang 86
Mn hnh kt qu nh sau:
2.2.5
Lp CTreeView v ng dng
CTreeView c s dng trong trng hp cn c giao din h tr hin th cy. CTreeView c xy dng lin quan n TreeView control iu khin c cy trong giao din chng trnh, chng ta s dng hm GetTreeCtrl ly quyn iu khin/truy xut cy. V d 1:
UINT nCount = GetTreeCtrl().GetCount(); // ly s nt trn cy
to cy, c th dng cc kiu sau: Kiu TVS_HASLINES TVS_LINESATROOT TVS_HASBUTTONS TVS_EDITLABELS TVS_DISABLEDRAGDROP TVS_SHOWSELALWAYS
M t Adds lines connecting subitems to their parents. Adds lines connecting items at the top level, or root, of the hierarchy. This style is valid only if TVS_HASLINES is also specified. Adds buttons containing plus or minus signs to items that have subitems. Clicking a button expands or collapses the associated subtree. Enables in-place label editing notifications. Disables drag-and-drop notifications. Specifies that the item that's currently selected should always be highlighted. By default, the highlight is removed when the control loses the input focus.
Trang 87
Trang 88
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "DriveTree.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; cs.style &= ~FWS_ADDTOTITLE; return TRUE; } ////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG //////////////////////////////////////////////////////////////////////
Trang 89
DriveView.h
// DriveTreeView.h : interface of the CDriveView class // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_DRIVETREEVIEW_H__090B382D_959D_11D2_8E53_006008A82731__INCLUDED_) #define AFX_DRIVETREEVIEW_H__090B382D_959D_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CDriveView : public CTreeView { protected: // create from serialization only CDriveView(); DECLARE_DYNCREATE(CDriveView) // Attributes public: CDriveTreeDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDriveView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // called first time after construct //}}AFX_VIRTUAL // Implementation public: virtual ~CDriveView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: BOOL AddDriveItem (LPCTSTR pszDrive); int AddDirectories (HTREEITEM hItem, LPCTSTR pszPath); void DeleteAllChildren (HTREEITEM hItem); void DeleteFirstChild (HTREEITEM hItem); CString GetPathFromItem (HTREEITEM hItem); BOOL SetButtonState (HTREEITEM hItem, LPCTSTR pszPath); int AddDrives (); CImageList m_ilDrives; //{{AFX_MSG(CDriveView) afx_msg void OnItemExpanding(NMHDR* pNMHDR, LRESULT* pResult);
Trang 90
DriveView.cpp
// DriveTreeView.cpp : implementation of the CDriveView class // #include "stdafx.h" #include "DriveTree.h" #include "DriveTreeDoc.h" #include "DriveView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Image indexes #define ILI_HARD_DISK 0 #define ILI_FLOPPY 1 #define ILI_CD_ROM 2 #define ILI_NET_DRIVE 3 #define ILI_CLOSED_FOLDER 4 #define ILI_OPEN_FOLDER 5 ////////////////////////////////////////////////////////////////////// // CDriveView IMPLEMENT_DYNCREATE(CDriveView, CTreeView) BEGIN_MESSAGE_MAP(CDriveView, CTreeView) //{{AFX_MSG_MAP(CDriveView) ON_NOTIFY_REFLECT(TVN_ITEMEXPANDING, OnItemExpanding) //}}AFX_MSG_MAP END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////// // CDriveView construction/destruction CDriveView::CDriveView() { } CDriveView::~CDriveView() { } BOOL CDriveView::PreCreateWindow(CREATESTRUCT& cs) { if (!CTreeView::PreCreateWindow (cs))
Trang 91
Trang 92
Trang 93
case DRIVE_CDROM: hItem = GetTreeCtrl ().InsertItem (pszDrive, ILI_CD_ROM, ILI_CD_ROM); GetTreeCtrl ().InsertItem (_T (""), ILI_CLOSED_FOLDER, ILI_CLOSED_FOLDER, hItem); break; default: return FALSE; } return TRUE; } BOOL CDriveView::SetButtonState(HTREEITEM hItem, LPCTSTR pszPath) { HANDLE hFind; WIN32_FIND_DATA fd; BOOL bResult = FALSE; CString strPath = pszPath; if (strPath.Right (1) != _T ("\\")) strPath += _T ("\\"); strPath += _T ("*.*"); if ((hFind = ::FindFirstFile (strPath, &fd)) == INVALID_HANDLE_VALUE) return bResult; do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { CString strComp = (LPCTSTR) &fd.cFileName; if ((strComp != _T (".")) && (strComp != _T (".."))) { GetTreeCtrl ().InsertItem (_T (""), ILI_CLOSED_FOLDER, ILI_CLOSED_FOLDER, hItem); bResult = TRUE; break; } } } while (::FindNextFile (hFind, &fd)); ::FindClose (hFind); return bResult; } void CDriveView::OnItemExpanding(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; HTREEITEM hItem = pNMTreeView->itemNew.hItem; CString string = GetPathFromItem (hItem); *pResult = FALSE; if (pNMTreeView->action == TVE_EXPAND) { DeleteFirstChild (hItem); if (AddDirectories (hItem, string) == 0) *pResult = TRUE; }
Trang 94
Trang 95
Mn hnh kt qu nh sau:
2.2.6
Lp CListView v ng dng
Tng t cc dng view nu trn, CListView gip to giao din dng list Vic iu khin, tng tc vi danh sch (list) c thc hin thng qua vic gi hm GetListCtrl nhm ly quyn iu khin Cc dng list c chn la theo cc ty chn sau: Kiu M t LVS_ICON Selects large icon mode. LVS_SMALLICON Selects small icon mode. LVS_LIST Selects list mode. LVS_REPORT Selects report mode. LVS_NOCOLUMNHEADER Removes the header control that's normally displayed in report mode. LVS_NOSORTHEADER Disables the LVN_COLUMNCLICK notifications that are sent by default when a column header is clicked in report mode. LVS_ALIGNLEFT Aligns items along the left border in large and small icon mode. Trang 96
Lp trnh Windows vi VC/MFC LVS_ALIGNTOP LVS_AUTOARRANGE LVS_EDITLABELS LVS_NOLABELWRAP LVS_NOSCROLL LVS_OWNERDRAWFIXED LVS_SHAREIMAGELISTS LVS_SINGLESEL LVS_SHOWSELALWAYS LVS_SORTASCENDING LVS_SORTDESCENDING Aligns items along the top border in large and small icon mode. Automatically arranges items in rows and columns in large and small icon mode. Enables in-place label editing notifications. Restricts labels to single lines in large icon mode. Disables scrolling. Scrolling is enabled by default. Specifies that the control's owner will draw the items in response to WM_DRAWITEM messages. Prevents a list view from automatically deleting the image lists associated with it when the view itself is deleted. Disables multiple-selection support. Specifies that the selected items should always be highlighted. By default, the highlight is removed when the view loses the input focus. Specifies that items should be sorted in ascending order(for example, A through Z). Specifies that items should be sorted in descending order(for example, Z through A).
Vic khi to cho 1 list gm 5 bc sau y: To 1 cp hnh bitmap bao gm 1 hnh cho ch xem ln, v 1 hnh cho cc ch xem cn li. S dng SetImageList lin kt danh sch hnh vi list view control Dng InsertColumn() thm cc ct cho list (tng ng vi ch xem chi tit) Thm cc phn t vi lnh InsertItem() Gn ta cho nt con vi SetItemText() V d tng hp: MainFrm.h
// MainFrm.h : interface of the CMainFrame class // /////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINFRM_H__18BD7B7C_95C6_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MAINFRM_H__18BD7B7C_95C6_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMainFrame : public CFrameWnd { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CMainFrame();
Trang 97
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "WinDir.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; cs.style &= ~FWS_ADDTOTITLE; return TRUE;
Trang 98
FileView.h
// FileView.h : interface of the CFileView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_FILEVIEW_H__18BD7B80_95C6_11D2_8E53_006008A82731__INCLUDED_) #define AFX_FILEVIEW_H__18BD7B80_95C6_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 typedef struct tagITEMINFO { CString strFileName; DWORD nFileSizeLow; FILETIME ftLastWriteTime; } ITEMINFO; class CFileView : public CListView { protected: // create from serialization only CFileView(); DECLARE_DYNCREATE(CFileView) // Attributes public: CWinDirDoc* GetDocument(); // Operations public: static int CALLBACK CompareFunc (LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFileView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // called first time after construct
Trang 99
FileView.cpp
// FileView.cpp : implementation of the CFileView class // #include "stdafx.h" #include "WinDir.h" #include "PathDialog.h" #include "WinDirDoc.h" #include "FileView.h"
Trang 100
#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CFileView IMPLEMENT_DYNCREATE(CFileView, CListView) BEGIN_MESSAGE_MAP(CFileView, CListView) //{{AFX_MSG_MAP(CFileView) ON_WM_DESTROY() ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDispInfo) ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick) ON_COMMAND(ID_VIEW_LARGE_ICONS, OnViewLargeIcons) ON_COMMAND(ID_VIEW_SMALL_ICONS, OnViewSmallIcons) ON_COMMAND(ID_VIEW_LIST, OnViewList) ON_COMMAND(ID_VIEW_DETAILS, OnViewDetails) ON_UPDATE_COMMAND_UI(ID_VIEW_LARGE_ICONS, OnUpdateViewLargeIcons) ON_UPDATE_COMMAND_UI(ID_VIEW_SMALL_ICONS, OnUpdateViewSmallIcons) ON_UPDATE_COMMAND_UI(ID_VIEW_LIST, OnUpdateViewList) ON_UPDATE_COMMAND_UI(ID_VIEW_DETAILS, OnUpdateViewDetails) ON_COMMAND(ID_FILE_NEW_DIR, OnFileNewDirectory) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CFileView construction/destruction CFileView::CFileView() { } CFileView::~CFileView() { } BOOL CFileView::PreCreateWindow(CREATESTRUCT& cs) { if (!CListView::PreCreateWindow (cs)) return FALSE; cs.style &= ~LVS_TYPEMASK; cs.style = LVS_REPORT; return TRUE; } /////////////////////////////////////////////////////////////////////////// // CFileView drawing void CFileView::OnDraw(CDC* pDC) { CWinDirDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here } void CFileView::OnInitialUpdate() { CListView::OnInitialUpdate(); //
Trang 101
Trang 102
Trang 103
if (GetListCtrl ().InsertItem (&lvi) == -1) return FALSE; return TRUE; } void CFileView::FreeItemMemory() { int nCount = GetListCtrl ().GetItemCount (); if (nCount) { for (int i=0; i<nCount; i++) delete (ITEMINFO*) GetListCtrl ().GetItemData (i); } } void CFileView::OnDestroy() { FreeItemMemory (); CListView::OnDestroy (); } void CFileView::OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult) { CString string; LV_DISPINFO* pDispInfo = (LV_DISPINFO*) pNMHDR; if (pDispInfo->item.mask & LVIF_TEXT) { ITEMINFO* pItem = (ITEMINFO*) pDispInfo->item.lParam; switch (pDispInfo->item.iSubItem) { case 0: // File name. ::lstrcpy (pDispInfo->item.pszText, pItem->strFileName); break; case 1: // File size. string.Format (_T ("%u"), pItem->nFileSizeLow); ::lstrcpy (pDispInfo->item.pszText, string); break; case 2: // Date and time. CTime time (pItem->ftLastWriteTime); BOOL pm = FALSE; int nHour = time.GetHour (); if (nHour == 0) nHour = 12; else if (nHour == 12) pm = TRUE; else if (nHour > 12) { nHour -= 12; pm = TRUE; } string.Format (_T ("%d/%0.2d/%0.2d (%d:%0.2d%c)"), time.GetMonth (), time.GetDay (), time.GetYear () % 100, nHour, time.GetMinute (), pm ? _T (`p') : _T (`a')); ::lstrcpy (pDispInfo->item.pszText, string); break; } } *pResult = 0;
Trang 104
Trang 105
Mn hnh kt qu nh sau:
Vn quan tm
Hiu v cu trc ca dng MDI Hiu v vai tr ca cc lp trong cu trc MDI.
2.3.2
Trong ng dng MDI, 1 document c th c th hin trong nhiu view (windows), c th ng b cc view ny cn s dng phng thc UpdateAllViews (trong lp CDocument) V d 1:
void UpdateAllViews(CView* pSender, LPARAM lHint = 0L, CObject* pHint = NULL)
Hay
UpdateAllViews(NULL);
Khi gi hm ny, chng trnh s gi hm OnUpdate ca tt c cc view hin hnh v thc hin thao tc cp nht tng ng. V d 2:
// Thc hin trong lp CDocument UpdateAllViews(NULL, 1, pLine); // In the view class void CMyView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) {
Trang 106
Trang 107
CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate( IDR_MDISQUTYPE, RUNTIME_CLASS(CSquaresDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CSquaresView)); AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) return FALSE;
Trang 108
Trang 109
MainFrm.h
// MainFrm.h : interface of the CMainFrame class // /////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MAINFRM_H__36D513DF_9CA0_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MAINFRM_H__36D513DF_9CA0_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMainFrame : public CMDIFrameWnd DECLARE_DYNAMIC(CMainFrame) public: CMainFrame(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(CMainFrame) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG DECLARE_MESSAGE_MAP()
Trang 110
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "MdiSquares.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CMDIFrameWnd::PreCreateWindow(cs) ) return FALSE; return TRUE; } /////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWnd::Dump(dc); }
Trang 111
ChildFrm.h
// ChildFrm.h : interface of the CChildFrame class // /////////////////////////////////////////////////////////////////////////// #if !defined(AFX_CHILDFRM_H__36D513E1_9CA0_11D2_8E53_006008A82731__INCLUDED_) #define AFX_CHILDFRM_H__36D513E1_9CA0_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CChildFrame : public CMDIChildWnd { DECLARE_DYNCREATE(CChildFrame) public: CChildFrame(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CChildFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(CChildFrame) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately // before the previous line. #endif // !defined( // AFX_CHILDFRM_H__36D513E1_9CA0_11D2_8E53_006008A82731__INCLUDED_)
Trang 112
SquaresDoc.h
// SquaresDoc.h : interface of the CSquaresDoc class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_SQUARESDOC_H__36D513E3_9CA0_11D2_8E53_006008A82731__INCLUDED_)
Trang 113
Trang 114
SquaresDoc.cpp
// SquaresDoc.cpp : implementation of the CSquaresDoc class // #include "stdafx.h" #include "MdiSquares.h" #include "SquaresDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CSquaresDoc IMPLEMENT_DYNCREATE(CSquaresDoc, CDocument) BEGIN_MESSAGE_MAP(CSquaresDoc, CDocument) //{{AFX_MSG_MAP(CSquaresDoc) ON_COMMAND(ID_COLOR_RED, OnColorRed) ON_COMMAND(ID_COLOR_YELLOW, OnColorYellow) ON_COMMAND(ID_COLOR_GREEN, OnColorGreen) ON_COMMAND(ID_COLOR_CYAN, OnColorCyan) ON_COMMAND(ID_COLOR_BLUE, OnColorBlue) ON_COMMAND(ID_COLOR_WHITE, OnColorWhite) ON_UPDATE_COMMAND_UI(ID_COLOR_RED, OnUpdateColorRed) ON_UPDATE_COMMAND_UI(ID_COLOR_YELLOW, OnUpdateColorYellow) ON_UPDATE_COMMAND_UI(ID_COLOR_GREEN, OnUpdateColorGreen) ON_UPDATE_COMMAND_UI(ID_COLOR_CYAN, OnUpdateColorCyan) ON_UPDATE_COMMAND_UI(ID_COLOR_BLUE, OnUpdateColorBlue) ON_UPDATE_COMMAND_UI(ID_COLOR_WHITE, OnUpdateColorWhite) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CSquaresDoc construction/destruction CSquaresDoc::CSquaresDoc() { } CSquaresDoc::~CSquaresDoc() { } BOOL CSquaresDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE;
Trang 115
for (int i=0; i<4; i++) for (int j=0; j<4; j++) m_clrGrid[i][j] = RGB (255, 255, 255); m_clrCurrentColor = RGB (255, 0, 0); return TRUE; } /////////////////////////////////////////////////////////////////////////// // CSquaresDoc serialization void CSquaresDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { for (int i=0; i<4; i++) for (int j=0; j<4; j++) ar << m_clrGrid[i][j]; ar << m_clrCurrentColor; } else { for (int i=0; i<4; i++) for (int j=0; j<4; j++) ar >> m_clrGrid[i][j]; ar >> m_clrCurrentColor; } } /////////////////////////////////////////////////////////////////////////// // CSquaresDoc diagnostics #ifdef _DEBUG void CSquaresDoc::AssertValid() const { CDocument::AssertValid(); } void CSquaresDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG /////////////////////////////////////////////////////////////////////////// // CSquaresDoc commands COLORREF CSquaresDoc::GetCurrentColor() { return m_clrCurrentColor; } COLORREF CSquaresDoc::GetSquare(int i, int j) { ASSERT (i >= 0 && i <= 3 && j >= 0 && j <= 3); return m_clrGrid[i][j]; } void CSquaresDoc::SetSquare(int i, int j, COLORREF color) { ASSERT (i >= 0 && i <= 3 && j >= 0 && j <= 3); m_clrGrid[i][j] = color;
Trang 116
SquaresView.h
// SquaresView.h : interface of the CSquaresView class //
Trang 117
Trang 118
SquaresView.cpp
// SquaresView.cpp : implementation of the CSquaresView class // #include "stdafx.h" #include "MdiSquares.h" #include "SquaresDoc.h" #include "SquaresView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CSquaresView IMPLEMENT_DYNCREATE(CSquaresView, CView) BEGIN_MESSAGE_MAP(CSquaresView, CView) //{{AFX_MSG_MAP(CSquaresView) ON_WM_LBUTTONDOWN() //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CSquaresView construction/destruction CSquaresView::CSquaresView() { } CSquaresView::~CSquaresView() { } BOOL CSquaresView::PreCreateWindow(CREATESTRUCT& cs) { return CView::PreCreateWindow(cs); } /////////////////////////////////////////////////////////////////////////// // CSquaresView drawing void CSquaresView::OnDraw(CDC* pDC) { CSquaresDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // // Set the mapping mode to MM_LOENGLISH. // pDC->SetMapMode (MM_LOENGLISH); // // Draw the 16 squares. // for (int i=0; i<4; i++) { for (int j=0; j<4; j++) { COLORREF color = pDoc->GetSquare (i, j); CBrush brush (color); int x1 = (j * 70) + 35; int y1 = (i * -70) - 35;
Trang 119
Trang 120
Mn hnh kt qu nh sau:
2.3.3
Dng splitter
phn chia ca s thnh cc vng ring bit, cn thc hin vic phn chia ca s, thao tc nh sau: 2.3.3.1 To vng phn chia ng: Thm bin thnh vin (thuc class CSplitterWnd) vo class CMainFrame ca s khung chng trnh. Khai bo li hm OnCreateClient v gi hm CSplitterWnd::Create to khung ca s phn chia c trong ca s khung. V d:
class CMainFrame : public CFrameWnd { protected: CSplitterWnd m_wndSplitter; };
v
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { return m_wndSplitter.Create(this, 2, 1, CSize(8, 8), pContext); }
2.3.3.2 To vng phn chia tnh: Thm bin thnh vin (thuc class CSplitterWnd) vo class CMainFrame ca s khung chng trnh. Khai bo li hm OnCreateClient v gi hm CSplitterWnd::CreateStatic to khung ca s phn chia c trong ca s khung Dng CSplitterWnd::CreateView to cc view cho mi thnh phn. V d:
class CMainFrame : public CFrameWnd { protected: CSplitterWnd m_wndSplitter; };
v
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { if(!m_wndSplitter.CreateStatic(this, 1, 2)
Trang 121
2.3.4
V d tng hp
Trang 122
Sketch.cpp
// Sketch.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "Line.h" #include "Sketch.h" #include "MainFrm.h" #include "SketchDoc.h" #include "SketchView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CSketchApp BEGIN_MESSAGE_MAP(CSketchApp, CWinApp) //{{AFX_MSG_MAP(CSketchApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CSketchApp construction CSketchApp::CSketchApp() { } /////////////////////////////////////////////////////////////////////////// // The one and only CSketchApp object CSketchApp theApp; /////////////////////////////////////////////////////////////////////////// // CSketchApp initialization BOOL CSketchApp::InitInstance() { SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file // options (including MRU)
CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CSketchDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CSketchView)); AddDocTemplate(pDocTemplate); // Enable DDE Execute open EnableShellOpen();
Trang 123
Trang 124
MainFrm.h
// MainFrm.h : interface of the CMainFrame class // /////////////////////////////////////////////////////////////////////////// // #if !defined(AFX_MAINFRM_H__1260AFC9_9CAC_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MAINFRM_H__1260AFC9_9CAC_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMainFrame : public CFrameWnd { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions
Trang 125
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "Sketch.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { } CMainFrame::~CMainFrame() { } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; return TRUE; } /////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const
Trang 126
SketchDoc.h
// SketchDoc.h : interface of the CSketchDoc class // /////////////////////////////////////////////////////////////////////////// #if !defined(AFX_SKETCHDOC_H__1260AFCB_9CAC_11D2_8E53_006008A82731__INCLUDED_) #define AFX_SKETCHDOC_H__1260AFCB_9CAC_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 typedef CTypedPtrArray<CObArray, CLine*> CLineArray; class CSketchDoc : public CDocument { protected: // create from serialization only CSketchDoc(); DECLARE_DYNCREATE(CSketchDoc) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSketchDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); virtual void DeleteContents(); //}}AFX_VIRTUAL // Implementation public: CLine* GetLine (int nIndex); int GetLineCount (); CLine* AddLine (POINT from, POINT to); BOOL IsGridVisible (); virtual ~CSketchDoc(); #ifdef _DEBUG virtual void AssertValid() const;
Trang 127
SketchDoc.cpp
// SketchDoc.cpp : implementation of the CSketchDoc class // #include "stdafx.h" #include "Line.h" #include "Sketch.h" #include "SketchDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CSketchDoc IMPLEMENT_DYNCREATE(CSketchDoc, CDocument) BEGIN_MESSAGE_MAP(CSketchDoc, CDocument) //{{AFX_MSG_MAP(CSketchDoc) ON_COMMAND(ID_VIEW_GRID, OnViewGrid) ON_UPDATE_COMMAND_UI(ID_VIEW_GRID, OnUpdateViewGrid) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CSketchDoc construction/destruction CSketchDoc::CSketchDoc() { } CSketchDoc::~CSketchDoc() { } BOOL CSketchDoc::OnNewDocument()
Trang 128
Trang 129
SketchView.h
// SketchView.h : interface of the CSketchView class // /////////////////////////////////////////////////////////////////////////// // #if !defined(AFX_SKETCHVIEW_H__1260AFCD_9CAC_11D2_8E53_006008A82731__INCLUDED_) #define AFX_SKETCHVIEW_H__1260AFCD_9CAC_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CSketchView : public CScrollView { protected: // create from serialization only CSketchView(); DECLARE_DYNCREATE(CSketchView)
Trang 130
Trang 131
Trang 132
Trang 133
Trang 134
Mn hnh kt qu nh sau:
Trang 135
Wanderer.cpp
// Wanderer.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "Wanderer.h" #include "MainFrm.h" #include "WandererDoc.h" #include "DriveView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CWandererApp BEGIN_MESSAGE_MAP(CWandererApp, CWinApp) //{{AFX_MSG_MAP(CWandererApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CWandererApp construction CWandererApp::CWandererApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } /////////////////////////////////////////////////////////////////////////// // The one and only CWandererApp object CWandererApp theApp; ///////////////////////////////////////////////////////////////////////////
Trang 136
Trang 137
// Implementation protected: //{{AFX_MSG(CAboutDlg) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CWandererApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } /////////////////////////////////////////////////////////////////////////// // CWandererApp message handlers
MainFrm.h
// MainFrm.h : interface of the CMainFrame class // /////////////////////////////////////////////////////////////////////////// // #if !defined(AFX_MAINFRM_H__AE0A6FFE_9B0F_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MAINFRM_H__AE0A6FFE_9B0F_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMainFrame : public CFrameWnd { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations
Trang 138
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "Wanderer.h" #include "WandererDoc.h" #include "DriveView.h" #include "FileView.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
Trang 139
Trang 140
WandererDoc.h
// WandererDoc.h : interface of the CWandererDoc class // /////////////////////////////////////////////////////////////////////////// // #if !defined(AFX_WANDERERDOC_H__AE0A7000_9B0F_11D2_8E53_006008A82731__INCLUDED_) #define AFX_WANDERERDOC_H__AE0A7000_9B0F_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CWandererDoc : public CDocument { protected: // create from serialization only CWandererDoc(); DECLARE_DYNCREATE(CWandererDoc) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CWandererDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL // Implementation public: BOOL RouteCmdToAllViews (CView* pView, UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); virtual ~CWandererDoc(); #ifdef _DEBUG
Trang 141
WandererDoc.cpp
// WandererDoc.cpp : implementation of the CWandererDoc class // #include "stdafx.h" #include "Wanderer.h" #include "WandererDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CWandererDoc IMPLEMENT_DYNCREATE(CWandererDoc, CDocument) BEGIN_MESSAGE_MAP(CWandererDoc, CDocument) //{{AFX_MSG_MAP(CWandererDoc) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CWandererDoc construction/destruction CWandererDoc::CWandererDoc() { } CWandererDoc::~CWandererDoc() { } BOOL CWandererDoc::OnNewDocument() { if (!CDocument::OnNewDocument())
Trang 142
DriveView.h
// DriveTreeView.h : interface of the CDriveView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_DRIVETREEVIEW_H__090B382D_959D_11D2_8E53_006008A82731__INCLUDED_) #define AFX_DRIVETREEVIEW_H__090B382D_959D_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CDriveView : public CTreeView
Trang 143
Trang 144
DriveView.cpp
// DriveTreeView.cpp : implementation of the CDriveView class // #include "stdafx.h" #include "Wanderer.h" #include "WandererDoc.h" #include "DriveView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Image indexes #define ILI_HARD_DISK 0 #define ILI_FLOPPY 1 #define ILI_CD_ROM 2 #define ILI_NET_DRIVE 3 #define ILI_CLOSED_FOLDER 4 #define ILI_OPEN_FOLDER 5 /////////////////////////////////////////////////////////////////////////// // CDriveView IMPLEMENT_DYNCREATE(CDriveView, CTreeView) BEGIN_MESSAGE_MAP(CDriveView, CTreeView) //{{AFX_MSG_MAP(CDriveView) ON_NOTIFY_REFLECT(TVN_ITEMEXPANDING, OnItemExpanding) ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnSelectionChanged) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CDriveView construction/destruction CDriveView::CDriveView() { } CDriveView::~CDriveView() { } BOOL CDriveView::PreCreateWindow(CREATESTRUCT& cs) { if (!CTreeView::PreCreateWindow (cs)) return FALSE; cs.style |= TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS; return TRUE; } /////////////////////////////////////////////////////////////////////////// // CDriveView drawing
Trang 145
Trang 146
Trang 147
Trang 148
Trang 149
do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { CString strComp = (LPCTSTR) &fd.cFileName; if ((strComp != _T (".")) && (strComp != _T (".."))) { hNewItem = GetTreeCtrl ().InsertItem ((LPCTSTR) &fd.cFileName, ILI_CLOSED_FOLDER, ILI_OPEN_FOLDER, hItem); CString strNewPath = pszPath; if (strNewPath.Right (1) != _T ("\\")) strNewPath += _T ("\\"); strNewPath += (LPCTSTR) &fd.cFileName; SetButtonState (hNewItem, strNewPath); nCount++; } } } while (::FindNextFile (hFind, &fd)); ::FindClose (hFind); return nCount; } void CDriveView::OnSelectionChanged(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*) pNMHDR; CString strPath = GetPathFromItem (pNMTreeView->itemNew.hItem); GetDocument ()->UpdateAllViews (this, 0x5A, (CObject*) (LPCTSTR) strPath); *pResult = 0; }
FileView.h
// FileView.h : interface of the CFileView class // /////////////////////////////////////////////////////////////////////////// // #if !defined(AFX_FILEVIEW_H__18BD7B80_95C6_11D2_8E53_006008A82731__INCLUDED_) #define AFX_FILEVIEW_H__18BD7B80_95C6_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 typedef struct tagITEMINFO { CString strFileName; DWORD nFileSizeLow; FILETIME ftLastWriteTime; } ITEMINFO; class CFileView : public CListView { protected: // create from serialization only CFileView(); DECLARE_DYNCREATE(CFileView)
Trang 150
Trang 151
FileView.cpp
// FileView.cpp : implementation of the CFileView class // #include "stdafx.h" #include "Wanderer.h" #include "WandererDoc.h" #include "FileView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CFileView IMPLEMENT_DYNCREATE(CFileView, CListView) BEGIN_MESSAGE_MAP(CFileView, CListView) //{{AFX_MSG_MAP(CFileView) ON_WM_DESTROY() ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnGetDispInfo) ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnColumnClick) ON_COMMAND(ID_VIEW_LARGE_ICONS, OnViewLargeIcons) ON_COMMAND(ID_VIEW_SMALL_ICONS, OnViewSmallIcons) ON_COMMAND(ID_VIEW_LIST, OnViewList) ON_COMMAND(ID_VIEW_DETAILS, OnViewDetails) ON_UPDATE_COMMAND_UI(ID_VIEW_LARGE_ICONS, OnUpdateViewLargeIcons) ON_UPDATE_COMMAND_UI(ID_VIEW_SMALL_ICONS, OnUpdateViewSmallIcons) ON_UPDATE_COMMAND_UI(ID_VIEW_LIST, OnUpdateViewList) ON_UPDATE_COMMAND_UI(ID_VIEW_DETAILS, OnUpdateViewDetails) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CFileView construction/destruction CFileView::CFileView() { } CFileView::~CFileView() { } BOOL CFileView::PreCreateWindow(CREATESTRUCT& cs) { if (!CListView::PreCreateWindow (cs)) return FALSE; cs.style &= ~LVS_TYPEMASK; cs.style |= LVS_REPORT; return TRUE;
Trang 152
Trang 153
Trang 154
Trang 155
Trang 156
Mn hnh kt qu nh sau:
Vn quan tm
Hiu v s dng c cc class v Toolbar, StatusBar.
Trang 157
2.4.2
ToolBar
ToolBar l cng c lin kt gia cc hnh bitmap vi cc hm chc nng tng ng th hin vai tr tng t nh 1 button MFC cung cp lp CToolBar gip thao tc vi toolbar thun li hn. Tuy nhin class CToolBarCtrl cn gip m rng kh nng thao tc vi toolbar control (trong comctl32.dll) to v khai bo 1 toolbar, cn thc hin theo trnh t sau y: Vo Resources View, thm 1 toolbal vo v thm/bt cc hnh bitmap tng ng. C th to 1 class lin kt vi toolbar ny hay s dng class CToolBar c s Vo class CMainFrame o Thm bin lin kt vi toolbar(c kiu l CToolBar hay class t to) o Thm lnh khi to cho toolbar ny trong hm OnCreate v thit lp cc c tnh tng ng. o Lin kt vi document bi vic gi hm EnableDocking v DockControlBar o Thm cc hm chc nng tng ng vi cc bitmap trong toolbar p ng cc s kin tng tc vi chng. S dng s h tr t AppWizard nh sau:
// Trong file H
class CMainFrame : public CFrameWnd { protected: CToolBar m_wndMyToolBar; }
V d 2:
Trong file RC
IDR_TOOLBAR BITMAP Toolbar.bmp IDR_TOOLBAR TOOLBAR 16, 15 BEGIN BUTTON ID_FILE_NEW BUTTON ID_FILE_OPEN BUTTON ID_FILE_SAVE SEPARATOR BUTTON ID_EDIT_CUT BUTTON ID_EDIT_COPY BUTTON ID_EDIT_PASTE BUTTON ID_EDIT_UNDO SEPARATOR BUTTON ID_FILE_PRINT END
Trong file RC
IDR_TOOLBAR BITMAP Toolbar.bmp
Trang 159
2.4.3
StatusBar
StatusBar l cng c th hin thng tin trong ca s ng dng. MFC cung cp class CStatusBar gip thao tc vi statusbar thun li hn. to v khai bo 1 statusbar, cn thc hin theo trnh t sau y: Xc nh danh sch cc phn(pane) trong statusbar. Vo class CMainFrame o Thm bin lin kt vi statusbar(c kiu l CStatusBar) o Thm lnh khi to cho toolbar ny trong hm OnCreate v thit lp cc c tnh tng ng. o Gi hm SetIndicators khai bo s lng pane trong statusbar o tng tc(iu khin, hin th thng tin) , truy xut thng qua bin lin kt cc hm nh SetPaneText V d 1: Trong Resources View
Khai bo cc thnh phn trong statusbar static UINT nIndicators[] = { ID_SEPARATOR, ID_SEPARATOR, ID_SEPARATOR }; STRINGTABLE DISCARDABLE DISCARDABLE BEGIN ID_INDICATOR_EXT "EXT" ID_INDICATOR_CAPS "CAP" ID_INDICATOR_NUM "NUM" ID_INDICATOR_SCRL "SCRL" ID_INDICATOR_OVR "OVR" ID_INDICATOR_REC "REC" END
Trong file H
class CMainFrame : public CFrameWnd { protected: CStatusBar m_wndMyStatusBar;
Trang 160
V d tng hp MainFrm.h
// MainFrm.h : interface of the CMainFrame class // /////////////////////////////////////////////////////////////////////////// #if !defined( AFX_MAINFRM_H__C85C9089_A154_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MAINFRM_H__C85C9089_A154_11D2_8E53_006008A82731__INCLUDED_ #include "StyleBar.h" #if _MSC_VER > 1000 // Added by ClassView
Trang 161
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "MyWord.h" #include "MainFrm.h"
Trang 162
Trang 163
Trang 164
MyWordDoc.h
// MyWordDoc.h : interface of the CMyWordDoc class // /////////////////////////////////////////////////////////////////////////// #if !defined( AFX_MYWORDDOC_H__C85C908B_A154_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MYWORDDOC_H__C85C908B_A154_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMyWordDoc : public CRichEditDoc { protected: // create from serialization only CMyWordDoc(); DECLARE_DYNCREATE(CMyWordDoc) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMyWordDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL virtual CRichEditCntrItem* CreateClientItem(REOBJECT* preo) const; // Implementation public: virtual ~CMyWordDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMyWordDoc) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; /////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}}
Trang 165
MyWordDoc.cpp
// MyWordDoc.cpp : implementation of the CMyWordDoc class // #include "stdafx.h" #include "MyWord.h" #include "MyWordDoc.h" #include "CntrItem.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CMyWordDoc IMPLEMENT_DYNCREATE(CMyWordDoc, CRichEditDoc) BEGIN_MESSAGE_MAP(CMyWordDoc, CRichEditDoc) //{{AFX_MSG_MAP(CMyWordDoc) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Enable default OLE container implementation ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_LINKS, CRichEditDoc::OnUpdateEditLinksMenu) ON_COMMAND(ID_OLE_EDIT_LINKS, CRichEditDoc::OnEditLinks) ON_UPDATE_COMMAND_UI_RANGE(ID_OLE_VERB_FIRST, ID_OLE_VERB_LAST, CRichEditDoc::OnUpdateObjectVerbMenu) END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CMyWordDoc construction/destruction CMyWordDoc::CMyWordDoc() { } CMyWordDoc::~CMyWordDoc() { } BOOL CMyWordDoc::OnNewDocument() { if (!CRichEditDoc::OnNewDocument()) return FALSE; return TRUE; } CRichEditCntrItem* CMyWordDoc::CreateClientItem(REOBJECT* preo) const { return new CMyWordCntrItem(preo, (CMyWordDoc*) this); } /////////////////////////////////////////////////////////////////////////// // CMyWordDoc serialization
Trang 166
MyWordView.h
// MyWordView.h : interface of the CMyWordView class // /////////////////////////////////////////////////////////////////////////// #if !defined( AFX_MYWORDVIEW_H__C85C908D_A154_11D2_8E53_006008A82731__INCLUDED_) #define AFX_MYWORDVIEW_H__C85C908D_A154_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMyWordCntrItem; class CMyWordView : public CRichEditView { protected: // create from serialization only CMyWordView(); DECLARE_DYNCREATE(CMyWordView) // Attributes public: CMyWordDoc* GetDocument(); // Operations public: void GetFontInfo (LPTSTR pszFaceName, int& nSize); void ChangeFont (LPCTSTR pszFaceName); void ChangeFontSize (int nSize); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMyWordView) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // called first time after construct //}}AFX_VIRTUAL // Implementation
Trang 167
MyWordView.cpp
// MyWordView.cpp : implementation of the CMyWordView class // #include "stdafx.h" #include "MyWord.h" #include "MyWordDoc.h" #include "CntrItem.h" #include "MyWordView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif
Trang 168
Trang 169
Trang 170
Trang 171
StyleBar.h
#if !defined( AFX_STYLEBAR_H__C85C9099_A154_11D2_8E53_006008A82731__INCLUDED_) #define AFX_STYLEBAR_H__C85C9099_A154_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // StyleBar.h : header file // /////////////////////////////////////////////////////////////////////////// // CStyleBar command target class CStyleBar : public CToolBar { // Attributes public: // Operations public: static int CALLBACK EnumFontNameProc (ENUMLOGFONT* lpelf, NEWTEXTMETRIC* lpntm, int nFontType, LPARAM lParam); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CStyleBar) //}}AFX_VIRTUAL virtual void OnUpdateCmdUI (CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Implementation protected: void InitTypefaceList (CDC* pDC); CFont m_font; CComboBox m_wndFontNames; CComboBox m_wndFontSizes; // Generated message map functions //{{AFX_MSG(CStyleBar)
Trang 172
StyleBar.cpp
// StyleBar.cpp : implementation file // #include "stdafx.h" #include "MyWord.h" #include "MyWordDoc.h" #include "MyWordView.h" #include "StyleBar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CStyleBar BEGIN_MESSAGE_MAP(CStyleBar, CToolBar) //{{AFX_MSG_MAP(CStyleBar) ON_WM_CREATE() //}}AFX_MSG_MAP ON_CBN_SELENDOK (IDC_FONTNAMES, OnSelectFont) ON_CBN_SELENDOK (IDC_FONTSIZES, OnSelectSize) ON_CBN_CLOSEUP (IDC_FONTNAMES, OnCloseUp) ON_CBN_CLOSEUP (IDC_FONTSIZES, OnCloseUp) END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CStyleBar message handlers int CStyleBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { static int nFontSizes[] = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 32, 36, 48, 72 }; if (CToolBar::OnCreate(lpCreateStruct) == -1) return -1; // // Load the toolbar. // if (!LoadToolBar (IDR_STYLE_BAR)) return -1; // // Create an 8-point MS Sans Serif font for the combo boxes.
Trang 173
Trang 174
Trang 175
Mn hnh kt qu nh sau:
Trang 176
CHNG 3. X L H THNG
3.1 TIMER/IDLE
3.1.1
Vn quan tm
Hiu v s dng c cc class v Timer/Idles.
3.1.2
Timer
Vic to s kin thc thi lp i lp li theo chu k nht nh c gii quyt bi vic dng WM_TIMER to s kin dng Timer, cn thc hin theo trnh t sau: Vo Add Windows Message Handler thm message WM_TIMER vo ng dng, hm OnTimer xut hin sau khi thm. Trong hm OnCreate ca class, thm hm SetTimer khai bo thi gian(chu k) lp li(thi gian ti a l 2^32-1 milliseconds) Hin thc cc thao tc trong hm OnTimer p ng s kin WM_TIMER. V d 1:
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_WM_TIMER() END_MESSAGE_MAP() int CMainFrame::OnCreate(LPCREATESTRUCT lpcs) { if(CFrameWnd::OnCreate(lpcs) == -1) return -1; // ID_TIMER_ELLIPSE l timerID ca s kin Timer ny if(!SetTimer(ID_TIMER_ELLIPSE, 100, NULL)) { MessageBox(_T("Error: SetTimer failed")); return -1; } return 0; }
hay:
void CMainFrame::OnTimer(UINT nTimerID) { CRect rect; GetClientRect(&rect); int int int int x1 x2 y1 y2 = = = = rand() rand() rand() rand() % % % % rect.right; rect.right; rect.bottom; rect.bottom;
CClientDC dc(this); CBrush brush(RGB(rand() % 255, rand() % 255, rand() % 255)); CBrush* pOldBrush = dc.SelectObject(&brush); dc.Ellipse(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)); dc.SelectObject(pOldBrush); }
Trang 177
3.1.3
Idles
Vic lm x l gin on trong h thng c gii quyt bi hm Idle hay s kin OnIdle V d 1:
BOOL CMyApp::OnIdle(LONG lCount) { BOOL bMFCContinue = CWinApp::OnIdle(lCount); BOOL bAppContinue = TRUE; if(lCount >= 2) bAppContinue = DoIdleWork(); // Do custom idle processing. return(bMFCContinue bAppContinue); }
Clock.rc
#include <afxres.h> #include "Resource.h" IDI_APPICON ICON Clock.ico
Clock.h
class CMyApp : public CWinApp { public: virtual BOOL InitInstance (); }; class CMainWindow : public CFrameWnd { protected: BOOL m_bFullWindow; BOOL m_bStayOnTop; int m_nPrevSecond; int m_nPrevMinute; int m_nPrevHour; void DrawClockFace (CDC* pDC); void DrawSecondHand (CDC* pDC, int nLength, int nScale, int nDegrees, COLORREF clrColor); void DrawHand (CDC* pDC, int nLength, int nScale, int nDegrees, COLORREF clrColor); void void void void SetTitleBarState (); SetTopMostState (); SaveWindowState (); UpdateSystemMenu (CMenu* pMenu);
Trang 178
int OnCreate (LPCREATESTRUCT lpcs); void OnGetMinMaxInfo (MINMAXINFO* pMMI); void OnTimer (UINT nTimerID); void OnPaint (); UINT OnNcHitTest (CPoint point); void OnSysCommand (UINT nID, LPARAM lParam); void OnContextMenu (CWnd* pWnd, CPoint point); void OnEndSession (BOOL bEnding); void OnClose ();
DECLARE_MESSAGE_MAP () };
Clock.cpp
#include <afxwin.h> #include <math.h> #include "Clock.h" #include "Resource.h" #define SQUARESIZE 20 #define ID_TIMER_CLOCK 1 CMyApp myApp; ///////////////////////////////////////////////////////////////////////// // CMyApp member functions BOOL CMyApp::InitInstance () { SetRegistryKey (_T ("Programming Windows with MFC")); m_pMainWnd = new CMainWindow; if (!((CMainWindow*) m_pMainWnd)->RestoreWindowState ()) 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_PAINT () ON_WM_TIMER () ON_WM_GETMINMAXINFO () ON_WM_NCHITTEST () ON_WM_SYSCOMMAND () ON_WM_CONTEXTMENU () ON_WM_ENDSESSION () ON_WM_CLOSE () END_MESSAGE_MAP () CMainWindow::CMainWindow () { m_bAutoMenuEnable = FALSE;
Trang 179
);
Create (strWndClass, _T ("Clock")); } BOOL CMainWindow::PreCreateWindow (CREATESTRUCT& cs) { if (!CFrameWnd::PreCreateWindow (cs)) return FALSE; cs.dwExStyle &= ~WS_EX_CLIENTEDGE; return TRUE; } int CMainWindow::OnCreate (LPCREATESTRUCT lpcs) { if (CFrameWnd::OnCreate (lpcs) == -1) return -1; // // Set a timer to fire at 1-second intervals. // if (!SetTimer (ID_TIMER_CLOCK, 1000, NULL)) { MessageBox (_T ("SetTimer failed"), _T ("Error"), MB_ICONSTOP MB_OK); return -1; } // // Customize the system menu. // CMenu* pMenu = GetSystemMenu (FALSE); pMenu->AppendMenu (MF_SEPARATOR); pMenu->AppendMenu (MF_STRING, IDM_SYSMENU_FULL_WINDOW, _T ("Remove &Title")); pMenu->AppendMenu (MF_STRING, IDM_SYSMENU_STAY_ON_TOP, _T ("Stay on To&p")); return 0; } void CMainWindow::OnClose () { SaveWindowState (); KillTimer (ID_TIMER_CLOCK); CFrameWnd::OnClose (); } void CMainWindow::OnEndSession (BOOL bEnding) { if (bEnding) SaveWindowState ();
Trang 180
Trang 181
Trang 182
// 12 o'clock // 1 o'clock // 2 o'clock // 3 o'clock // 4 o'clock // 5 o'clock // 6 o'clock // 7 o'clock // 8 o'clock // 9 o'clock // 10 o'clock // 11 o'clock
pDC->SelectStockObject (NULL_BRUSH); for (int i=0; i<12; i++) pDC->Rectangle (point[i].x - SQUARESIZE, point[i].y + SQUARESIZE, point[i].x + SQUARESIZE, point[i].y - SQUARESIZE); } void CMainWindow::DrawHand (CDC* pDC, int nLength, int nScale, int nDegrees, COLORREF clrColor) { CPoint point[4]; double nRadians = (double) nDegrees * 0.017453292; point[0].x = (int) (nLength * sin (nRadians)); point[0].y = (int) (nLength * cos (nRadians)); point[2].x = -point[0].x / nScale; point[2].y = -point[0].y / nScale; point[1].x = -point[2].y; point[1].y = point[2].x; point[3].x = -point[1].x; point[3].y = -point[1].y; CPen pen (PS_SOLID, 0, clrColor); CPen* pOldPen = pDC->SelectObject (&pen);
Trang 183
pDC->SelectObject (pOldPen); } void CMainWindow::DrawSecondHand (CDC* pDC, int nLength, int nScale, int nDegrees, COLORREF clrColor) { CPoint point[2]; double nRadians = (double) nDegrees * 0.017453292; point[0].x = (int) (nLength * sin (nRadians)); point[0].y = (int) (nLength * cos (nRadians)); point[1].x = -point[0].x / nScale; point[1].y = -point[0].y / nScale; CPen pen (PS_SOLID, 0, clrColor); CPen* pOldPen = pDC->SelectObject (&pen); pDC->MoveTo (point[0]); pDC->LineTo (point[1]); pDC->SelectObject (pOldPen); } void CMainWindow::SetTitleBarState () { CMenu* pMenu = GetSystemMenu (FALSE); if (m_bFullWindow ) { ModifyStyle (WS_CAPTION, 0); pMenu->ModifyMenu (IDM_SYSMENU_FULL_WINDOW, MF_STRING, IDM_SYSMENU_FULL_WINDOW, _T ("Restore &Title")); } else { ModifyStyle (0, WS_CAPTION); pMenu->ModifyMenu (IDM_SYSMENU_FULL_WINDOW, MF_STRING, IDM_SYSMENU_FULL_WINDOW, _T ("Remove &Title")); } SetWindowPos (NULL, 0, 0, 0, 0, SWP_NOMOVE SWP_NOSIZE SWP_NOZORDER SWP_DRAWFRAME); } void CMainWindow::SetTopMostState () { CMenu* pMenu = GetSystemMenu (FALSE); if (m_bStayOnTop) { SetWindowPos (&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE SWP_NOSIZE); pMenu->CheckMenuItem (IDM_SYSMENU_STAY_ON_TOP, MF_CHECKED); } else {
Trang 184
_T ("flags"), -1)) != -1) && _T ("showCmd"), -1)) != -1) && _T ("x1"), -1)) != -1) && _T ("y1"), -1)) != -1) && _T ("x2"), -1)) != -1) && _T ("y2"), -1)) != -1)) {
wp.rcNormalPosition.left = min (wp.rcNormalPosition.left, ::GetSystemMetrics (SM_CXSCREEN) ::GetSystemMetrics (SM_CXICON)); wp.rcNormalPosition.top = min (wp.rcNormalPosition.top, ::GetSystemMetrics (SM_CYSCREEN) ::GetSystemMetrics (SM_CYICON)); SetWindowPlacement (&wp); return TRUE; } return FALSE; } void CMainWindow::SaveWindowState () { CString version = _T ("Version 1.0"); myApp.WriteProfileInt (version, _T ("FullWindow"), m_bFullWindow); myApp.WriteProfileInt (version, _T ("StayOnTop"), m_bStayOnTop); WINDOWPLACEMENT wp; wp.length = sizeof (WINDOWPLACEMENT); GetWindowPlacement (&wp); myApp.WriteProfileInt myApp.WriteProfileInt myApp.WriteProfileInt myApp.WriteProfileInt myApp.WriteProfileInt (version, (version, (version, (version, (version, _T _T _T _T _T ("flags"), wp.flags); ("showCmd"), wp.showCmd); ("x1"), wp.rcNormalPosition.left); ("y1"), wp.rcNormalPosition.top); ("x2"), wp.rcNormalPosition.right);
Trang 185
Mn hnh kt qu nh sau:
Trang 186
3.2 THREADS
3.2.1
Vn quan tm
Hiu v s dng c k thut lp trnh v thread.
3.2.2
Gii thiu
Thread (tiu trnh/lung) l mt phn lnh ca chng trnh ng dng thc thi vi mc ch c lp v khng phn chia nh hn na. Mt qu trnh trong ng dng dng Win-32 bit c bt u nh n lung (single thread) nhng cng c th thm nhiu lung khc tr thnh a lung (multi threads) Vic xy dng ng dng dng multi threads khng n gin v khng dnh cho tt c cc dng ng dng m ch dng cho cc ng dng dng lp trnh/x l song song (paralell processing) MFC h tr vic lp trnh vi thread bi lp CWinThread
3.2.3
Threads
to mt thread, gi hm AfxBeginThread V d 1:
CWinThread* pThread = AfxBeginThread(ThreadFunc, &threadInfo); V UINT ThreadFunc(LPVOID pParam) { UINT nIterations =(UINT) pParam; for(UINT i=0; i<nIterations; i++); return 0; }
Trang 187
C th tm ngng (Suspend) v khi phc (Resume) vic hot ng ca thread bi cc lnh SuspendThread v ResumeThread C th t thread vo trng thi tm ngng trong mt thi gian hn nh bng vic dng lnh Sleep Kt thc mt thread bng vic dng lnh AfxEndThread t u tin cho thread bng SetPriorityClass, vi cc gi tr c th chn nh sau: u tin M t IDLE_PRIORITY_CLASS The process runs only when the system is idlefor example, when no other thread is waiting for a given CPU. NORMAL_PRIORITY_CLASS The default process priority class. The process has no special scheduling needs. HIGH_PRIORITY_CLASS The process receives priority over IDLE_PRIORITY_CLASS and NORMAL_PRIORITY_CLASS processes. REALTIME_PRIORITY_CLASS The process must have the highest possible priority, and its threads should preempt even threads belonging to HIGH_PRIORITY_CLASS processes. V: Mc u tin THREAD_PRIORITY_IDLE M t The thread's base priority level is 1 if the process's priority class is HIGH_PRIORITY_CLASS or lower, or 16 if the process's priority class is REALTIME_PRIORITY_CLASS. The thread's base priority level is equal to the
Lp trnh Windows vi VC/MFC process's priority class minus 2. The thread's base priority level is equal to the process's priority class minus 1. The default thread priority value. The thread's base priority level is equal to the process's priority class. The thread's base priority level is equal to the process's priority class plus 1. The thread's base priority level is equal to the process's priority class plus 2. The thread's base priority level is 15 if the process's priority class is HIGH_PRIORITY_CLASS or lower, or 31 if the process's priority class is REALTIME_PRIORITY_CLASS.
Trang 189
Trang 190
Sieve.cpp
// Sieve.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "Sieve.h" #include "SieveDlg.h"
Trang 191
#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CSieveApp BEGIN_MESSAGE_MAP(CSieveApp, CWinApp) //{{AFX_MSG_MAP(CSieveApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CSieveApp construction CSieveApp::CSieveApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } /////////////////////////////////////////////////////////////////////////// // The one and only CSieveApp object CSieveApp theApp; /////////////////////////////////////////////////////////////////////////// // CSieveApp initialization BOOL CSieveApp::InitInstance() { // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. CSieveDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
SieveDlg.h
// SieveDlg.h : header file //
Trang 192
SieveDlg.cpp
// SieveDlg.cpp : implementation file //
Trang 193
Trang 194
Mn hnh kt qu nh sau:
Trang 195
3.2.4
ng b cc threads(Thread Synchronization)
(Xem Chng 17, phn Thread Synchronization, sch Programming Windows with MFC, 2nd edition) Windows cung cp 4 kiu ca i tng ng b m c th dng ng b cc hnh ng ca cc thread hot ng song hnh nh sau: Critical sections Mutexes Events Semaphores Vic ng b cc thread bi cc i tng ny thng qua vic x l hin thc tc v Lock v Unlock iu phi quyn truy xut d liu/b nh ng thi hay khng. Ngoi ra MFC cn cung cp lp CSingleLock and CMultiLock tr gp vic x l hin thc tc v Lock v Unlock ca cc i tng trn mt cch n gin hn.
CCriticalSection g_cs; CSingleLock lock (&g_cs); // Wrap it in a CSingleLock. lock.Lock (); // Lock the critical section.
hay
CMutex g_mutex; CEvent g_event[2]; CSyncObject* g_pObjects[3] = { &g_mutex, &g_event[0], &g_event[1] }; // Block until all three objects become signaled. CMultiLock multiLock (g_pObjects, 3); multiLock.Lock (); // Block until one of the three objects becomes signaled. CMultiLock multiLock (g_pObjects, 3); multiLock.Lock (INFINITE, FALSE);
Trang 196
MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "ImageEdit.h" #include "ImageEditDoc.h" #include "SpecialStatusBar.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
Trang 197
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_WM_QUERYNEWPALETTE() ON_WM_PALETTECHANGED() //}}AFX_MSG_MAP ON_MESSAGE (WM_USER_UPDATE_STATS, OnUpdateImageStats) ON_MESSAGE (WM_USER_THREAD_UPDATE, OnThreadUpdate) ON_MESSAGE (WM_USER_THREAD_FINISHED, OnThreadFinished) ON_MESSAGE (WM_USER_THREAD_ABORTED, OnThreadAborted) END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, ID_SEPARATOR, ID_SEPARATOR }; /////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction CMainFrame::CMainFrame() { m_nPercentDone = -1; } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndStatusBar.Create(this)) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; return TRUE; } /////////////////////////////////////////////////////////////////////////// // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const {
Trang 198
Trang 200
ImageEditDoc.cpp
// ImageEditDoc.cpp : implementation of the CImageEditDoc class // #include "stdafx.h" #include "ImageEdit.h" #include "ImageEditDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // CImageEditDoc IMPLEMENT_DYNCREATE(CImageEditDoc, CDocument) BEGIN_MESSAGE_MAP(CImageEditDoc, CDocument) //{{AFX_MSG_MAP(CImageEditDoc) ON_COMMAND(ID_EFFECTS_GRAY_SCALE, OnGrayScale) ON_UPDATE_COMMAND_UI(ID_EFFECTS_GRAY_SCALE, OnUpdateGrayScale) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////// // CImageEditDoc construction/destruction CImageEditDoc::CImageEditDoc() : m_event (FALSE, TRUE) // Manual-reset event, initially unowned { m_hThread = NULL; m_bWorking = FALSE; } CImageEditDoc::~CImageEditDoc() { } BOOL CImageEditDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; return TRUE; } /////////////////////////////////////////////////////////////////////////// // CImageEditDoc diagnostics #ifdef _DEBUG void CImageEditDoc::AssertValid() const { CDocument::AssertValid(); }
Trang 201
Trang 202
Trang 203
Trang 204
Trang 205
Trang 206
ImageEditView.h
// ImageEditView.h : interface of the CImageEditView class // /////////////////////////////////////////////////////////////////////////// #if !defined( AFX_IMAGEEDITVIEW_H__9D77AEEC_AA14_11D2_8E53_006008A82731__INCLUDED_) #define AFX_IMAGEEDITVIEW_H__9D77AEEC_AA14_11D2_8E53_006008A82731__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CImageEditView : public CScrollView
Trang 207
ImageEditView.cpp
// ImageEditView.cpp : implementation of the CImageEditView class // #include "stdafx.h" #include "ImageEdit.h" #include "ImageEditDoc.h" #include "ImageEditView.h"
Trang 208
Trang 209
SpecialStatusBar.h
// SpecialStatusBar.h: interface for the CSpecialStatusBar class. // ////////////////////////////////////////////////////////////////////// #if !defined(
Trang 210
SpecialStatusBar.cpp
// SpecialStatusBar.cpp: implementation of the CSpecialStatusBar class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ImageEdit.h" #include "SpecialStatusBar.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CSpecialStatusBar, CStatusBar) ON_WM_CREATE () ON_WM_SIZE () END_MESSAGE_MAP() CSpecialStatusBar::CSpecialStatusBar() { } CSpecialStatusBar::~CSpecialStatusBar() { } int CSpecialStatusBar::OnCreate (LPCREATESTRUCT lpcs) { static UINT nIndicators[] = { ID_SEPARATOR,
Trang 211
Trang 212
Mn hnh kt qu nh sau:
Trang 213
Vn quan tm
Hiu v s dng c cc class v truy xut d liu m MFC h tr. Hiu v lp trnh c cc s kin tng tc d liu.
4.1.2
Gii thiu
T chc cc class gip truy xut d liu bao gm: Class Use CDaoWorkspace Giao din qun l cc n kt ni. CDaoDatabase Giao din lm vic vi database CDaoRecordset Giao din lm vic vi tp cc mu tin (kiu table, dynaset, snapshot) CDaoTableDef Giao din thao tc nh ngha hay truy xut bng d liu. CDaoQueryDef Giao din truy vn d liu Trong qu trnh truy xut d liu, d liu ly t c s d liu v thng c lu tr v qun l bi class CRecordset. Thnh phn ca class CRecordset nh sau: Tn hm M t Open M recordset AddNew Chun b thm mi mu d liu vo bng d liu Update Hon tt thao tc AddNew hay Edit bi thc hin lu vo c s d liu. Delete Xo mu d liu hin hnh Edit Chun b thay i mu d liu vo bng d liu IsBOF Nhn bit v tr ng u trong tp d liu IsEOF Nhn bit v tr ng cui trong tp d liu MoveNext Di chuyn sang mu d liu k tip MoveFirst Di chuyn sang mu d liu u tin MoveLast Di chuyn sang mu d liu cui cng MovePrev Di chuyn sang mu d liu lin trc GetDefaultConnect Ly v chui kt ni c s d liu mc nh GetDefaultSQL Ly v chui truy vn c s d liu mc nh DoFieldExchange Thc hin trao i d liu gia thnh phn d liu trong tp d liu vi bin lin kt tng ng GetStatus Ly v ch mc ca mu d liu hin hnh v trng thy ca n GetRecordCount Ly v s lng mu d liu trong tp d liu GetODBCFieldCount Ly v s lng thnh phn d liu trong tp d liu GetODBCFieldInfo Ly v thng tin thnh phn d liu trong tp d liu Trang 214
Lp trnh Windows vi VC/MFC Vic nhn bit trng thi v s lng mu tin (row/record) trong qu trnh truy vn d liu t i tng CRecordset c thc hin bi hm GetRecordCount() v GetStatus() Vic di chuyn gia cc record bi hm MoveNext(), MovePrevious(), MoveFirst(), MoveLast(). x l by li trong qu trnh truy xut, dng c ch trycatch theo v d sau: V d 1:
try { m_pSet->Delete(); // thao tc cp nht - xo d liu } catch(CDBException* e) { AfxMessageBox(e->m_strError); e->Delete(); m_pSet->MoveFirst(); // lost our place! UpdateData(FALSE); return; } m_pSet->MoveNext();
duyt tp hp d liu trong i tng CRecordset, dng vng lp theo v d sau: V d 2: To 1 class CMySet nh sau:
class CMySet: public CRecordset { int MyID; CString MyName; CString GetDefaultConnect() {return _T("ODBC;DSN=MyDabase");}; CString GetDefaultSQL() { return _T("[MyTable]");}; }
if(m_pSet->IsBOF())
return; }
m_pSet->MoveFirst(); // fails if recordset is empty while(!m_pSet->IsEOF()) { str.Format("%ld", m_pSet->m_MyID); pDC->TextOut(10, 20, str); pDC->TextOut(10, 50, m_pSet->m_MyName);
Trang 215
m_pSet->Update();
0 Ch : s dng cc lp truy xut d liu, cn thm vo hng cui cng trong file StdAfx.h hng khai bo nh sau:
#include <afxdb.h>
sau hng lnh "#include ""afxprint.rc"" // printing print preview resources\r\n" thm hng khai bo
#include "afxdb.rc" // database resources
sau hng lnh #include "afxprint.rc" // printing print preview resources khai bo ngun d liu, cn s dng tin ch DataSource(ODBC) c trong chng trnh Windows (ti Control Panel) nh sau:
v qu trnh khai bo tn ngun d liu c tin hnh trong ng dng ny: Trang 216
v:
v:
Trang 217
4.1.3
V d tng hp
4.1.3.1 Chng trnh 1: B1: Cho c s d liu c cu trc cc bng (table) nh sau:
Trang 218
v:
v:
Trang 219
B6: Cp nht chng trnh nh sau: Trong lp (class) CEx31aDoc ca file ex31aDoc.h, thm:
CEx31aSet m_ex31aSet;
Trang 220
4.1.3.2 Chng trnh 2: B1: To ng dng trong mi trng Visual C++ nh sau (tha k t CFormView):
B2: To giao din chng trnh nh sau (vi cc edit box c tn ln lt l IDC_NAME, and IDC_ROOM): Trang 221
v:
B4: Bin dch v thc thi chng trnh B5: To cc hm lin kt cc icon (next, back, first, last) c trn toolbar nhu sau: Command ID ID_RECORD_ADD ID_RECORD_CLEARFIELDS ID_RECORD_DELETE Command Handler OnRecordAdd OnRecordClearfields OnRecordDelete OnUpdateRecordDelete Update Command UI Handler
BOOL CEx31bView::OnMove(UINT nIDMoveCommand) { switch (nIDMoveCommand) { case ID_RECORD_PREV: m_pSet->MovePrev(); if (!m_pSet->IsBOF()) break; case ID_RECORD_FIRST: m_pSet->MoveFirst(); break; case ID_RECORD_NEXT: m_pSet->MoveNext(); if (!m_pSet->IsEOF()) break; if (!m_pSet->CanScroll()) { // Clear screen since we're sitting on EOF m_pSet->SetFieldNull(NULL); break; } case ID_RECORD_LAST: m_pSet->MoveLast(); break; default: // unexpected case value ASSERT(FALSE); } // Show results of Move operation UpdateData(FALSE); return TRUE; }
v:
void CEx31bView::OnRecordAdd() { m_pSet->AddNew(); UpdateData(TRUE); if (m_pSet->CanUpdate()) { m_pSet->Update(); } if (!m_pSet->IsEOF()) { m_pSet->MoveLast(); } m_pSet->Requery(); // for sorted sets UpdateData(FALSE); }
Trang 223
void CEx31bView::OnRecordClearfields() { m_pSet->SetFieldNull(NULL); UpdateData(FALSE); } void CEx31bView::OnRecordDelete() { CRecordsetStatus status; try { m_pSet->Delete(); } catch(CDBException* e) { AfxMessageBox(e->m_strError); e->Delete(); m_pSet->MoveFirst(); // lost our place! UpdateData(FALSE); return; } m_pSet->GetStatus(status); if (status.m_lCurrentRecord == 0) { // We deleted last of 2 records m_pSet->MoveFirst(); } else { m_pSet->MoveNext(); } UpdateData(FALSE); } void CEx31bView::OnUpdateRecordDelete(CCmdUI* pCmdUI) { pCmdUI->Enable(!m_pSet->IsEOF()); } void CEx31bView::OnRecordUpdate() { m_pSet->Edit(); UpdateData(TRUE); if (m_pSet->CanUpdate()) { m_pSet->Update(); } // should requery if key field changed } void CEx31bView::OnUpdateRecordUpdate(CCmdUI* pCmdUI) { pCmdUI->Enable(!m_pSet->IsEOF()); }
Trang 224
Vn quan tm
Hiu v bn cht ca ADO v s dng c cc class v truy xut d liu m MFC h tr.
4.2.2
OLEDB l mt tp hp cc giao din truy xut d liu thng qua COM. Cu trc ca OLEDB bao gm: Enumerators: c tc v tm cc ngun d liu kh dng. Data source objects: Data source objects cha cc c ch kt ni ti ngun d liu - mt phin lm vic (session) c to ra khi chng trnh kt ni n mt ngun d liu. Sessions: Sessions th hin mt kt ni(phin lm vic) n ngun d liu c th ngun d liu c th to nhiu sessions. Mi Sessions c th to ra transactions, commands, v rowsets. Transaction: l i tng qun l cc thao tc truy xut d liu v bo m an ton d liu. Commands: l i tng cho php thc thi cc lnh SQL. Nu lnh SQL l lnh SELECT, th i tng ny s to ra (nhn v) rowsets. Mt seesion c th to s dng vi commands. Rowsets: l tp d liu dng bng (tabular). Rowsets c th c to t session hay command. Errors: Errors c th c to ra bi bt k giao din ca i tng OLE DB no. Errors cha cc thng tin v li.
4.2.3
MFC cung cp mt s class gip thao tc vi OLEDB nh: Class Use CDataSource This class represents the data source component and manages the connection to a data source. CEnumerator This class provides a way to select a provider by cycling through a list of providers. Its functionality is equivalent to the SQLBrowseConnect and SQLDriverConnect functions. CSession This class handles transactions. You can use this class to create rowsets, commands, and many other objects. A CDataSource object creates a CSession object using the CSession::Open method CAccessor This class is used when a record is statically bound to a data source it contains the pre-existing data buffer and understands the data format up front. CAccessor is used when you know the structure and the type of the database ahead of time. CDynamicAccessor This class is used for retrieving data from a source whose structure is not known at design time. This class uses Trang 225
Lp trnh Windows vi VC/MFC IColumnsInfo::GetColumnInfo to get the database column information. CDynamicAccessor creates and manages the data buffer. This class is similar to CDynamicAccessor except that it's used with commands. When used to prepare commands, CDynamicParameterAccessor can get parameter information from the ICommandWithParameters interface, which is especially useful for handling unknown command types. This class lets you access whatever data types you want as long as the provider can convert the type. CManualAccessor handles both result columns and command parameters. The CTable class is a minimal class implementation that opens a table on a data source(which you can specify programmatically). Use this class when you need bare-bones access to a source, since CTable is designed for simple providers that do not support commands CCommand is used mostly for executing commands. This class has a function named Open that executes singular commands. This class also has a function named Prepare for setting up a command to execute multiple times Implemented? Yes Yes Yes Yes No No No No Yes Yes Yes Yes No No No No Yes Yes Yes Yes Yes No No No No No No Yes Yes Yes Yes Yes No Yes, through ATL No Yes No
CDynamicParameterAccessor
CManualAccessor CTable
CCommand
Mt s giao din c cung cp tng tc vi OLEDB nh: Interface Required? IDBInitialize Mandatory IDBCreateSession Mandatory IDBProperties Mandatory IPersist Mandatory IDBDataSourceAdmin Optional IDBInfo Optional IPersistFile Optional ISupportErrorInfo Optional IDBInitialize Mandatory IDBCreateSession Mandatory IDBProperties Mandatory IPersist Mandatory IDBDataSourceAdmin Optional IDBInfo Optional IPersistFile Optional ISupportErrorInfo Optional IGetDataSource Mandatory IOpenRowset Mandatory ISessionProperties Mandatory IDBCreateCommand Optional IDBSchemaRowset Optional IIndexDefinition Optional ISupportErrorInfo Optional ITableDefinition Optional ITransactionJoin Optional ITransactionLocal Optional ITransactionObject Optional IAccessor Mandatory IColumnsInfo Mandatory IConvertType Mandatory IRowset Mandatory IRowsetInfo Mandatory IColumnsRowset Optional IConnectionPointContainer Optional IRowsetChange Optional IRowsetIdentity Required for Level 0 IRowsetLocate Optional Trang 226
No No No No
V d 2:
CCommand<CDynamicAccessor, CRowset> dbCommand; try { Recordset20Ptr spRs; ADORecordsetConstructionPtr spADOsCt; CDBPropSet propset(DBPROPSET_ROWSET); propset.AddProperty(DBPROP_CLIENTCURSOR, true); propset.AddProperty(DBPROP_IRowsetChange, true); propset.AddProperty(DBPROP_UPDATABILITY, DBPROPVAL_UP_CHANGE | DBPROPVAL_UP_INSERT | DBPROPVAL_UP_DELETE); CString sCommand; sCommand.Format("SELECT * FROM [%s]", sTableName); HRESULT hr = dbCommand.Create( pMainFrame->m_session,(LPCTSTR)sCommand); if(FAILED(hr)) _com_issue_error(hr); hr = dbCommand.Open(&propset, NULL, true); if(FAILED(hr)) _com_issue_error(hr); hr = spRs.CreateInstance(__uuidof(Recordset)); if(FAILED(hr))
Trang 227
V d 3:
try { CTables tableSet; HRESULT hr = tableSet.Open(pMainFrame->m_session); if(SUCCEEDED(hr)) { CString sName, sNameShort, sSchema; int nPos = -1; HRESULT hr = S_OK; int nIndex = 0; hTreeRoot = GetTreeCtrl().InsertItem("Tables", 0, 0); while(tableSet.MoveNext() == S_OK) { sName = tableSet.m_szName; sNameShort = sName; nPos = sName.Find(';'); if(nPos != -1) sName = sName.Left(nPos); if(sName.Find(' ') != -1) // MS SQL Server scenario sName = "[" + sName + "]"; // Alternatively... sSchema = tableSet.m_szSchema; HTREEITEM hTreeSPRoot = GetTreeCtrl().InsertItem( sName, 1, 1, hTreeRoot); } } else { if(FAILED(hr)) _com_issue_error(hr); } }
Trang 228
Vn quan tm
Hiu v bn cht ca ADO v s dng c cc class v truy xut d liu m MFC h tr.
4.3.2
ADO l mt tp hp cc giao din truy xut d liu thng qua COM (tng t nh OLEDB nhng s dng n gin hn). ADO ng vai tr trung gian tng tc vi chng trnh ng dng v c s d liu, c th hin nh hnh sau:
Connection: l i tng qun l cc tc v truy cp/kt ni c s d liu. Command: l i tng qun l cc tc v cp nht d liu Recordset: l i tng qun l d liu truy vn c Error: l i tng qun l li xy ra
4.3.3
0 Cn thm khai bo v th vin ADO vo hng cui cng ca file StdAfx.h nh sau:
0 Khai bo kt ni n c s d liu:
// Kt ni n Access: m_szConnection="Provider=Microsoft.JET.OLEDB.4.0;Data source=xxx;
v:
// Kt ni tng qut: m_szConnection="File name=xxx;
CString Error = e->ErrorMessage(); AfxMessageBox(e->ErrorMessage()); return FALSE; } catch(...) { AfxMessageBox("Loi bat ky"); return FALSE; }
0 ng kt ni:
if (m_pConnection->GetState() == adStateOpen) m_pConnection->Close(); m_pConnection = NULL;
Trang 230
0 Cp nht d liu:
if (AfxMessageBox("Delete it?", 1,0)!=IDOK) return; if (m_pConnection->GetState() == adStateOpen) { // UpdateData(TRUE); // CString szSQL;
Trang 231
MessageBox("Whoa"); } OnButtonLoad(); }
Trang 232
MyADO.cpp
// MyADO.cpp: implementation of the CMyADO class. ////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <string.h> #include "MyADO.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// // Class Constructor CMyADO::CMyADO() { m_pCommandPtr = NULL; } // Class Destructor CMyADO::~CMyADO() { if( m_pRecordsetPtr ) { if( m_pRecordsetPtr->State == adStateOpen ) m_pRecordsetPtr->Close(); m_pRecordsetPtr = NULL; } m_pCommandPtr = NULL; } //Create a Parameter and Add it to the CommandPtr Object //(Which will be used to Execute the Stored Procedure) HRESULT CMyADO::AddParameter( _bstr_t btParameterName, DataTypeEnum enDataType, ParameterDirectionEnum enParameterDirection, long lSize, _variant_t vtValue ) { HRESULT hReturn = S_FALSE; if( IsConnected() && IsInitialized()) { try
Trang 233
Trang 234
Trang 235
Trang 236
Trang 237
Trang 238
Trang 239
Main.cpp
#include <stdio.h> #include "MyADO.h" void main() { // Initialize COM CoInitialize( NULL ); // Instantiate the Object CMyADO MyADOObject; // Open( ConnectionString, UserID, Password ) the Connection if( MyADOObject.Open( "TestMyADO", "", "" ) == S_OK ) { // Some Example Strings char* pNames[] = { "First Name", "Second Name", "Third Name", "Fourth "Fifth Name", "Sixth Name", "Seventh Name", "Eighth Name", "Nineth Name", Name" }; char* pValues[] = { "Value One", "Value Two", "Value Three", "Value "Value Five", "Value Six", "Value Seven", "Value Eight", "Value Nine", Ten" }; // The Index DWORD dwIndex = 0; // The Insert Loop while( dwIndex < 10 ) { // Initialize( StoredProcedureName ) the Stored Procedure if( MyADOObject.Initialize( "InsertMyADO" ) == S_OK ) { // Add the Return Value Parameter if( MyADOObject.AddParameterReturnValue() == S_OK ) { // Add the Output Long Parameter
Trang 240
Trang 241
Trang 242
Vn quan tm
Hiu cu trc v vai tr ca m hnh COM Khai thc c u im ca COM trong lp trnh ng dng.
5.1.2
L cu trc ng dng m trong cc nhm ng dng c phn chia theo tnh nng v vai tr theo tng lp (tier).
Mi m hnh c tng u/khuyt im khc nhau, c s dng trong cc ng cnh khc nhau.
5.1.3
COM l m hnh i tng thnh phn, c s dng trong cc ng dng 3-lp (hoc n-lp) nhm tng hiu sut hot ng, tnh bo mt ca h thng v tnh linh hot cao. Vi COM, chng ta c th m rng kh nng lin kt v tch hp gia cc thnh phn (c lp ngn ng) trong h thng v bn thn COM c th hin dng m nh phn. C th dng VC++ hay VB to COM, v bt c ng dng no cng c th tng tc vi COM (nu c h tr). T chc v tng tc ca mt component vi mi trng nh sau:
5.1.4
Cu trc COM
COM c t chc di dng tp cc class trong mi class bao gm cc method (hm thnh vin), attribute (bin thnh vin) v cc property. Trang 243
Lp trnh Windows vi VC/MFC Cc method v cc property c nhm vo trong cc interface (giao din) cc interface c (nh l v bc ca cc class) c nhim v giao tip vi cc ng dng khc nhm che du/ngn chn s truy cp trc tip vo cc thnh phn ca class trong COM - ng thi cung cp cc phng thc truy cp cc method v property ny. Microsoft nh ngha sn khong 100 interface h tr cho COM, nhng ngi s dng c th t to interface ring bit.
Mi COM khi to ra lun c sn interface IUnknown v cc method nh: Phng thc M t QueryInterface Returns a pointer to another interface AddRef Increments the object's reference count Release Decrements the object's reference count
v t chc lu tr nh sau:
Mi class trong COM khi to ra cn c class ID (hay CLSID) khai bo vi h thng, gi tr ny c th hin bi chui nh ngha 128-bit, trong thng tin lin quan gm:
Trang 244
V d 1: khi to i tng ca COM, gi hm kch hot CoCreateInstance cng vi CLSID ca i tng , kt qu nhn v l mt pointer qun l ca i tng . V d 2:
Khi to mt COM class c CLSID l CLSID_Object v lin kt ti interface IMath bi pointer pMath IMath* pMath; CoCreateInstance (CLSID_Object, NULL, CLSCTX_SERVER, IID_IMath, (void**) &pMath);
i tng COM c khi to bi thao tc new nhng c t ng hy (m khng dng delete). C th mt interface h tr nhiu truy xut ng thi, s lng truy xut c th c nhn bit v qun l bi mt bin thnh vin v cc s kin AddRef, Release: V d 3:
ULONG __stdcall CComClass::AddRef() { return ++m_lRef; } ULONG __stdcall CComClass::Release() { if (m_lRef == 0) { delete this; return 0; } return m_lRef; }
Trang 245
5.1.5
COM server
Mt file i tng thc thi m hin thc mt i tng COM c gi l COM server. Section HKEY_CLASSES_ROOT\CLSID trong registry s cha cc thng tin v CLSID v cc i tng thc thi lin quan. V d 5:
Nu server file l MathSvr.exe hin thc cho i tng Math objects, v ngI dng gI CoCreateInstance vI CLSID ca Math, th COM s tm CLSID trong registry, v ly c ng dn ca MathSvr.exe ri thc thi file EXE ny.
C 2 kiu COM-server l: in-process: l COM c dng file l DLL, khi hot ng th c np (ct/lu) trong cng khng gian a ch ca ng dng client ti u hn trong hin thc. out-of-process: l COM c dng file l EXE, khi hot ng th c np vo mt khng gian a ch khc vi ng dng client c khuyt im l nh hng n tc thc thi ca ng dng. M hnh DCOM (Distributed COM) c gii thiu vi m hnh dng out-of-process chy t do trn cc my server ca mi trng mng.
Mt u im ca COM l tnh cht trong sut v tr (Location Transparency), tc l chng trnh client khng quan tm n v tr ca cc object ca COM, v COM s qun l tt c thao tc h tr vic kt ni ny. Vic tng tc ny th hin qua cu trc proxy/stub m COM h tr sn.
Trang 246
5.1.6
MFC v COM
Trang 247
hay:
*ppv = (ISpelling*) this;
v:
Trang 248
Trang 249
Trang 250
trong cc giao din thnh phn nh sau: Interface Comments IConnectionPointContainer Exposes connection points for event interfaces IDataObject Makes presentation data available to the control container IDispatch Exposes the control's methods and properties IOleCache Controls the presentation data cache IOleControl Base interface for ActiveX controls IOleInPlaceActiveObject Base interface for embedded objects that support in-place activation IOleInPlaceObjectWindowless Allows the container to manage the activation and deactivation of both windowed and windowless controls IOleObject Base interface for embedded objects IQuickActivate Speeds control creation in containers that recognize this interface IPerPropertyBrowsing Allows containers to acquire information about control properties, such as each property's name IPersistMemory Allows the control to write property values to memory and read them back IPersistPropertyBag Allows the control to save property values in "property bag" objects provided by the container IPersistStorage Allows the control to save property values in storage objects IPersistStreamInit Allows the control to save property values in stream objects Trang 251
Lp trnh Windows vi VC/MFC IProvideClassInfo2 ISpecifyPropertyPages IViewObjectEx T chc lp cha v s kin nh sau: Makes type information available to the control container Allows the control to add pages to property sheets displayed by the container Allows the container to acquire images of inactive controls and paint windowless controls
Comments Base interface for embedding containers Base interface for OLE containers that support in-place activation Base interface for OLE containers Base interface for OLE containers that support in-place activation Base interface for ActiveX control sites Exposes the container's ambient properties Traps events fired by a control Allows the control to notify the container about property changes and to ask permission before changing them Description Called to paint the control. Override to add control-specific painting logic. Called to save or load a control's persistent properties. Override to support persistent control properties. Description Retrieves an ambient property value from the container (for example, AmbientBackColor) Fires a stock event (for example, FireClick) Retrieves the values of an ambient property for which no Ambientxxx function is defined Retrieves the value of a stock property (for example, GetBackColor) Makes the IDs of the control's event interface and IDispatch interface known to MFC; normally called from the class constructor Repaints the control Serializes the control's stock properties Marks the control as dirty or not dirty (A "dirty" control is one that contains unsaved property changes.) Generates an error when a client attempts to write to a read-only property
Cc hm h tr trong lp COleControl nh sau: Function Ambientxxx Firexxx GetAmbientProperty Getxxx InitializeIIDs InvalidateControl SerializeStockProps SetModifiedFlag SetNotSupported Trang 252
ThrowError TranslateColor
Signals that an error occurred; used in method implementations and property accessor functions Translates an OLE_COLOR value into a COLORREF value
Thao tc to ActiveX Control: B1: Chn loi ActiveX Control v thc hin cc bc yu cu nh hnh sau y
v:
v:
Trang 253
Trang 254
CalendarCtl.cpp
// CalendarCtl.cpp : Implementation of the // CCalendarCtrl ActiveX Control class. #include #include #include #include "stdafx.h" "Calendar.h" "CalendarCtl.h" "CalendarPpg.h"
#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CCalendarCtrl, COleControl)
Trang 255
Trang 256
Trang 257
Trang 258
Trang 259
Trang 260
Mn hnh kt qu:
v:
v:
Trang 261
ng k OCX:
Regsvr32 Calendar.ocx
Hy ng k:
Regsvr32 /U Calendar.ocx
Trang 262
Trang 263
d. e.
f. g. h. i.
Tm hiu cc thnh phn View/Document ca project ExSDI. Kt hp vi s h tr ca cc lp CArray, hy x l sao cho khi nhp thng tin v nhn button Add th thng tin ny s c lu vo b nh, tng t cho php cp nht, xa hay reset khi nhn vo cc button Edit/Delete hay Reset. X l tng t vi cc button First/Previous/Next/Last cho php hin th cc mu tin mong mun. Thm 1 editbox (t ID l IDC_EDIT_NUMBER) Cp nht li chng trnh sao cho khi bm di chuyn n mu tin no th s th t mu tin s hin ra tng ng trong editbox cu g. Lp li cc bc (e) n (f) vi CList.
b. c. d.
e.
f.
Thc hin thao tc lu danh sch Product ang c vo file c tn ProductList.dat khi bm nt Save File Thc hin thao tc lu ni dung ang c trong file ProductList.dat vo danh sch Product khi bm nt Load File Thc hin vic by li vi c ch trycatch, xut thng bo li(trong trng hp c li), xut thng bo Du lieu duoc luu xong (trong trng hp Add/Edit), xut thng bo Ban muon xoa du lieu khong? (trong trng hp va bm Delete) v xut thng bo Du lieu duoc xoa xong (sau khi thc hin Delete xong) To Toolbar (nu cha c) hay thm vo Toolbar hin hnh cc biu tng tng ng vi cc button c (Add/Edit/Delete/Save File,First/Previous/Next/Last) sao cho chng thc thi tng t nh khi bm cc button c ny. Thc hin tng t cu (c) nhng hin thng bo ra StatusBar pha di.
Trang 264
v combo-box c ID l IDC_COMBO_CATEGORY c. Truy cp c s d liu Northwind (dng Access hay SQL Server nu c) : Trong property page (tab) Maintain Product, thc hin np d liu t bng Categories vo combo-box(dropdown listbox) Category Name sao cho CategoryID c lu ngm v CategoryName hin ln trong combo-box Trong property page (tab) Maintain Product, thc hin tng t cu (e) v (f) ca bi 3 nhng truy xut trc tip c s d liu. Trang 265
Lp trnh Windows vi VC/MFC Trong property page (tab) Search Product, thc hin vic tm kim khi bm button Search v xut kt qu ra danh sch Result bn di.
b.
Xy dng chng trnh qun l ni dung lch hp ca nhn vin trong 1 c quan (khng dng COM) c giao din ty chn (giao din xy dng ty )
Trang 266
CHNG 7. BI TP TNG HP
7.1 Bi 1
Thc hin chng trnh tng t nh ng dng Windows Explorer.
7.2 Bi 2
Thc hin chng trnh tng t nh ng dng Microsoft Internet Explorer.
7.3 Bi 3
a. Xem cu trc ca c s d liu ContactManagement trong file Access
Xy dng chng trnh ng dng dng SDI trong c menu Tools bao gm cc lnh (menu item) theo cu trc sau sau: Tools |- Enter-View Contacts |- Enter-View Contact Types sao cho khi bm vo tng lnh s m cc form tng ng (mn hnh nh cu 3 v 5) c. Xy dng form Contacts c dng property sheet nh hnh sau:
b.
Trang 267
Lp trnh Windows vi VC/MFC d. Thc hin truy xut c s d liu ContactManagement v lm cc thao tc sau: i) Cho php tm kim d liu Contact ii) Cho php xem thng tin ca Contact iii) Cho php thm, cp nhp, xo contact. Cho php reset mn hnh. Cho php thc hin di chuyn first, last, next, previous xem thng tin Contact. Thc hin tng t cu 3, 4 to form cho php nhp d liu cho ContactType vi mn hnh nh sau:
e.
7.4 Bi 4
a. Xem cu trc ca c s d liu ContactManagement trong file Access
b.
Xy dng chng trnh ng dng dng SDI trong c menu Tools bao gm cc lnh (menu item) theo cu trc sau sau: Tools |- Enter-View Candidates |- Enter-View Interview Progress Xy dng chng trnh qun l cc ng vin v qu trnh phng vn tuyn dng ca cng ty ABC (da theo bi tng hp s 3).
c.
7.5 Bi 5
Vit chng trnh MyPainBrush, tng t nh ng dng PainBrush ca Windows.
7.6 Bi 6
Vit chng trnh MyGraph h tr v th ca mt ng bc nht (dng y=ax+b) hay bc hai (dng y=ax2+bx+c), dng y=(ax+b)/(cx+d), dng y=(ax2+bx+c)/(dx+e) vi cc gi tr a, b, c, ... do ngi dng nhp vo.
7.7 Bi 7
Vit chng trnh MyPainBrush, tng t nh ng dng WordPad ca Windows.
Trang 268
0.1 n tp C .............................................................................................................................................. 2 0.1.1 Kiu d liu, bin v chuyn i kiu ............................................................................................ 2 0.2 Hm v li gi hm ............................................................................................................................. 2 0.2.1 Pht biu iu khin ....................................................................................................................... 2 0.2.2 Array............................................................................................................................................... 2 0.2.3 Pointer............................................................................................................................................. 2 0.2.4 File.................................................................................................................................................. 2 0.2.5 Debug by li............................................................................................................................... 2 0.3 n tp C++ .......................................................................................................................................... 2 0.3.1 Class ............................................................................................................................................... 2 0.3.2 Cu trc tha k .............................................................................................................................. 2 0.3.3 Tm vc truy xut........................................................................................................................... 2 0.3.4 Object ............................................................................................................................................. 2
Lp trnh Windows vi VC/MFC 1.5.1 Vn quan tm ...........................................................................................................................37 1.5.2 Lp CFile ......................................................................................................................................37 1.5.3 Chui ho v CArchive.................................................................................................................38 1.6 CC LP MFC CA CC IU KHIN WINDOWS. .................................................................42 1.6.1 Vn quan tm ...........................................................................................................................42 1.6.2 Cc loi iu khin........................................................................................................................42 1.6.3 Loi CButton.................................................................................................................................43 1.7 DIALOG BOX, COMMON DIALOG V PROPERTY SHEET.....................................................43 1.7.1 Vn quan tm ...........................................................................................................................43 1.7.2 Hp thoi (dialog) .........................................................................................................................43 1.7.3 Cc hp thoi thng dng (Common Dialog Classes) ..................................................................45 1.7.4 Property Sheet/Property Page .......................................................................................................46 1.8 Mt s iu khin trong Windows 9.x*.............................................................................................58 1.8.1 Cc loi iu khin........................................................................................................................58 1.8.2 V d tng hp: ............................................................................................................................. 59 1.8.2.1 Chng trnh 1: ...................................................................................................................59 1.8.2.2 Chng trnh 2: ...................................................................................................................66
CHNG 3. X L H THNG
177
3.1 TIMER/IDLE................................................................................................................................... 177 3.1.1 Vn quan tm ......................................................................................................................... 177 3.1.2 Timer........................................................................................................................................... 177 3.1.3 Idles............................................................................................................................................. 178 3.2 THREADS....................................................................................................................................... 187 3.2.1 Vn quan tm ......................................................................................................................... 187 3.2.2 Gii thiu .................................................................................................................................... 187 3.2.3 Threads ....................................................................................................................................... 187 3.2.4 ng b cc threads(Thread Synchronization)........................................................................... 196
Lp trnh Windows vi VC/MFC 4.1.2 Gii thiu.................................................................................................................................... 214 4.1.3 V d tng hp ............................................................................................................................ 218 4.1.3.1 Chng trnh 1: ................................................................................................................. 218 4.1.3.2 Chng trnh 2: ................................................................................................................. 221 4.2 TRUY XUT VI OLEDB............................................................................................................ 225 4.2.1 Vn quan tm ......................................................................................................................... 225 4.2.2 Gii thiu OLEDB...................................................................................................................... 225 4.2.3 Thc hin tc v truy xut d liu vi OLEDB: ........................................................................ 225 4.3 TRUY XUT VI ADO ................................................................................................................ 229 4.3.1 Vn quan tm ......................................................................................................................... 229 4.3.2 Gii thiu ADO .......................................................................................................................... 229 4.3.3 Thc hin truy xut c s d liu vi ADO: .............................................................................. 229
243
5.1 COMPONENT OBJECT MODEL (COM)..................................................................................... 243 5.1.1 Vn quan tm ......................................................................................................................... 243 5.1.2 Gii thiu m hnh 3-lp v n-lp .............................................................................................. 243 5.1.3 Gii thiu COM.......................................................................................................................... 243 5.1.4 Cu trc COM ............................................................................................................................ 243 5.1.5 COM server ................................................................................................................................ 246 5.1.6 MFC v COM............................................................................................................................. 247 5.2 ACTIVE X CONTROL................................................................................................................... 250
263
Bi thc hnh 1................................................................................................................................ 263 Bi thc hnh 2................................................................................................................................ 263 Bi thc hnh 3................................................................................................................................ 263 Bi thc hnh 4................................................................................................................................ 264 Bi thc hnh 5................................................................................................................................ 265 Bi thc hnh 6................................................................................................................................ 265 Bi thc hnh 7................................................................................................................................ 266 Bi thc hnh 8................................................................................................................................ 266 Bi thc hnh 9................................................................................................................................ 266 Bi thc hnh 10.............................................................................................................................. 266
CHNG 7. BI TP TNG HP
267
Bi 1 ................................................................................................................................................ 267 Bi 2 ................................................................................................................................................ 267 Bi 3 ................................................................................................................................................ 267 Bi 4 ................................................................................................................................................ 268 Bi 5 ................................................................................................................................................ 268 Bi 6 ................................................................................................................................................ 268 Bi 7 ................................................................................................................................................ 268
Trang 271