ListControl

纵然是瞬间 提交于 2020-03-08 11:10:08

一、基本使用

1.新加ListControl 控件,属性中的style属性页下的View选择Report。

并设置其对应的控制变量如:m_list1。


2.初始化,即设置列。     用m_list1。

 m_list1.InsertColumn(0,"曲名");         //插入列

 m_list1.InsertColumn(1,"类型");

 m_list1.InsertColumn(2,"长度");

 m_list1.InsertColumn(3,"路径");


 CRect rect4;

 m_list1.GetClientRect(rect4);                    //获得当前客户区信息

 m_list1.SetColumnWidth(0,rect4.Width()/4);       //设置列的宽度。

 m_list1.SetColumnWidth(1,rect4.Width()/5);

 m_list1.SetColumnWidth(2,rect4.Width()/5);

 m_list1.SetColumnWidth(3,rect4.Width()*8/20);


 这部分初始化操作,最好放在对话框类的OnInitDialog()函数里,自动初始化。


3.插入数据

        m_list1.InsertItem(0,"大海");      //插入第一个数据,即第0条数据。先插入,然后在修改其他的信息。

        m_list1.SetItemText(0,1,"MP3");    //修改第0条数据的其他信息。

        m_list1.SetItemText(0,2,"4:20");

        m_list1.SetItemText(0,3,"c:\");


4.删除所有数据

        m_list1.DeleteAllItems();

      

       

        

        

二、其他技巧


1.如何设置ListView控件的完全行(Full Row)选项。

    这个控件有个地方常常很恼人,那就是在报告视图中选中一行时,它只加亮最左边的一个栏目。

    为了克服这个问题,这里告诉你一个方法:向ListView控件发送一个LVM_SETEXTENDEDLISTVIEWSTYLE消息。

::SendMessage(m_list1.m_hWnd, LVM_SETEXTENDEDLISTVIEWSTYLE,LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT);

1. ListCtrl 风格
      LVS_ICON: 为每个item显示大图标
      LVS_SMALLICON: 为每个item显示小图标
      LVS_LIST: 显示一列带有小图标的item
      LVS_REPORT: 显示item详细资料
      直观的理解:windows资源管理器,“查看”标签下的“大图标,小图标,列表,详细资料”
--------------------------------------------------------------------------------
2. 设置listctrl 风格及扩展风格
      LONG lStyle;
      lStyle = GetWindowLong(m_list.m_hWnd, GWL_STYLE);//获取当前窗口style
      lStyle &= ~LVS_TYPEMASK; //清除显示方式位
      lStyle |= LVS_REPORT; //设置style
      SetWindowLong(m_list.m_hWnd, GWL_STYLE, lStyle);//设置style

      DWORD dwStyle = m_list.GetExtendedStyle();
      dwStyle |= LVS_EX_FULLROWSELECT;//选中某行使整行高亮(只适用与report风格的listctrl)
      dwStyle |= LVS_EX_GRIDLINES;//网格线(只适用与report风格的listctrl)
      dwStyle |= LVS_EX_CHECKBOXES;//item前生成checkbox控件
      m_list.SetExtendedStyle(dwStyle); //设置扩展风格
--------------------------------------------------------------------------------
3. 插入数据
      m_list.InsertColumn( 0, "ID", LVCFMT_LEFT, 40 );//插入列
      m_list.InsertColumn( 1, "NAME", LVCFMT_LEFT, 50 );
      int nRow = m_list.InsertItem(0, “11”);//插入行
      m_list.SetItemText(nRow, 1, “jacky”);//设置数据
--------------------------------------------------------------------------------
4. 一直选中item
    选中style中的Show selection always,或者在上面第2点中设置LVS_SHOWSELALWAYS
--------------------------------------------------------------------------------
5. 选中和取消选中一行
    int nIndex = 0;
    //选中
    m_list.SetItemState(nIndex, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
    //取消选中
    m_list.SetItemState(nIndex, 0, LVIS_SELECTED|LVIS_FOCUSED);

--------------------------------------------------------------------------------
6. 得到listctrl中所有行的checkbox的状态
      m_list.SetExtendedStyle(LVS_EX_CHECKBOXES);
      CString str;
      for(int i=0; i<m_list.GetItemCount(); i )
      {
           if( m_list.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED || m_list.GetCheck(i))
           {
                str.Format(_T("第%d行的checkbox为选中状态"), i);
                AfxMessageBox(str);
           }
      }

CString strIns;
strIns="delete from tmpStatByGround";
m_pRs.CreateInstance(__uuidof(Recordset));
m_pRs->CursorLocation = adUseClient;
m_pRs->Open((LPCTSTR)strIns, vDispatch, adOpenKeyset,
adLockOptimistic, adCmdUnknown);

--------------------------------------------------------------------------------
7. 得到listctrl中所有选中行的序号
      方法一:
      CString str;
      for(int i=0; i<m_list.GetItemCount(); i )
      {
           if( m_list.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED )
           {
                str.Format(_T("选中了第%d行"), i);
                AfxMessageBox(str);
           }
      }
      方法二:
      POSITION pos = m_list.GetFirstSelectedItemPosition();
      if (pos == NULL)
           TRACE0("No items were selected!\n");
      else
      {
           while (pos)
           {
                int nItem = m_list.GetNextSelectedItem(pos);
                TRACE1("Item %d was selected!\n", nItem);
                // you could do your own processing on nItem here
           }
      }
--------------------------------------------------------------------------------
8. 得到item的信息
      TCHAR szBuf[1024];
      LVITEM lvi;
      lvi.iItem = nItemIndex;
      lvi.iSubItem = 0;
      lvi.mask = LVIF_TEXT;
      lvi.pszText = szBuf;
      lvi.cchTextMax = 1024;
      m_list.GetItem(&lvi);
--------------------------------------------------------------------------------
9. 得到listctrl的所有列的header字符串内容
      LVCOLUMN lvcol;
      char  str[256];
      int   nColNum;
      CString  strColumnName[4];//假如有4列
      nColNum = 0;
      lvcol.mask = LVCF_TEXT;
      lvcol.pszText = str;
      lvcol.cchTextMax = 256;
      while(m_list.GetColumn(nColNum, &lvcol))
      {
           strColumnName[nColNum] = lvcol.pszText;
           nColNum ;
      }
--------------------------------------------------------------------------------
10. 使listctrl中一项可见,即滚动滚动条
    m_list.EnsureVisible(i, FALSE);
--------------------------------------------------------------------------------
11. 得到listctrl列数
    int nHeadNum = m_list.GetHeaderCtrl()->GetItemCount();
--------------------------------------------------------------------------------
12. 删除所有列
      方法一:
         while ( m_list.DeleteColumn (0))
       因为你删除了第一列后,后面的列会依次向上移动。
      方法二:
      int nColumns = 4;
      for (int i=nColumns-1; i>=0; i--)
          m_list.DeleteColumn (i);
--------------------------------------------------------------------------------
13. 得到单击的listctrl的行列号
      添加listctrl控件的NM_CLICK消息相应函数
      void CTest6Dlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
      {
           // 方法一:
           /*
           DWORD dwPos = GetMessagePos();
           CPoint point( LOWORD(dwPos), HIWORD(dwPos) );
  
           m_list.ScreenToClient(&point);
  
           LVHITTESTINFO lvinfo;
           lvinfo.pt = point;
           lvinfo.flags = LVHT_ABOVE;
    
           int nItem = m_list.SubItemHitTest(&lvinfo);
           if(nItem != -1)
           {
                CString strtemp;
                strtemp.Format("单击的是第%d行第%d列", lvinfo.iItem, lvinfo.iSubItem);
                AfxMessageBox(strtemp);
           }
          */
  
          // 方法二:
          /*
           NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
           if(pNMListView->iItem != -1)
           {
                CString strtemp;
                strtemp.Format("单击的是第%d行第%d列",
                                pNMListView->iItem, pNMListView->iSubItem);
                AfxMessageBox(strtemp);
           }
          */
           *pResult = 0;
      }
--------------------------------------------------------------------------------
14. 判断是否点击在listctrl的checkbox上
      添加listctrl控件的NM_CLICK消息相应函数
      void CTest6Dlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
      {
           DWORD dwPos = GetMessagePos();
           CPoint point( LOWORD(dwPos), HIWORD(dwPos) );
  
           m_list.ScreenToClient(&point);
  
           LVHITTESTINFO lvinfo;
           lvinfo.pt = point;
           lvinfo.flags = LVHT_ABOVE;
    
           UINT nFlag;
           int nItem = m_list.HitTest(point, &nFlag);
           //判断是否点在checkbox上
           if(nFlag == LVHT_ONITEMSTATEICON)
           {
                AfxMessageBox("点在listctrl的checkbox上");
           }
           *pResult = 0;
      }
--------------------------------------------------------------------------------
15. 右键点击listctrl的item弹出菜单
      添加listctrl控件的NM_RCLICK消息相应函数
      void CTest6Dlg::OnRclickList1(NMHDR* pNMHDR, LRESULT* pResult)
      {
           NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
           if(pNMListView->iItem != -1)
           {
                DWORD dwPos = GetMessagePos();
                CPoint point( LOWORD(dwPos), HIWORD(dwPos) );
   
                CMenu menu;
                VERIFY( menu.LoadMenu( IDR_MENU1 ) );
                CMenu* popup = menu.GetSubMenu(0);
                ASSERT( popup != NULL );
                popup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this );
           }
           *pResult = 0;
  }
--------------------------------------------------------------------------------
16. item切换焦点时(包括用键盘和鼠标切换item时),状态的一些变化顺序
      添加listctrl控件的LVN_ITEMCHANGED消息相应函数
      void CTest6Dlg::OnItemchangedList1(NMHDR* pNMHDR, LRESULT* pResult)
      {
           NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
           // TODO: Add your control notification handler code here
   
           CString sTemp;

           if((pNMListView->uOldState & LVIS_FOCUSED) == LVIS_FOCUSED &&
            (pNMListView->uNewState & LVIS_FOCUSED) == 0)
           {
                sTemp.Format("%d losted focus",pNMListView->iItem);
           }
           else if((pNMListView->uOldState & LVIS_FOCUSED) == 0 &&
               (pNMListView->uNewState & LVIS_FOCUSED) == LVIS_FOCUSED)
           {
                sTemp.Format("%d got focus",pNMListView->iItem);
           }

           if((pNMListView->uOldState & LVIS_SELECTED) == LVIS_SELECTED &&
            (pNMListView->uNewState & LVIS_SELECTED) == 0)
           {
                sTemp.Format("%d losted selected",pNMListView->iItem);
           }
           else if((pNMListView->uOldState & LVIS_SELECTED) == 0 &&
            (pNMListView->uNewState & LVIS_SELECTED) == LVIS_SELECTED)
           {
                sTemp.Format("%d got selected",pNMListView->iItem);
           }
   
           *pResult = 0;
      }
--------------------------------------------------------------------------------
17. listctrl的  subitem 添加图标
      注意: 首先要用 InsertItem() 插入一行的第一列, 然后才能用 SetItem 设置其他项 
      m_list.SetExtendedStyle(LVS_EX_SUBITEMIMAGES);
      m_userlist.SetItem(..);
--------------------------------------------------------------------------------
18. 在CListCtrl显示文件,并根据文件类型来显示图标
      网上找到的代码,自己试用并改正过, share
步骤1: 设置 list 的图像列表为 系统图像列表   
BOOL SetSystemImageList( CListCtrl & list )
{     
HIMAGELIST himlSmall;
HIMAGELIST himlLarge;
SHFILEINFO sfi;
char  cSysDir[MAX_PATH];
CString  strBuf;
memset(cSysDir, 0, MAX_PATH);
GetWindowsDirectory(cSysDir, MAX_PATH);
strBuf = cSysDir ;

// SHGetFileInfo:
// If uFlags contains SHGFI_SYSICONINDEX, the return value is a handle to
// an image list that contains the large icon images.
// If SHGFI_SMALLICON is included with SHGFI_SYSICONINDEX, the return value
// is the handle to an image list that contains the small icon images.
//
himlSmall = (HIMAGELIST)SHGetFileInfo ( (LPCSTR)cSysDir, 
     0, 
     &sfi,
     sizeof(SHFILEINFO), 
     SHGFI_SYSICONINDEX | SHGFI_SMALLICON );
himlLarge = (HIMAGELIST)SHGetFileInfo((LPCSTR)cSysDir, 
     0, 
     &sfi, 
     sizeof(SHFILEINFO), 
     SHGFI_SYSICONINDEX | SHGFI_LARGEICON);
if (himlSmall && himlLarge)
{
  ::SendMessage(list.m_hWnd, LVM_SETIMAGELIST,
      (WPARAM)LVSIL_SMALL, (LPARAM)himlSmall);
  
  ::SendMessage(list.m_hWnd, LVM_SETIMAGELIST,
      (WPARAM)LVSIL_NORMAL, (LPARAM)himlLarge);
}
return TRUE;
}
步骤2:  给列表添加指定的文件, 同时获得该文件的的图标索引, 给 list 添加图标
int GetIconIndex(LPCTSTR lpszPath, BOOL bIsDir, BOOL bSelected) ; //  向前声明
void AddFiles(CListCtrl & list, LPCTSTR lpszFileName, BOOL bAddToDocument)
{
int nIcon = GetIconIndex(lpszFileName, FALSE, TRUE);
CString strSize;
CFileFind filefind;
//  get file size
if ( filefind.FindFile(lpszFileName))
{
  filefind.FindNextFile();
  strSize.Format("%d", filefind.GetLength());
}
else
  strSize = "0";
// split path and filename
CString strFileName = lpszFileName;
CString strPath;
int nPos = strFileName.ReverseFind('\\');
if (nPos != -1)
{
  strPath = strFileName.Left(nPos);
  strFileName = strFileName.Mid(nPos 1);
}
// insert to list
int nItem = list.GetItemCount();


//list.InsertItem(nItem, strFileName, nIcon);
//list.SetItemText(nItem, 1, strSize);
//
// 此处可以根据实际需要修改代码
//
}
     
--------------------------------------------------------------------------------
19. listctrl内容进行大数据量更新时,避免闪烁
      m_list.SetRedraw(FALSE);
      //更新内容
      m_list.SetRedraw(TRUE);
      m_list.Invalidate();
      m_list.UpdateWindow();
20. 清除 ListCtrl 以重新初始化:
      // 删除所有行
m_ctrllist.DeleteAllItems() ;    
// 删除所有列
int iColCount = m_ctrllist.GetHeaderCtrl()->GetItemCount() ;

// 方法 1
// 原理: 删除第一列后, 其他列向前移动
while( m_ctrllist.DeleteColumn(0) ) ;
   
// 方法 2
for (int i=0; i < iColCount ; i )
{
  m_ctrllist.DeleteColumn(0);
}
// 方法 3
for (int i=iColCount-1; i >= 0; i-- )
{
  m_ctrllist.DeleteColumn( i );
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!