Create Listview Controls
//=============================================================================
//COMMON CONTROLS: LISTVIEW - Copyright © 2000,2005 Ken Fitlike
//=============================================================================
//API functions used: CreateWindowEx,DefWindowProc,DestroyIcon,DispatchMessage,
//ExtractIcon,GetMessage,GetSystemMetrics,ImageList_AddIcon,ImageList_Create,
//ImageList_Destroy,InitCommonControlsEx,LoadImage,MessageBox,PostQuitMessage,
//RegisterClassEx,ShowWindow,UpdateWindow,TranslateMessage,WinMain.
//=============================================================================
//This demonstrates the creation of a listview common control.
//
//BCC55 - Link with comctl32.lib
//MINGW - Link with libcomctl32.a (-lcomctl32)
//MSVC  - Link with comctl32.lib
//=============================================================================
#include <windows.h>  //include all the basics
#include <tchar.h>    //string and other mapping macros

#if defined __MINGW_H
#define _WIN32_IE 0x0400
#endif
#include <commctrl.h>

#include <string>

//define an unicode string type alias
typedef std::basic_string<TCHAR> ustring;
//=============================================================================
//message processing function declarations
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
int OnCreate(const HWND,CREATESTRUCT*);
void OnDestroy(const HWND);
void OnSize(const HWND,int,int,UINT);

//non-message function declarations
HWND CreateListview(const HWND,const HINSTANCE,DWORD,const RECT&,const int);
inline int ErrMsg(const ustring&);
void StartCommonControls(DWORD);

//setup some control id's
enum {
  IDC_IPADDRESS=200
};

struct LVHandles
{
HWND       hListview;
HIMAGELIST hLargeIcons;
HIMAGELIST hSmallIcons;
};
//=============================================================================
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE,LPSTR pStr,int nCmd)
{
ustring classname=_T("SIMPLEWND");
WNDCLASSEX wcx={0};  //used for storing information about the wnd 'class'

wcx.cbSize         = sizeof(WNDCLASSEX);           
wcx.lpfnWndProc    = WndProc;             //wnd Procedure pointer
wcx.hInstance      = hInst;               //app instance
//use 'LoadImage' to load wnd class icon and cursor as it supersedes the 
//obsolete functions 'LoadIcon' and 'LoadCursor', although these functions will 
//still work. Because the icon and cursor are loaded from system resources ie 
//they are shared, it is not necessary to free the image resources with either 
//'DestroyIcon' or 'DestroyCursor'.
wcx.hIcon         = reinterpret_cast<HICON>(LoadImage(0,IDI_APPLICATION,
                                            IMAGE_ICON,0,0,LR_SHARED));
wcx.hCursor       = reinterpret_cast<HCURSOR>(LoadImage(0,IDC_ARROW,
                                              IMAGE_CURSOR,0,0,LR_SHARED));
wcx.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);   
wcx.lpszClassName = classname.c_str(); 
//the window 'class' (not c++ class) has to be registered with the system
//before windows of that 'class' can be created
if (!RegisterClassEx(&wcx))
  {
  ErrMsg(_T("Failed to register wnd class"));
  return -1;
  }

int desktopwidth=GetSystemMetrics(SM_CXSCREEN);
int desktopheight=GetSystemMetrics(SM_CYSCREEN);

HWND hwnd=CreateWindowEx(0,                     //extended styles
                         classname.c_str(),     //name: wnd 'class'
                         _T("Common Controls - Listview"), //wnd title
                         WS_OVERLAPPEDWINDOW,   //wnd style
                         desktopwidth/4,        //position:left
                         desktopheight/4,       //position: top
                         desktopwidth/2,        //width
                         desktopheight/2,       //height
                         0,                     //parent wnd handle
                         0,                     //menu handle/wnd id
                         hInst,                 //app instance
                         0);                    //user defined info
if (!hwnd)
  {
  ErrMsg(_T("Failed to create wnd"));
  return -1;
  }

ShowWindow(hwnd,nCmd); 
UpdateWindow(hwnd);
//start message loop - windows applications are 'event driven' waiting on user,
//application or system signals to determine what action, if any, to take. Note 
//that an error may cause GetMessage to return a negative value so, ideally,  
//this result should be tested for and appropriate action taken to deal with 
//it(the approach taken here is to simply quit the application).
MSG msg;
while (GetMessage(&msg,0,0,0)>0)
  {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
  }
return static_cast<int>(msg.wParam);
}
//=============================================================================
LRESULT CALLBACK WndProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch (uMsg)
  {
  case WM_CREATE:
    {
    return OnCreate(hwnd,reinterpret_cast<CREATESTRUCT*>(lParam));
    }
  case WM_DESTROY:
    {
    OnDestroy(hwnd);
    return 0;
    }
  case WM_SIZE:
    OnSize(hwnd,LOWORD(lParam),HIWORD(lParam),static_cast<UINT>(wParam));
    return 0;
  default:
    //let system deal with msg
    return DefWindowProc(hwnd,uMsg,wParam,lParam);  
  }
}
//=============================================================================
int OnCreate(const HWND hwnd,CREATESTRUCT *cs)
{
//handles the WM_CREATE message of the main, parent window; return -1 to fail
//window creation
RECT rc={0,0,0,0};  //dimesnions will be set in WM_SIZE handler 
StartCommonControls(ICC_LISTVIEW_CLASSES); //ICC_WIN95_CLASSES can also be used

//create storage for struct to contain information about the listview (window
//and image list handles).
LVHandles *lvh=new LVHandles;

//now store that pointer as the user data associated with the
//parent window so that it can be retrieved for later use. This will emit a 
//C4244 warning if /wp64 is enabled with ms compilers under win32 due to how 
//SetWindowLongPtr is typedef'd for 32bit and 64bit compatibility. The warning
//in this context can be safely ignored. Despite this being identified as a 
//glitch under msvc.net 2003, it still exists in the later msvc express 2005. 
//A workaround would be to wrap the offending call in #pragma warning 
//directives, or to typedef the fn properly for 32/64 bit compatibility. 
//See http://msdn.microsoft.com/msdnmag/issues/01/08/bugslayer/
//for details.
SetWindowLongPtr(hwnd,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(lvh));

lvh->hListview=CreateListview(hwnd,cs->hInstance,LVS_ICON,rc,IDC_IPADDRESS);

//set up and attach image lists to list view common control
//create the image lists
lvh->hLargeIcons=ImageList_Create(GetSystemMetrics(SM_CXICON),
                                  GetSystemMetrics(SM_CYICON),
                                  ILC_COLOR32|ILC_MASK,1,1); 
lvh->hSmallIcons=ImageList_Create(GetSystemMetrics(SM_CXSMICON),
                                  GetSystemMetrics(SM_CYSMICON),
                                  ILC_COLOR32|ILC_MASK,1,1);
                               
//add icons to imagelists. The icons are loaded from "shell32.dll". 
//ExtractIcon is used firstly to get the total number of icon groups and 
//secondly to load one of each group individually.
int nNumIcons=static_cast<int>(reinterpret_cast<INT_PTR>(ExtractIcon(0,
                _T("shell32.dll"),static_cast<UINT>(-1))));

HICON hIcon;
LVITEM lvi={0};

lvi.mask=LVIF_TEXT|LVIF_IMAGE;
int i;
for (i=0;i<nNumIcons;++i)
  {
  hIcon=ExtractIcon(0,_T("shell32.dll"),i);
  ImageList_AddIcon(lvh->hLargeIcons,hIcon); 
  ImageList_AddIcon(lvh->hSmallIcons,hIcon); 
  DestroyIcon(hIcon); 
  }
//attach image lists to list view common control
ListView_SetImageList(lvh->hListview,lvh->hLargeIcons,LVSIL_NORMAL); 
ListView_SetImageList(lvh->hListview,lvh->hSmallIcons,LVSIL_SMALL);

//add some items to the the list view common control
        
//flags to determine what information is to be set
TCHAR chBuffer[16];   
for (i=0;i<nNumIcons;++i)
  {
  lvi.iItem=i;                     //the zero-based item index 
  wsprintf(chBuffer,_T("%d"),i);   //convert item index int to string
  lvi.pszText=chBuffer;            //item label
  lvi.cchTextMax=lstrlen(chBuffer);//length of item label
  lvi.iImage=i;                    //image list index
  SendMessage(lvh->hListview,LVM_INSERTITEM,0,(LPARAM)&lvi);
  }

return 0;
}
//=============================================================================
void OnDestroy(const HWND hwnd)
{
//free up resources - first get the information which has been previously
//stored as the user data of the main window
LVHandles *lvh=reinterpret_cast<LVHandles*>(static_cast<LONG_PTR>
                                   (GetWindowLongPtr(hwnd,GWLP_USERDATA)));
ImageList_Destroy(lvh->hLargeIcons);
ImageList_Destroy(lvh->hSmallIcons);
delete lvh;
    
PostQuitMessage(0);    //signal end of application
}
//=============================================================================
void OnSize(const HWND hwnd,int cx,int cy,UINT uFlags)
{
//get the pointer to listview information which has been previously stored in  
//the user data associated with the parent window.
LVHandles *lvh=reinterpret_cast<LVHandles*>(static_cast<LONG_PTR>
                                   (GetWindowLongPtr(hwnd,GWLP_USERDATA)));
//resize the listview control so it fills the parent window's client area
MoveWindow(lvh->hListview,0,0,cx,cy,1);
//arrange contents of listview along top of control
SendMessage(lvh->hListview,LVM_ARRANGE,LVA_ALIGNTOP,0);
}
//=============================================================================
HWND CreateListview(const HWND hParent,const HINSTANCE hInst,DWORD dwStyle,
                    const RECT& rc,const int id)
{
dwStyle|=WS_CHILD|WS_VISIBLE;
return CreateWindowEx(0,                  //extended styles
                      WC_LISTVIEW,        //control 'class' name
                      0,                  //control caption
                      dwStyle,            //wnd style
                      rc.left,            //position: left
                      rc.top,             //position: top
                      rc.right,           //width
                      rc.bottom,          //height
                      hParent,            //parent window handle
                      //control's ID
                      reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),
                      hInst,              //instance
                      0);                 //user defined info
}
//=============================================================================
inline int ErrMsg(const ustring& s)
{
return MessageBox(0,s.c_str(),_T("ERROR"),MB_OK|MB_ICONEXCLAMATION);
}
//=============================================================================
void StartCommonControls(DWORD flags)
{
//load the common controls dll, specifying the type of control(s) required 
INITCOMMONCONTROLSEX iccx;
iccx.dwSize=sizeof(INITCOMMONCONTROLSEX);
iccx.dwICC=flags;
InitCommonControlsEx(&iccx);
}
//=============================================================================