VC:CListCtrl(库函数的加载和释放、获取系统颜色、向图片链表添加位图、客户区的获取和填充)

时间:2022-10-10 23:27:45

(Memset()和Syscopy函数、获取当前路径、按钮的加载、获取当前窗口样式(GetWindowLongGRB())、设置或获取背景色、设或获取置文本背景色、设置或获取文本色、插入类表头、获取客户端大小、设置每列的宽度、设置扩展样式、插入项、获取所有项数、设置每项每列的文本,设置项选中状态、设置背景图片、删除所有项、获取系统颜色、向图片链表添加位图、获取当前位项置,获取当前项的下一项、获取列表控件的头)

1、基本知识:

       m_list.SetBkColor(RGB(123,123,123));

       m_list.SetTextBkColor(RGB(255,0,0));

       m_list.SetTextColor(RGB(255,255,0));

       m_list.InsertColumn(0,"日期");

       m_list.InsertColumn(1,"天气");

 

       //获取列表宽度

       RECT rect;

       m_list.GetWindowRect(&rect);

       int wid=rect.right-rect.left;

 

       //为每列设置宽度

       m_list.SetColumnWidth(0,wid/4);

       m_list.SetColumnWidth(1,3*wid/4);

       m_list.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP);

       CString str;

       int i;

       for( i=0;i<7;i++)

       {    

              m_list.InsertItem(i,"1");

       }

       for(i=0;i<7;i++)

       {

              str.Format("星期%d",i+1);

              //int count=m_list.GetItemCount();

              m_list.SetItemText(i,0,str);

              m_list.SetItemText(i,1,(i%2==0)?"晴":"多云");

       }

       /*

       for( i=0;i<7;i++)

       {    

              m_list.InsertItem(i,"1");

      

              str.Format("星期%d",i+1);

              //int count=m_list.GetItemCount();

              m_list.SetItemText(0,0,str);

              m_list.SetItemText(0,1,(i%2==0)?"晴":"多云");

 

       }

  */

2、升华:综合知识

 

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

       : CDialog(CListCtrlDlg::IDD, pParent)

{

       //{{AFX_DATA_INIT(CListCtrlDlg)

              // NOTE: the ClassWizard will add member initialization here

       modalflag=true;

       //}}AFX_DATA_INIT

       // Note that LoadIcon does not require a subsequent DestroyIcon in Win32

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

 

       //背景透明

/*    SetWindowLong(this-> GetSafeHwnd(),GWL_EXSTYLE,GetWindowLong(this-> GetSafeHwnd(),GWL_EXSTYLE)^0x80000);

HINSTANCE   hInst   =   LoadLibrary( "User32.DLL ");  

if(hInst)  

{  

typedef   BOOL   (WINAPI   *MYFUNC)(HWND,COLORREF,BYTE,DWORD);  

MYFUNC   fun   =   NULL;

//取得SetLayeredWindowAttributes函数指针  

fun=(MYFUNC)GetProcAddress(hInst,   "SetLayeredWindowAttributes ");

if(fun)fun(this-> GetSafeHwnd(),0,222,2);   //128

FreeLibrary(hInst);  

}

*/

}

 

void CListCtrlDlg::DoDataExchange(CDataExchange* pDX)

{

       CDialog::DoDataExchange(pDX);

       //{{AFX_DATA_MAP(CListCtrlDlg)

       DDX_Control(pDX, IDC_LIST1, m_list);

       //}}AFX_DATA_MAP

}

 

BEGIN_MESSAGE_MAP(CListCtrlDlg, CDialog)

       //{{AFX_MSG_MAP(CListCtrlDlg)

       ON_WM_SYSCOMMAND()

       ON_WM_PAINT()

 

       ON_WM_ERASEBKGND()

 

       ON_WM_QUERYDRAGICON()

       ON_BN_CLICKED(IDC_EXCHANGE, OnExchange)

       ON_BN_CLICKED(IDC_INSERTITEM, OnInsertitem)

       ON_BN_CLICKED(IDC_CHECKBOX, OnCheckbox)

       ON_BN_CLICKED(IDC_LINESELECTED, OnLineselected)

       ON_BN_CLICKED(IDC_ITEMINFO, OnIteminfo)

       ON_BN_CLICKED(IDC_ENSUREVISIBLE, OnEnsurevisible)

       ON_BN_CLICKED(IDC_GETCOLUM, OnGetcolum)

       ON_BN_CLICKED(IDC_DELETECOLUMNS, OnDeletecolumns)

       ON_NOTIFY(NM_CLICK, IDC_LIST1, OnClickList1)

       ON_NOTIFY(NM_RCLICK, IDC_LIST1, OnRclickList1)

       ON_NOTIFY(LVN_ODFINDITEM, IDC_LIST1, OnOdfinditemList1)

       ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST1, OnItemchangedList1)

       ON_BN_CLICKED(IDC_ADDIMAGE, OnAddimage)

       ON_BN_CLICKED(IDC_REDRAW, OnRedraw)

       ON_BN_CLICKED(IDC_OTHER, OnOther)

       ON_BN_CLICKED(IDC_ADDFILECODE, OnAddfilecode)

       ON_BN_CLICKED(IDOK, OnOk)

       ON_BN_CLICKED(IDC_CURITEM, OnCuritem)

       ON_BN_CLICKED(IDC_GETBKIMAGE, OnGetbkimage)

       ON_BN_CLICKED(IDC_INSERTIMAGE, OnInsertimage)

       //}}AFX_MSG_MAP

END_MESSAGE_MAP()

 

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

// CListCtrlDlg message handlers

 

BOOL CListCtrlDlg::OnInitDialog()

{

       CDialog::OnInitDialog();

 

       // Add "About..." menu item to system menu.

 

       // IDM_ABOUTBOX must be in the system command range.

       ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);

       ASSERT(IDM_ABOUTBOX < 0xF000);

 

       CMenu* pSysMenu = GetSystemMenu(FALSE);

       if (pSysMenu != NULL)

       {

              CString strAboutMenu;

              strAboutMenu.LoadString(IDS_ABOUTBOX);

              if (!strAboutMenu.IsEmpty())

              {

                     pSysMenu->AppendMenu(MF_SEPARATOR);

                     pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);

              }

       }

 

       // Set the icon for this dialog.  The framework does this automatically

       //  when the application's main window is not a dialog

       SetIcon(m_hIcon, TRUE);                  // Set big icon

       SetIcon(m_hIcon, FALSE);          // Set small icon

      

       // TODO: Add extra initialization here

      

       m_list.InsertColumn( 0, "Column1",LVCFMT_IMAGE|LVCFMT_LEFT, 89 );//插入列

    m_list.InsertColumn( 1, "Column2", LVCFMT_LEFT, 100 );

       m_list.InsertColumn( 1, "Column3", LVCFMT_LEFT, 100 );

       for(int i=0;i<3;i++)

       {

              //nRow = m_list.InsertItem(i, "11");//插入行

              //m_list.SetItemText(nRow, 1, "shen");//设置数据

              CString str;

              str.Format("%d",i);

              m_list.InsertItem(i, str);//插入行

       }

       m_list.SetItemText(2, 1, "shen");//设置数据

       m_list.SetItemText(1, 1, "chao");//设置数据

       m_list.SetItemText(0, 1, "huge");//设置数据

      

       int nIndex = 0;

    //选中

    m_list.SetItemState(nIndex, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);

       //取消选中

    //m_list.SetItemState(nIndex, 0, LVIS_SELECTED|LVIS_FOCUSED);

      

char  Dir[MAX_PATH];

       CString  Buf;

 

       memset(Dir, 0, MAX_PATH);

//获取当前路径

//HRESULT GetCurrentDir(

//  BSTR *pbstrPathSpec

//);

 

       ::GetCurrentDirectory(MAX_PATH,Dir);

       Buf=Dir;

       //sprintf(cSysDir,"%s",strBuf.Left(strBuf.Find("\\")+1));

       //Buf.Left(Buf.ReverseFind('\\')+1);

       //设置背景图片

 LVBKIMAGE bki;

 

  if (m_list.GetBkImage(&bki) && (bki.ulFlags ==

                                   LVBKIF_SOURCE_NONE))

  {

        

    //m_list.SetBkImage(TEXT("C:\\mahi.bmp"),TRUE);

        CString str=Buf+"\\res\\mahi.bmp";

        //MessageBox(str);

       strcpy(chImagePath,str);

       MessageBox(TEXT(chImagePath));

       m_list.SetBkImage(TEXT(chImagePath),TRUE);

      // Use your own Image Address Here

  }

/*在函数InitInstance()中初始化 COM libraries ;

如下:

 

        AfxEnableControlContainer();

 

    CoInitialize(NULL); // Initialize COM libraries

*/

 

 

  //读取图标信息

 

/*

                   CBitmap bt ;

 

                   bt.LoadBitmap(IDB_BITMAP1);

 

                   m_ImageList.Create(32,32,ILC_COLOR24,3,1);

                            //bt.Attach(hbitmap);

                   m_ImageList.Add(&bt,RGB(216,233,236));//将RGB(216,233,236)变成透明色

 

 

                  // CBitmap bt ;

 

                   bt.LoadBitmap(IDB_BITMAP2);

 

                   m_smallImageList.Create(16,16,ILC_COLOR24,3,1);

 

                   m_smallImageList.Add(&bt,RGB(216,233,236));//将RGB(216,233,236)变成透明色

 

 

 

         //设置图像

 

         m_list.SetImageList(&m_ImageList,LVSIL_NORMAL );

 

         m_list.SetImageList(&m_smallImageList,LVSIL_SMALL );

*/

 

       return TRUE;  // return TRUE  unless you set the focus to a control

}

 

void CListCtrlDlg::OnSysCommand(UINT nID, LPARAM lParam)

{

       if ((nID & 0xFFF0) == IDM_ABOUTBOX)

       {

              CAboutDlg dlgAbout;

              dlgAbout.DoModal();

       }

       else

       {

              CDialog::OnSysCommand(nID, lParam);

       }

}

 

// If you add a minimize button to your dialog, you will need the code below

//  to draw the icon.  For MFC applications using the document/view model,

//  this is automatically done for you by the framework.

 

void CListCtrlDlg::OnPaint()

{

       if (IsIconic())

       {

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

 

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

 

              // Center icon in client rectangle

              int cxIcon = GetSystemMetrics(SM_CXICON);

              int cyIcon = GetSystemMetrics(SM_CYICON);

              CRect rect;

              GetClientRect(&rect);

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

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

 

              // Draw the icon

              dc.DrawIcon(x, y, m_hIcon);

       }

       else

       {

              CDialog::OnPaint();

       }

}

 

// The system calls this to obtain the cursor to display while the user drags

//  the minimized window.

HCURSOR CListCtrlDlg::OnQueryDragIcon()

{

       return (HCURSOR) m_hIcon;

}

 

void CListCtrlDlg::OnExchange()

{

       // TODO: Add your control notification handler code here

       LONG lStyle;

       DWORD dwStyle;

       if(modalflag)

       {

              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

 

              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); //设置扩展风格

       }

       else

       {

              lStyle = GetWindowLong(m_list.m_hWnd, GWL_STYLE);//获取当前窗口style

              lStyle &= ~LVS_TYPEMASK; //清除显示方式位

              //lStyle |= LVS_ICON ; //设置style

              lStyle |= LVS_LIST ; //设置style

              SetWindowLong(m_list.m_hWnd, GWL_STYLE, lStyle);//设置style

 

              dwStyle = m_list.GetExtendedStyle();

              dwStyle |= LVS_SHOWSELALWAYS |LVS_EX_CHECKBOXES;//item前生成checkbox控件

              m_list.SetExtendedStyle(dwStyle); //设置扩展风格

       }

       modalflag=!modalflag;

}

 

void CListCtrlDlg::OnInsertitem()

{

       // TODO: Add your control notification handler code here

       // The pointer to my list view control.

       //extern CListCtrl* pmyListCtrl;

       CListCtrl* pmyListCtrl;

       pmyListCtrl=(CListCtrl*)GetDlgItem(IDC_LIST1);

       CString strText;

       int nColumnCount = pmyListCtrl->GetHeaderCtrl()->GetItemCount();

 

       m_list.DeleteAllItems();

       // Insert 10 items in the list view control.

       for (int i=0;i < 10;i++)

       {

          strText.Format(TEXT("item %d"), i);

 

          // Insert the item, select every other item.

          pmyListCtrl->InsertItem(

                LVIF_TEXT|LVIF_STATE, i, strText,

                (i%2)==0 ? LVIS_SELECTED : 0, LVIS_SELECTED,

                0, 0);

 

          // Initialize the text of the subitems.

          for (int j=1;j < nColumnCount;j++)

          {

                strText.Format(TEXT("sub-item %d %d"), i, j);

                pmyListCtrl->SetItemText(i, j, strText);

          }

       }

       //方法二:

            // CFormView::OnInitialUpdate();

 

      m_list.InsertColumn(0, "Western States", LVCFMT_LEFT, 150);

 

      LV_ITEM lvItem;

      ZeroMemory(&lvItem, sizeof(lvItem));

      lvItem.mask = LVIF_TEXT | LVIF_STATE;

 

      lvItem.iItem = 0;

      lvItem.state = LVIS_CUT | LVIS_SELECTED;

      lvItem.pszText = "Washington";

      m_list.InsertItem(&lvItem); // initially selected

 

      lvItem.iItem = 1;

      lvItem.state = LVIS_CUT | LVIS_SELECTED;

      lvItem.pszText = "Arizona";

      m_list.InsertItem(&lvItem); // initially selected

 

      lvItem.iItem = 2;

      lvItem.state = LVIS_CUT;

      lvItem.pszText = "Alaska";

      m_list.InsertItem(&lvItem);

 

      lvItem.iItem = 3;

      lvItem.state = LVIS_CUT;

      lvItem.pszText = "California";

      m_list.InsertItem(&lvItem);

 

      lvItem.iItem = 4;

      lvItem.state = LVIS_CUT;

      lvItem.pszText = "Nevada";

      m_list.InsertItem(&lvItem);

 

      UINT nState;

      CString strText1;

      int iItem = -1;

 

      // as long as GetNextItem found an item...

      while ((iItem = m_list.GetNextItem(iItem, LVNI_ALL)) > -1 )

      {

         // get item string

         strText1 = m_list.GetItemText(iItem, 0);

 

         // show initial state of flags

         nState = m_list.GetItemState(iItem, LVIS_SELECTED | LVIS_CUT);

         TRACE("%s state flag is %0x\n", strText1, nState);

 

         // Get only LVIS_SELECTED flag

         // note that LVIS_CUT is not returned in nState

         nState = m_list.GetItemState(iItem, LVIS_SELECTED);

 

         // select states beginning with 'A'

         if (strText[0] == 'A' && !nState) {

            TRACE("%s needed to be selected\n", strText1);

            m_list.SetItemState(iItem,

               LVIS_SELECTED,  // nState

               LVIS_SELECTED); // nMask

 

         // deselect states that don't begin with 'A'

         } else if (strText1[0] != 'A' && nState) {

            TRACE("%s needed to be deselected\n", strText1);

            m_list.SetItemState(iItem,

               0,              // nState

               LVIS_SELECTED); // nMask

         }

 

         // show new flags if modified, note that LVIS_CUT wasn't affected

         nState = m_list.GetItemState(iItem, LVIS_SELECTED | LVIS_CUT);

         TRACE("%s state flag is now %0x\n", strText1, nState);

      }

 

}

 

void CListCtrlDlg::OnCheckbox()

{

       // TODO: Add your control notification handler code here

         //m_list.SetExtendedStyle(LVS_EX_CHECKBOXES);

      CString str;

      for(int i=0; i<m_list.GetItemCount(); i++)

      {

           if(  m_list.GetCheck(i))

           {

                str.Format(_T("第%d行的checkbox为选中状态"), i);

                AfxMessageBox(str);

           }

      }

 

}

 

void CListCtrlDlg::OnLineselected()

{

       // TODO: Add your control notification handler code here

         //方法一:

     /* 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);

           }

      }*/

 

     // 方法二:

       CListCtrl* pListCtrl = (CListCtrl*) GetDlgItem(IDC_LIST1);

              ASSERT(pListCtrl != NULL);

 

 

      POSITION pos = m_list.GetFirstSelectedItemPosition();

      if (pos == NULL)

                MessageBox("No items were selected!n");

           //TRACE0("No items were selected!n");

      else

      {

           while (pos)

           {

                int nItem = m_list.GetNextSelectedItem(pos);

                CString str;

                            str.Format("Item %d was selected!n", nItem);

                            MessageBox(str);  

                            //TRACE1("Item %d was selected!n", nItem);

 

                // you could do your own processing on nItem here

           }

      }

}

 

void CListCtrlDlg::OnIteminfo()

{

       // TODO: Add your control notification handler code

       int nItemIndex;

 

       POSITION pos = m_list.GetFirstSelectedItemPosition();

      if (pos == NULL)

                MessageBox("No items were selected!n");

           //TRACE0("No items were selected!n");

      else

      {

           while (pos)

           {

                nItemIndex = m_list.GetNextSelectedItem(pos);

           }

      }

 

 

       TCHAR szBuf[1024];

    LVITEM lvi;

    lvi.iItem = nItemIndex;

    //lvi.iSubItem = 0;

       lvi.iSubItem = 1;

    lvi.mask = LVIF_TEXT;

    lvi.pszText = szBuf;

    lvi.cchTextMax = 1024;

    m_list.GetItem(&lvi);

 

       CString str;

       str.Format("%s",lvi.pszText);

       MessageBox(str);

       //TRACE("%d,%d,%s",lvi.iItem,lvi.iSubItem,lvi.pszText);

}

 

void CListCtrlDlg::OnEnsurevisible()

{

       // TODO: Add your control notification handler code here

       //使listctrl中一项可见,即滚动滚动条

       //for(int i;i<m_list.GetItemCount();i++)

       //     m_list.EnsureVisible(i, FALSE);

 

       m_list.EnsureVisible(0, FALSE);

 

 

}

 

void CListCtrlDlg::OnGetcolum()

{

       // TODO: Add your control notification handler code here

       //得到listctrl列数

    int nHeadNum = m_list.GetHeaderCtrl()->GetItemCount();

       //TRACE("%d",nHeadNum);

       CString s;

       s.Format("%d",nHeadNum);

       MessageBox(s);

}

 

void CListCtrlDlg::OnDeletecolumns()

{

       // TODO: Add your control notification handler code here

       //12. 删除所有列

     // 方法一:

         while ( m_list.DeleteColumn (0));

      // 因为你删除了第一列后,后面的列会依次向上移动。

 

      //方法二:

     /* int nColumns = 4;

      for (int i=nColumns-1; i>=0; i--)

          m_list.DeleteColumn (i);

*/

 

}

 

void CListCtrlDlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)

{

       // TODO: Add your control notification handler code here

       //方法一:

      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);

           }

      }

 

    /* // 方法二:

       CListCtrl* pListCtrl = (CListCtrl*) GetDlgItem(IDC_LIST1);

              ASSERT(pListCtrl != NULL);

 

 

      POSITION pos = m_list.GetFirstSelectedItemPosition();

      if (pos == NULL)

                MessageBox("No items were selected!n");

           //TRACE0("No items were selected!n");

      else

      {

           while (pos)

           {

                int nItem = m_list.GetNextSelectedItem(pos);

                CString str;

                            str.Format("Item %d was selected!n", nItem);

                            MessageBox(str);  

                            //TRACE1("Item %d was selected!n", nItem);

 

                // you could do your own processing on nItem here

           }

      }*/

 

         /* 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上");

           }

*/

 

       // The pointer to my list view control.

       /*    CListCtrl* pmyListCtrl= (CListCtrl*) GetDlgItem(IDC_LIST1);;

              // The pointer where the mouse was clicked.

              CPoint myPoint;

 

              // Select the item the user clicked on.

              UINT uFlags;

              int nItem = pmyListCtrl->HitTest(myPoint, &uFlags);

 

              if (uFlags & LVHT_ONITEMLABEL)

              {

                 pmyListCtrl->SetItem(nItem, 1, LVIF_STATE, "HELLO", 0, LVIS_SELECTED,

                       LVIS_SELECTED, 0);

              }

*/

 

       *pResult = 0;

}

 

void CListCtrlDlg::OnRclickList1(NMHDR* pNMHDR, LRESULT* pResult)

{

       // TODO: Add your control notification handler code here

       //15. 右键点击listctrl的item弹出菜单

     // 添加listctrl控件的NM_RCLICK消息相应函数

 

        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;

}

 

/*void CListCtrlDlg::OnItemchangedList1(NMHDR* pNMHDR, LRESULT* pResult)

{

       HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;

       // TODO: Add your control notification handler code here

      

       *pResult = 0;

}

*/

void CListCtrlDlg::OnOdfinditemList1(NMHDR* pNMHDR, LRESULT* pResult)

{

       NMLVFINDITEM* pFindInfo = (NMLVFINDITEM*)pNMHDR;

       // TODO: Add your control notification handler code here

      

       *pResult = 0;

}

 

void CListCtrlDlg::OnItemchangedList1(NMHDR* pNMHDR, LRESULT* pResult)

{

       NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;

       // TODO: Add your control notification handler code here

      

//item切换焦点时(包括用键盘和鼠标切换item时),状态的一些变化顺序

    //  添加listctrl控件的LVN_ITEMCHANGED消息相应函数

 

       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);

           }

 

                 MessageBox(sTemp);

 

       *pResult = 0;

}

 

void CListCtrlDlg::OnAddimage()

{

      

       // TODO: Add your control notification handler code here

       //20. listctrl的subitem添加图标

      m_list.SetExtendedStyle(LVS_EX_SUBITEMIMAGES);

         //BOOL SetItem( int nItem, int nSubItem, UINT nMask, LPCTSTR lpszItem,

                                   //int nImage, UINT nState, UINT nStateMask, LPARAM lParam );

//int nItem = pmyListCtrl->HitTest(myPoint, &uFlags);

 

      m_list.SetItem(0,0,0,"image",0,0,0,NULL); //具体参数请参考msdn

 

}

 

void CListCtrlDlg::AddFiles(LPCTSTR lpszFileName, BOOL bAddToDocument)

{

       int nIcon = GetIconIndex(lpszFileName, FALSE, FALSE);

           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 = m_list.GetItemCount();

           m_list.InsertItem(nItem, strFileName, nIcon);

           m_list.SetItemText(nItem, 1, strSize);

           m_list.SetItemText(nItem, 2, strFileName.Right(3));

           m_list.SetItemText(nItem, 3, strPath);

 

}

 

int CListCtrlDlg::GetIconIndex(LPCTSTR lpszPath, BOOL bIsDir, BOOL bSelected)

{

        SHFILEINFO sfi;

           memset(&sfi, 0, sizeof(sfi));

 

           if (bIsDir)

           {

            SHGetFileInfo(lpszPath,

                         FILE_ATTRIBUTE_DIRECTORY,

                         &sfi,

                         sizeof(sfi),

                         SHGFI_SMALLICON | SHGFI_SYSICONINDEX |

                         SHGFI_USEFILEATTRIBUTES |(bSelected ? SHGFI_OPENICON : 0));

            return  sfi.iIcon;

           }

           else

           {

            SHGetFileInfo (lpszPath,

                         FILE_ATTRIBUTE_NORMAL,

                         &sfi,

                         sizeof(sfi),

                         SHGFI_SMALLICON | SHGFI_SYSICONINDEX |

                         SHGFI_USEFILEATTRIBUTES | (bSelected ? SHGFI_OPENICON : 0));

            return   sfi.iIcon;

           }

           return  -1;

 

}

 

void CListCtrlDlg::OnRedraw()

{

       // TODO: Add your control notification handler code here

       //22. listctrl内容进行大数据量更新时,避免闪烁

      m_list.SetRedraw(FALSE);

      //更新内容

      m_list.SetRedraw(TRUE);

      m_list.Invalidate();

      m_list.UpdateWindow();

 

}

 

void CListCtrlDlg::OnOther()

{

       // TODO: Add your control notification handler code here

/*

--------------------------------------------------------------------------------

 

17. 得到另一个进程里的listctrl控件的item内容

http://www.codeproject.com/threads/int64_memsteal.asp

 

--------------------------------------------------------------------------------

 

18. 选中listview中的item

Q131284: How To Select a Listview Item Programmatically

http://support.microsoft.com/kb/131284/en-us

 

--------------------------------------------------------------------------------

 

19. 如何在CListView中使用CListCtrl的派生类

http://www.codeguru.com/cpp/controls/listview/introduction/article.php/c919/

--------------------------------------------------------------------------------

 

20. listctrl的subitem添加图标

      m_list.SetExtendedStyle(LVS_EX_SUBITEMIMAGES);

      m_list.SetItem(..); //具体参数请参考msdn

--------------------------------------------------------------------------------

 

*/

 

}

 

void CListCtrlDlg::OnAddfilecode()

{

       // TODO: Add your control notification handler code here

       //     添加文件 1

 

 

       HIMAGELIST himlSmall;

       HIMAGELIST himlLarge;

       SHFILEINFO sfi;

       char  cSysDir[MAX_PATH];

       CString  strBuf;

 

       memset(cSysDir, 0, MAX_PATH);

 

       GetWindowsDirectory(cSysDir, MAX_PATH);

       strBuf=cSysDir;

       sprintf(cSysDir,"%s",strBuf.Left(strBuf.Find("\\")+1));

/*    CString  str;

       int num=str.Find("\\")+1;

       str=strBuf.Left(num);

       sprintf(cSysDir,"%s",str);

       */

       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(m_list.m_hWnd, LVM_SETIMAGELIST,

                             (WPARAM)LVSIL_SMALL, (LPARAM)himlSmall);

       ::SendMessage(m_list.m_hWnd, LVM_SETIMAGELIST,

                             (WPARAM)LVSIL_NORMAL, (LPARAM)himlLarge);

       }

 

       //     添加文件 1部分 结束

       //测试:

       m_list.DeleteAllItems();

 

       char  cDir[MAX_PATH];

       CString  sBuf;

 

       memset(cDir, 0, MAX_PATH);

 

       GetWindowsDirectory(cDir, MAX_PATH);

       sBuf=cDir;

       strBuf.Left(strBuf.Find("\\")+1);

       GetIconIndex( sBuf , true , true );

       AddFiles("test.txt", true);

}

 

void CListCtrlDlg::OnOk()

{

       // TODO: Add your control notification handler code here

       CDialog::OnOK();

}

 

void CListCtrlDlg::OnCuritem()

{

       // TODO: Add your control notification handler code here

       int num=m_list.GetNextItem(-1, LVNI_ALL | LVNI_SELECTED);

       CString str;

       str.Format("%d",num);

       MessageBox(str);

}

 

 

      

 

//#define TIMER_1 1

//#define TIMER_2 2

//int gTimer=0;

void CListCtrlDlg::OnGetbkimage()

{

       // TODO: Add your control notification handler code here

       CFileDialog   dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"Image Files (*.jpg;*.bmp)|*.jpg;*.bmp|All Files (*.*)|*.*||");

 

   if(dlg.DoModal()==IDOK)

   {

         strImagePath= dlg.GetPathName();

         strcpy(chImagePath,strImagePath);

      m_list.SetBkImage(TEXT(chImagePath),TRUE);

 

   }

}

 

void CListCtrlDlg::OnInsertimage()

{

       // TODO: Add your control notification handler code here

       //     m_list.DeleteAllItems();

 

       /*    用下面的语句新建列:

              m_ListCtrl.InsertColumn(0,_T("文件名"),LVCFMT_IMAGE|LVCFMT_LEFT);

              m_ListCtrl.InsertColumn(1,_T("仪器类别"));

              m_ListCtrl.InsertColumn(2,_T("项目类别"));

 

              其中LVCFMT_IMAGE表示可以在第一列加入图标。如果不要图标可以删去。

 

              然后设置列宽:

              for(j=0;j<3;j++)

              m_ListCtrl.SetColumnWidth(j ,100);

 

              以下为列表加入图标,如果不需要图标,可以跳过这一步。注意只在第一次加入,如果多次加入会出错!

              先在头文件中加入声明:

              CImageList m_ImageList;

              这是必要的,如果在cpp的某个函数中加入由于生命期结束,CImageList自动释放,则效果是列表中看不到图标,只看到一个白方块。

              下面生成CImageList,并将其绑定到CListCtrl中,这是CImageList中还没有图标,只是一个容器:

              */

/*    static int flag=2;

              if(flag==2){//只调用一次SetImageList,否则出错

              m_ImageList.Create(128, 128, ILC_COLORDDB|ILC_MASK, 20, 1);

              m_list.SetImageList(&m_ImageList,LVSIL_SMALL);

              }

              flag=(flag+1)%2;

       //     如果CListCtrl已经用过,曾经加过图标进去,这时就要删除上次放进m_ImageList中的Image

              int m_listrowCount=m_ImageList.GetImageCount();

              for(int kk=0;kk<m_listrowCount;kk++)

              m_ImageList.Remove(kk);

 

              //下面介绍如何向CListCtrl里面加入行,并同时为每一行动态加入图标:

              //假设m_listRowCount为要加入的行数。

              CBitmap* bitmap;

              bitmap=new CBitmap[m_listrowCount];

              HBITMAP hbitmap;

 

              for(int i = 0; i < m_listrowCount; i++)

              {

              //为每一行插入相应的缩略图

              CFile f;

              CFileException e;

              CString m_FileName,bmpFile,path;

              m_FileName="ListCtrl.bmp";

              char  cSysDir3[MAX_PATH];

       //CString  strBuf3;

 

       memset(cSysDir3, 0, MAX_PATH);

 

       GetWindowsDirectory(cSysDir3, MAX_PATH);

       bmpFile=cSysDir3;

       path=bmpFile;

       //sprintf(cSysDir3,"%s",strBuf3.Left(strBuf3.Find("\\")+1));

              bmpFile=path+"\\res\\bitmap2.bmp";

              MessageBox(bmpFile);

              if( !f.Open(m_FileName, CFile::modeRead, &e )){ //m_FileName为bmp文件名,由你来定

                 hbitmap = (HBITMAP)LoadImage(NULL,path+"\\res\\bitmap1.bmp",IMAGE_BITMAP,0,0,

                     LR_CREATEDIBSECTION|LR_DEFAULTSIZE|LR_LOADFROMFILE);

              }else{

                 f.Close();

                 hbitmap = (HBITMAP)LoadImage(NULL,bmpFile,IMAGE_BITMAP,0,0,

                     LR_CREATEDIBSECTION|LR_DEFAULTSIZE|LR_LOADFROMFILE);

              }

//     hbitmap = (HBITMAP)LoadImage(NULL,"D:\\VC\\ListCtrl\\res\\ListCtrl.bmp",IMAGE_BITMAP,0,0,

       //     LR_CREATEDIBSECTION|LR_DEFAULTSIZE|LR_LOADFROMFILE);

              bitmap[i].Attach(hbitmap);

              m_ImageList.Add(&bitmap[i], RGB(0, 128, 128));

 

              //插入行

              //m_list.InsertItem(i,m_FileName,i);

       //m_list.SetItemText(i,1,"type");

       //m_list.SetItemText(i,2,"m_Path");

              }

 

              //记得删除已经没用的临时文件

              if(m_listrowCount!=0)

              delete[] bitmap;

 

              //2。如果是ICON类型的CListCtrl,则要做一点点改动:

              //把绑定图标集的代码由

              //SetImageList(&m_ImageList,LVSIL_SMALL);

              //改为

              m_list.SetImageList(&m_ImageList,LVSIL_NORMAL);

 

       //     插入行时只用

       //     InsertItem(i,mainSet.m_FileName,i);

       //     不用

       //     SetItemText(i,1,type);

       //     之类的代码。*/

/*

// create, initialize, and hook up image list

m_pImageList = new CImageList();

ASSERT(m_pImageList != NULL);    // serious allocation failure checking

m_pImageList->Create(32, 32, TRUE,   4, 4);

m_pImageList->Add(pApp->LoadIcon(IDI_ICONLIST1));

m_pImageList->Add(pApp->LoadIcon(IDI_ICONLIST2));

m_listctrl.SetImageList(m_pImageList, LVSIL_NORMAL);

*/

      

HICON   myIcon[3];  

 myIcon[0]=AfxGetApp()->LoadIcon(IDI_ICON1);//注意这里是通过LoadIcon获得HICON  

 myIcon[1]=AfxGetApp()->LoadIcon(IDI_ICON2);

 myIcon[2]=AfxGetApp()->LoadIcon(IDR_MAINFRAME);

   

 

 m_ImageList.Create(32, 32, ILC_COLOR32, 8, 8);  

 for(int i=0; i < 3; i++)  

 {  

  m_ImageList.Add(myIcon[i]);  

 }  

 //m_friend_list.SetImageList(&m_list, LVSIL_SMALL); 

 m_list.SetImageList(&m_ImageList, LVSIL_SMALL); 

 for(i=0; i < 3; i++)  

 {  

  LVITEM lvitem;

  lvitem.mask = LVIF_IMAGE|LVIF_TEXT;  

  lvitem.iItem = i; 

  CString str;

  lvitem.pszText = " ";  

  lvitem.iImage = i;  

  lvitem.iSubItem = 0;  

  m_list.InsertItem(&lvitem); 

 

 }

/*----------------------

只要能获得句柄就能获得ID

----------------------

//现在已经能正常显示图标了 改了这句话就行了

((CListCtrl *) lParam)->InsertItem(i,m_strTitle, i);

 

*/

 /*

// The pointer to my image list.

extern CImageList* pmyImageList;

 

// Add my icons.

pmyImageList->Add(AfxGetApp()->LoadIcon(IDI_ICON1));

pmyImageList->Add(AfxGetApp()->LoadIcon(IDI_ICON2));

 

// Add my bitmap, make all black pixels transparent.

CBitmap bm;

bm.LoadBitmap(IDB_BITMAP1);

pmyImageList->Add(&bm, RGB(0, 0, 0));

 

 

  */

}

 

BOOL CListCtrlDlg::OnEraseBkgnd(CDC *pDC)

{

//pDC-> SetBkMode   (TRANSPARENT);

        RECT rc;

    GetClientRect(&rc);

    pDC->FillSolidRect(&rc, RGB(111,222,333));

 

  /* // 使IDC_LIST1控件透明   

    RECT rcListCtrl;

    ::GetClientRect(::GetDlgItem(this->m_hWnd, IDC_LIST1), &rcListCtrl);

    pDC->FillSolidRect(&rcListCtrl,RGB(1, 2, 3));

*/

       // The pointer to my list view control.

//extern CListCtrl* pmyListCtrl;

 

// Use the 3D button face color for the background.

COLORREF crBkColor = ::GetSysColor(COLOR_3DFACE);

//pmyListCtrl->SetBkColor(crBkColor);

m_list.SetBkColor(crBkColor);

m_list.SetTextBkColor(crBkColor);

//m_list.SetTextBkColor(TRANSPARENT);

//ASSERT(pmyListCtrl->GetBkColor() == crBkColor);

ASSERT(m_list.GetBkColor() == crBkColor);

ASSERT(m_list.GetTextBkColor() == crBkColor);

 

}