CCtrlView
Base class for CEditView, CRichEditView, CListView, and CTreeView; can be used to create view classes based on other types of controls
Scroll Views
Override OnInitialUpdate in the view class, and call SetScrollSizes to specify the view's logical dimensions.
CScrollView::SetScrollSizes( ... )
An integer specifying the mapping mode (required)
A SIZE structure or CSize object specifying the view's logical dimensions (required)
A SIZE structure or CSize object specifying the page size—the amount by which MFC scrolls the view when the scroll bar shaft is clicked (optional)
A SIZE structure or CSize object specifying the line size—the amount by which MFC scrolls the view when the scroll bar arrows are clicked (optional)
Exam:
void CMyView::OnInitialUpdate ()
{
CScrollView::OnInitialUpdate ();
SetScrollSizes (MM_LOENGLISH, CSize (850, 1100),
CSize (200, 200), CSize (25, 25));
}
When OnDraw is called, the mapping mode has already been set to the one specified in the call to SetScrollSizes. Therefore, you needn't call SetMapMode yourself when you implement OnDraw.
If you draw in the view outside of OnDraw, call CScrollView::OnPrepareDC to allow MFC to factor the mapping mode and scroll position into the output.
CClientDC dc (this);
OnPrepareDC (&dc);
// Draw something with dc.
If you do any hit-testing in response to mouse messages, use CDC::DPtoLP to convert the click coordinates from device coordinates to logical coordinates to factor the mapping mode and scroll position into the hit-test.
void CMyView::OnLButtonDown (UINT nFlags, CPoint point)
{
CPoint pos = point;
CClientDC dc (this);
OnPrepareDC (&dc);
dc.DPtoLP (&pos);
CSize size = GetTotalSize ();
if (::abs (pos.y) < (size.cy / 2)) {
// Upper half was clicked.
}
else {
// Lower half was clicked.
}
}
Before it calls OnDraw, CView::OnPaint calls the virtual OnPrepareDC function. CScrollView overrides OnPrepareDC and in it calls CDC::SetMapMode to set the mapping mode and CDC::SetViewportOrg to translate the viewport origin an amount that equals the horizontal and vertical scroll positions.
CScrollView Operations
CPoint pos = GetScrollPosition ();
ScrollToPosition (CPoint (100, 100));
CSize size = GetTotalSize ();
int nWidth = size.cx;
int nHeight = size.cy;
SetScaleToFitSize (GetTotalSize ());
Optimizing Scrolling Performance
"works" and "performs acceptably" are two different things.
The key to optimizing OnDraw is a CDC function named GetClipBox
CRect rect;
pDC->GetClipBox (&rect);
How you use this information is highly application-specific.
HTML Views
Function | Description |
---|---|
GetBusy | Indicates whether a download is in progress |
GetLocationName | If an HTML page is displayed, retrieves the page's title; if a file or folder is currently displayed, retrieves the file or folder name |
GetLocationURL | Retrieves the URL of the resource that is currently displayed—for example, http://www.microsoft.com/ or file://C:/HTML Files/Clock.htm |
GoBack | Goes to the previous item in the history list |
GoForward | Goes to the next item in the history list |
Navigate | Displays the resource at the specified URL |
Refresh | Reloads the resource that is currently displayed |
Stop | Stops loading a resource |
Navigate2 does everything Navigate does and more. Because it will accept pointers to ITEMIDLIST structures in lieu of path names, Navigate2 can be used to access objects anywhere in the shell's namespace. Navigate, by contrast, is limited to file system objects only.
Function | Description |
---|---|
OnNavigateComplete2 | Called after navigating to a new URL |
OnBeforeNavigate2 | Called before navigating to a new URL |
OnProgressChange | Called to provide an update on the status of a download |
OnDownloadBegin | Called to indicate that a download is about to begin |
OnDownloadComplete | Called to indicate that a download is complete |
OnTitleChange | Called when the document title changes |
OnDocumentComplete | Called to indicate that a document was successfully downloaded |
OnProgressChange receives two parameters: a long specifying the number of bytes downloaded thus far and a long specifying the number of bytes to be downloaded. Dividing the first by the second and multiplying by 100 yields a percentage-done figure that can be displayed in a progress bar or other control. A call to OnProgressChange with a first parameter equal to -1 or a pair of 0 parameters is another indication that a download is complete.
Tree Views
UINT nCount = GetTreeCtrl ().GetCount ();
This paradigm—call a member function of the view to acquire a reference to the corresponding control—is shared by all of MFC's CCtrlView-derived classes.
Tree View Styles
You can apply any of the supported styles to a tree view by ORing them into the style field of the CREATESTRUCT structure passed to PreCreateWindow.
Style | Description |
---|---|
TVS_HASLINES | Adds lines connecting subitems to their parents. |
TVS_LINESATROOT | Adds lines connecting items at the top level, or root, of the hierarchy. This style is valid only if TVS_HASLINES is also specified. |
TVS_HASBUTTONS | Adds buttons containing plus or minus signs to items that have subitems. Clicking a button expands or collapses the associated subtree. |
TVS_EDITLABELS | Enables in-place label editing notifications. |
TVS_DISABLEDRAGDROP | Disables drag-and-drop notifications. |
TVS_SHOWSELALWAYS | 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. |
CImageList il;
il.Create (IDB_IMAGES, 16, 1, RGB (255, 0, 255));
GetTreeCtrl ().SetImageList (&il, TVSIL_NORMAL);
CTreeCtrl::InsertItem adds an item to a tree view control. Items are identified by HTREEITEM handles, and one of the parameters input to InsertItem is the HTREEITEM handle of the item's parent. A subitem is created when an item is added to a tree view and parented to another item. Root items—items in the uppermost level of the tree—are created by specifying TVI_ROOT as the parent.
Tree View Member Functions and Notifications
DeleteItem
DeleteAllItems
SetItemText
GetItemText
SortChildren
CTreeCtrl::GetSelectedItem
GetParentItem,
GetChildItem,
GetNextItem,
GetNextSiblingItem, and so on.
Notification | Sent When |
---|---|
TVN_BEGINDRAG | A drag-and-drop operation is begun with the left mouse button. Not sent if the control has the style TVS_DISABLEDRAGDROP. |
TVN_BEGINRDRAG | A drag-and-drop operation is begun with the right mouse button. Not sent if the control has the style TVS_DISABLEDRAGDROP. |
TVN_BEGINLABELEDIT | A label editing operation is begun. Sent only if the control has the style TVS_EDITLABELS. |
TVN_ENDLABELEDIT | A label editing operation is completed. Sent only if the control has the style TVS_EDITLABELS. |
TVN_GETDISPINFO | The control needs additional information to display an item. Sent if the item text is LPSTR_TEXTCALLBACK or the image index is I_IMAGECALLBACK. |
TVN_DELETEITEM | An item is deleted. |
TVN_ITEMEXPANDED | A subtree has expanded or collapsed. |
TVN_ITEMEXPANDING | A subtree is about to expand or collapse. |
TVN_KEYDOWN | A key is pressed while the control has the input focus. |
TVN_SELCHANGED | The selection has changed. |
TVN_SELCHANGING | The selection is about to change. |
TVN_SETDISPINFO | The information in a TV_DISPINFO structure needs to be updated. |
ON_NOTIFY_REFLECT entry in the message map reflects TVN_ITEMEXPANDING notifications so that CDriveView can handle them itself.
Removing the document name in the frame window class.
CMainFrame::PreCreateWindow( ... ){
cs.style &= ~FWS_ADDTOTITLE;
}
List Views
CListView::GetListCtrl()
Initializing a List View
override PreCreateWindow in the derived class and apply one or more default styles to the view
Style Description 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. LVS_ALIGNTOP Aligns items along the top border in large and small icon mode. LVS_AUTOARRANGE Automatically arranges items in rows and columns in large and small icon mode. LVS_EDITLABELS Enables in-place label editing notifications. LVS_NOLABELWRAP Restricts labels to single lines in large icon mode. LVS_NOSCROLL Disables scrolling. Scrolling is enabled by default. LVS_OWNERDRAWFIXED Specifies that the control's owner will draw the items in response to WM_DRAWITEM messages. LVS_SHAREIMAGELISTS Prevents a list view from automatically deleting the image lists associated with it when the view itself is deleted. LVS_SINGLESEL Disables multiple-selection support. LVS_SHOWSELALWAYS Specifies that the selected items should always be highlighted. By default, the highlight is removed when the view loses the input focus. LVS_SORTASCENDING Specifies that items should be sorted in ascending order (for example, A through Z). LVS_SORTDESCENDING Specifies that items should be sorted in descending order (for example, Z through A). Initialization is a five-step process:
- Create a pair of image lists containing images for the list view items.
- Use CListCtrl::SetImageList to associate the image lists with the list view control. Pass SetImageList an LVSIL_NORMAL flag for the image list containing large images and an LVSIL_SMALL flag for the image list containing small images.
- Add columns to the list view control with CListCtrl::InsertColumn. The leftmost column displays the items added to the control. The columns to the right display subitems and are visible only in report mode.
- Add items to the control with CListCtrl::InsertItem.
- Assign text strings to the item's subitems with CListCtrl::SetItemText.
You can base column widths on the widths of characters in the control font by using CListCtrl::GetStringWidth to convert text strings into pixel counts
Changing the Presentation Style
CWnd::ModifyStyle (LVS_TYPEMASK, LVS_SMALLICON);
ModifyStyle (LVS_TYPEMASK, LVS_REPORT);LVS_ICON, LVS_SMALLICON, LVS_LIST, and LVS_REPORT aren't true bit flags, so LVS_TYPEMASK also comes in handy when you query a list view to determine its current presentation style.
DWORD dwStyle = GetStyle () & LVS_TYPEMASK; if (dwStyle == LVS_ICON) // Large icon mode. else if (dwStyle == LVS_SMALLICON) // Small icon mode. else if (dwStyle == LVS_LIST) // List mode. else if (dwStyle == LVS_REPORT) // Report mode.Sorting in a List View
Do-It-Yourself Control Views
The key features of this class are the default constructor, which passes the base class's constructor the name of the tab control's WNDCLASS ("SysTabControl32"); the GetTabCtrl function, which returns a reference to the underlying tab control; and OnInitialUpdate, which adds three tabs to the control. PreCreateWindow also plays an important role by initializing the common controls library and applying default styles to the control.
LVN_COLUMNCLICK
lParam >> NM_LISTVIEW
CListCtrl::SortItems()
CALL BACK 比较函数
CListCtrl::SetItemData() [x]
LPSTR_TEXTCALLBACK
LVN_GETDISPINFO
Hit-Testing in a List View
CListCtrl::HitTest to perform hit-testing on the items in a list view. Given the coordinates of a point, HitTest returns the index of the item at that point or at -1 if the point doesn't correspond to an item.
一些函数和算法:
1. Win32 ::GetLogical- Drives
2. ::GetDriveType()
Return Value Meaning DRIVE_UNKNOWN The drive type is unknown. DRIVE_NO_ROOT_DIR The drive lacks a root directory. DRIVE_REMOVABLE The drive is removable (returned for floppy drives and other removable-media drives such as Zip drives). DRIVE_FIXED The drive is fixed (returned for hard disks). DRIVE_REMOTE The drive is remote (returned for network drives). DRIVE_CDROM The drive is a CD-ROM drive. DRIVE_RAMDISK The drive is a RAM disk. 3. Enum folders:
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;
}4.void CMyListView::OnDoubleClick (NMHDR* pnmh, LRESULT* pResult)
{
DWORD dwPos = ::GetMessagePos ();
CPoint point ((int) LOWORD (dwPos), (int) HIWORD (dwPos));
GetListCtrl ().ScreenToClient (&point);
int nIndex;
if ((nIndex = GetListCtrl ().HitTest (point)) != -1) {
CString string = GetListCtrl ().GetItemText (nIndex, 0);
TRACE (_T ("%s was double-clicked/n"), string);
}
*pResult = 0;
}