CListCtrl usage and summary (by how to hide Listctrl list header sort Small triangle this bug learned knowledge)

Source: Internet
Author: User
Tags function prototype truncated

1 How to hide the sort of Listctrl list header small triangles

When creating a control is Join | Lvs_nosortheader style can be.

Here is a summary of usage:

This article is based on my application in the project, to talk about some of the usage and skills of CListCtrl. At the beginning of the study, looked up a lot of information, piecemeal made some records, now is mainly to do a summary, convenient for later inspection. Mainly includes the following 13 points : basic operation, get the line number of the selected row, check box action, dynamically set the font color of the selected row, set the background color of the selected row, prohibit dragging the header, let the first column center display, set the row height and font, virtual list technology, click on the table header to categorize, Move up and down, resize issues dynamically, and avoid flicker issues.

It is divided into two articles to summarize. This article highlights: basic operations , get the row number of the selected row , check box action , dynamically set the font color of the selected row , set the background color of the selected row

1. Basic operation

The basic operation of CListCtrl is introduced from the following four points:

① Setting the list view display mode

Ⅰ. CListCtrl has four styles: Lvs_icon, Lvs_smallicon, Lvs_list, and Lsv_report, which can be set by control properties. All of the Lsv_report properties are described in this article.

Ⅱ. Extended styles:

There are three types of extended styles commonly used: Lvs_ex_fullrowselect, Lvs_ex_gridlines, lvs_ex_checkboxes, respectively, when a row is selected to highlight a row, set a grid line, and generate a Ckeckbox control before the item.

Use the SetExtendedStyle(style) function to set the extended style, using the getextendedstyle() function to get the style, such as:

Set list Extend Styledword dwstyle = GetExtendedStyle ();d wstyle |= lvs_ex_fullrowselect;dwstyle |= lvs_ex_gridlines; SetExtendedStyle (dwstyle);

Ⅲ. When using CListView, you need to add Cs.style in the PreCreateWindow () function | = Lvs_report;

To set it to Lvs_report style, otherwise the insert is not valid. Another way to set the style is to get CListCtrl control in Oninitialupate () and then modify the style as follows:

CListCtrl &thectrl =GetListCtrl();

Thectrl. ModifyStyle (0, Lvs_report);

② insert Operation

Insert Columns First:

int insertcolumn(int ncol, LPCTSTR lpszcolumnheading, int nformat, I NT nwidth, int nsubitem)

When you insert a column, you can indicate information such as column number, column name, column name display style, and column width. For the column with column number 0, the left side is always displayed, followed by the methods that make it appear in the show, and the other columns can be centered by setting the Nformat property.

Init columncstring strcolumn;strcolumn.loadstring (strName); CRect Listctrlrect; GetWindowRect (&listctrlrect); ScreenToClient (&listctrlrect); InsertColumn (0, Strcolumn, 0, Listctrlrect.width ());

Insert Row:

int insertitem(int nitem, LPCTSTR lpszitem)

Inserts a row directly, Nitem indicates the line number, and Lpszitem indicates the information for the No. 0 column of the row.

Setting Information:

BOOL setitemtext(int nitem, int nsubitem, LPCTSTR lpszText)

Set the information for line nitem nsubitem column (nitem:0,1,2,3 ... ; nsubitem:1,2,3. )

③ Delete Operation

There are three operation functions:

BOOL deleteallitems()-------Delete all rows

BOOL DeleteItem(nitem)--------Delete a row

BOOL deletecolumn(ncol)-----Delete a column

④ Get/Set Property function

There are a lot of functions, do not introduce each. Commonly used to have

int getitemcount()--------Gets the number of rows in the inserted information

BOOL setitemstate(int iLink, uintState, uintstatemask)---------set line status, such as highlighting

Wait a minute

2. Get the line number of the selected row

Getting the line number of a selected row, and then processing the row, is a lot of programming.

When the mouse clicks on item, the control sends a Nm_click message to the parent window whose response function is onnmclickxxxx (NMHDR *pnmhdr, LRESULT *presult), where the function comes down to write code to get the line number of the mouse click.

There are two ways to get the line number: The first is to use getfirstselecteditemposition and Getnextselecteditem mates to get it, and the second is to get the mouse position information and then call HitTest function to find the travel number. Examples are as follows:

The first method, which is truncated from MSDN, can be used as a modification.

POSITION pos = plist->getfirstselecteditemposition ();  if (pos = = NULL)     TRACE0 ("No items were selected!\n");  else  {     while (POS)     {        int nitem = Plist->getnextselecteditem (POS);        TRACE1 ("Item%d was selected!\n", nitem);        You could does your own processing on nitem here      }  }  

The second method, the example from my project, can be used after modification.

Get click on the line number   //find mouse position   DWORD Dwpos = Getmessagepos ();  CPoint Point (LoWord (Dwpos), HiWord (Dwpos));  M_listctrl.screentoclient (&point);     Define structure body   lvhittestinfo lvinfo;  lvinfo.pt = point;     Get line number information   int nitem = M_listctrl.hittest (&lvinfo);  if (nitem! =-1)      M_itemsel = Lvinfo.iitem;   Current line number  

The Getmessagepos function prototype is a DWORD Getmessagepos (VOID) that returns a long integer value that represents the position of the cursor at the screen coordinates. This position represents the point the mouse occupies when the previous message was taken by GetMessage.

Return value: The return value gives the x, y coordinates of the cursor position. The x-coordinate is in the low-level integer, and the y-coordinate is high.

HitTest (): Gets the current mouse position of item
In fact, the key is to have screentoclient the use of this function, I did not use this function, HitTest always return-1, make me big head. But this can't be used for subitem, it should be subitemhittest.

For the lvhittestinfo struct, there are four members, in the above HitTest invocation, its first member as input and the other three as output. Specific variable meaning can be viewed on MSDN.

typedef struct _LVHITTESTINFO {point      pt;      UINT flags;      int IItem;      int iSubItem;  } Lvhittestinfo, *lplvhittestinfo;  

  

3. check box operation

Sometimes you need to add a checkbox in front of the item for the user to select and then process all the selected items.

Here are two questions: the first one, how to add a checkbox style, and the second, how to determine if the checkbox state of a row has changed.

For the first question, the basic Operation has been elaborated, that is, through the SetExtendedStyle function to add lvs_ex_checkboxes extension style.

Here we focus on the second problem, first of all, there are two functions to operate the check box state:

BOOL getcheck(int nitem)-------Get check box state

BOOL setcheck(int nitem, BOOL fcheck = TRUE)-------Set check box state

Second, we have to figure out the following four points:

When the item item of the list changes, the control sends a lvn_itemchanged message to the parent window, so the status of the check box can be processed (queried or set) in the response function of the lvn_itemchanged message.

When the mouse clicks the checkbox, the order of the messages is nm_click-> lvn_itemchanged, that is, the status of the checkbox changes after the Nm_click message function ends, in nm_ Invalid use of Getcheck in click.

The order of the messages is lvn_itemchanged-> Nm_click when the mouse clicks on item (not the checkbox area).

The lvn_itemchanged message is also generated when calls the InsertItem function. In view of this, a bool variable m_bhit is usually customized to determine whether a click or insert operation, the variable is initially assigned false, when a mouse click on item is assigned true, detect if a checkbox is clicked and reset to False.

Examples are shown below:

void Cxxxx::onnmclickxxxx (NMHDR *pnmhdr, LRESULT *presult) {//Get click on the line number//find mouse position DWORD Dwpos = Getmessa      Gepos ();      CPoint Point (LoWord (Dwpos), HiWord (Dwpos));      M_listctrl.screentoclient (&point);      Define structure body Lvhittestinfo lvinfo;      lvinfo.pt = point;      Get line number information int nitem = M_listctrl.hittest (&lvinfo);   if (nitem! =-1) M_itemsel = Lvinfo.iitem;         Current line number//Determine if click on CheckBox on if (lvinfo.flags = = Lvht_onitemstateicon) M_bhit = TRUE;  *presult = 0; } void Cxxxx::onlvnitemchangedxxxx (NMHDR *pnmhdr, LRESULT *presult) {Lpnmlistview PNMLV = REINTERPRET_CAST<LP      Nmlistview> (PNMHDR);     Judge M_bhit, that is, whether to click the checkbox if (m_bhit) {m_bhit = FALSE;            Reset if (M_listctrl.getcheck (M_itemsel)) {//checkbox is selected//do your own processing      } else {//checkbox deselect//do your own processing      }} *presult = 0;   }

  

4. Dynamically set the font color of the selected row

Sometimes it may be necessary to set the text of a line as a special color to indicate a particular meaning, such as the information being downloaded is in green, and the download is suspended in gray.

First of all, give a codeproject link, this article is very good, mainly using custom draw. Http://www.codeproject.com/Articles/79/Neat-Stuff-to-Do-in-List-Controls-Using-Custom-Dra

Then, to talk about my approach, here is the main talk about the font color of the selected row of dynamic modification, of course, I also through the above article and my own practice combined.

We need to figure out the following points (can be combined with the following method to modify the font color of a row):

① when the control is drawn, a nm_customdraw message is sent, and the message response function for the message is

void Cxxxx::onnmcustomdrawxxxx (NMHDR *pnmhdr, LRESULT *presult)  {      Lpnmlvcustomdraw PLVCD = reinterpret_cast <LPNMLVCUSTOMDRAW> (PNMHDR);      Todo:add your control notification handler code here       *presult = Cdrf_dodefault;         ............    }  

② wherein,PNMHDR is the input parameter , which points to the Nmlvcustomdraw structure, which contains a lot of information, including font color, background, etc., especially the first member, for Nmcustomdraw struct variable, which contains the current drawing stage(does not know how to compile better), its possible values as shown in (truncated from MSDN)

presult is the output parameter , which determines what message is next sent to Windows (drawing-related), and by sending the message we can go to the processing stage needed for the next step. The specific output value depends on the current drawing stage, as shown in the possible values (truncated from MSDN)

④ has a point to pay attention to (in English, I think it looks more accurate than translation):

One thing to keep on mind are you must always check the draw stage before doing anything else, because your handle R'll receive many messages, and the draw stage determines what action your code takes.

Let's take a look at how to modify the font color of a line:

① First, we should understand that to modify the font color, should be done in the pre-paint phase

② therefore, in the message response function, we first determine whether the Pre-paint stage (that is, plvcd->nmcd.dwdrawstage = = Cdds_prepaint), and then by modifying the output value Presult Value to notify Windows that we need to process each item's message (that is, set *presult = Cdrf_notifyitemdraw).

When ③ enters the message response function again, we determine whether it is in the Pre-paint stage of item (that is, plvcd->nmcd.dwdrawstage = = Cdds_itemprepaint), and if so, to modify the font color and so on.

④ after processing is finished, reset *presult = Cdrf_dodefault, indicating that we no longer need other special messages, the default execution.

Examples are as follows:

void Cxxxx::onnmcustomdrawxxxx (NMHDR *pnmhdr, LRESULT *presult)  {      Lpnmlvcustomdraw PLVCD = reinterpret_cast <LPNMLVCUSTOMDRAW> (PNMHDR);      *presult = Cdrf_dodefault;        First Thing-check the draw stage. If It's the control ' s pre-paint stage,        //Then tell Windows we want messages for every item.       if (Cdds_prepaint = = plvcd->nmcd.dwdrawstage)      {          *presult = Cdrf_notifyitemdraw;      }      else if (Cdds_itemprepaint = = plvcd->nmcd.dwdrawstage)      {//This was the          notification message for an item.
   //processing, change item to the background color           if (/* match condition */)          Plvcd->clrtext = RGB (255,0,255);                       *presult = Cdrf_dodefault;      }  }  

  

The method discussed above is mainly used to set the static font color, of course, if your list of information is constantly changing (that is, with Setitemtext constantly modified), then also implemented a dynamic change, otherwise you need to call the redraw function in the appropriate place:

BOOL redrawitems (int nfirst, int nlast)

Represents a row between Nfirst and nlast that needs to be redrawn.

5. Set the background color of the selected row

Sets the background color of the selected row to display the selected rows in a special color, which is easy to understand which line is currently being processed. Despite highlighting, highlighting is focus-based, and if you select a line and then focus shifts, it's impossible to tell which line you've chosen.

The method of setting the background color of the selected row and the method of modifying the font color in section Fourth are similar, all using custom Draw. This involves setting a special color for the currently selected behavior, and restoring the color of the previous selected row, or it will be messy. Therefore, it is not difficult to record the line number of the previous selected row and the currently selected line, and I believe that through the previous summary, this is not hard to achieve. Then redraw between the currently selected row and the previous selected line.

Examples are as follows:

voidCxxxx::onnmclickxxxx (NMHDR *pnmhdr, LRESULT *PResult) {      //... ....//redraw Item, change background color    intNfirst =min (M_itemsel,m_itemforesel); intNlast =Max (M_itemsel,m_itemforesel);  M_listctrl.redrawitems (Nfirst, nlast); //redraw between the previous selected item and the currently selected item*presult =0; }  voidCxxxx::onnmcustomdrawxxxx (NMHDR *pnmhdr, LRESULT *PResult) {Lpnmlvcustomdraw PLVCD= reinterpret_cast<lpnmlvcustomdraw>(PNMHDR); *presult =Cdrf_dodefault; //First Thing-check the draw stage. If it ' s the control ' s Prepaint//stage, then tell the Windows we want messages for every item.     if(Cdds_prepaint = = plvcd->nmcd.dwdrawstage) {*presult =Cdrf_notifyitemdraw; }          Else if(Cdds_itemprepaint = = plvcd->nmcd.dwdrawstage) {//The notification message for a item. //handle, change item to background color        if(M_itemsel = = plvcd->nmcd.dwitemspec) {//the currently selected itemPLVCD-&GT;CLRTEXTBK = RGB (255,0,0); }          Else if(M_itemforesel = = plvcd->nmcd.dwitemspec) {//previous selected item, revert to whitePLVCD-&GT;CLRTEXTBK = RGB (255,255,255); }                    *presult =Cdrf_dodefault; }  }  

from:http://blog.csdn.net/zwgdft/article/details/7560592

CListCtrl usage and summary (by how to hide Listctrl list header sort Small triangle this bug learned knowledge)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.