Common Listview LVN_ITEMCHANGED error

Started by Paul Squires, February 04, 2010, 11:43:53 AM

Previous topic - Next topic

Paul Squires

I often times fall into this trap and it can be confusing if you do not realize what is happening. When the LVN_ITEMCHANGED notification fires, it is not always at the exact time that the new row gains focus.

Actually, the previous row fires the notification as it loses focus and then the row gaining focus also fires it. If you have code in your LVN_ITEMCHANGED message hanler thinking that it is only dealing with the new row then you might see some strange side effects.

You should also ensure that your Listview has the LVS_SINGLESEL windowstyle set if you do not want multiple rows selected.

The solution is to test the row to see if it has focus and if it does then execute the code need (for example, to show data in another control based on what line in the ListView has focus).

Here is the simple code:


Function FRMCHARTLIST_LISTVIEW1_LVN_ITEMCHANGED ( _
                                                ControlIndex  As Long,            _  ' index in Control Array
                                                hWndForm      As Dword,           _  ' handle of Form
                                                hWndControl   As Dword,           _  ' handle of Control
                                                ByVal lpNMV   As NM_LISTVIEW Ptr  _  ' pointer to NM_LISTVIEW
                                                ) As Long

   If IsTrue (@lpNMV.uNewState And %LVIS_SELECTED) Then
      ' Do whatever you want with the new line that now has focus.
      ' The line number (zero-based) is in @lpNMV.iItem
   End If   
   
End Function

Paul Squires
PlanetSquires Software

Rolf Brandt

That explains a lot of things. Thanks a lot.
Rolf Brandt
http://www.rbsoft.eu
http://www.taxifreeware.com
I cook with wine, sometimes I even add it to the food.
(W. C. Fields)

Roger Garstang

Most my apps anymore I cycle through searching through selected items, so been a while since I used that method.  Don't you also have to watch out for no item selected where it is -1?