Programming Windows with MFC - Capter 10. Scroll Views, HTML Views, and Other View Types

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   

CHtmlView Operations

FunctionDescription
GetBusyIndicates whether a download is in progress
GetLocationNameIf an HTML page is displayed, retrieves the page's title; if a file or folder is currently displayed, retrieves the file or folder name
GetLocationURLRetrieves 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
NavigateDisplays the resource at the specified URL
RefreshReloads the resource that is currently displayed
StopStops 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.

CHtmlView Overridables

Function Description
OnNavigateComplete2Called after navigating to a new URL
OnBeforeNavigate2 Called before navigating to a new URL
OnProgressChangeCalled to provide an update on the status of a download
OnDownloadBeginCalled to indicate that a download is about to begin
OnDownloadCompleteCalled 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.

StyleDescription
TVS_HASLINESAdds lines connecting subitems to their parents.
TVS_LINESATROOTAdds lines connecting items at the top level, or root, of the hierarchy. This style is valid only if TVS_HASLINES is also specified.
TVS_HASBUTTONSAdds 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_DISABLEDRAGDROPDisables drag-and-drop notifications.
TVS_SHOWSELALWAYSSpecifies 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.

NotificationSent When
TVN_BEGINDRAGA drag-and-drop operation is begun with the left mouse button. Not sent if the control has the style TVS_DISABLEDRAGDROP.
TVN_BEGINRDRAGA 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_GETDISPINFOThe control needs additional information to display an item. Sent if the item text is LPSTR_TEXTCALLBACK or the image index is I_IMAGECALLBACK.
TVN_DELETEITEMAn 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_SELCHANGEDThe 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

StyleDescription
LVS_ICON Selects large icon mode.
LVS_SMALLICONSelects 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_ALIGNTOPAligns items along the top border in large and small icon mode.
LVS_AUTOARRANGEAutomatically arranges items in rows and columns in large and small icon mode.
LVS_EDITLABELSEnables 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_OWNERDRAWFIXEDSpecifies 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_SORTASCENDINGSpecifies 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:

  1. Create a pair of image lists containing images for the list view items.
     
  2. 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.
     
  3. 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.
     
  4. Add items to the control with CListCtrl::InsertItem.
     
  5. 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_RAMDISKThe 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;
}


 


 


   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值