public const UInt32 LVM_GETCOLUMN = 4121;
public const UInt32 LVCF_ORDER = 0x0020;
// Define the LVCOLUMN for use with interop
[StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
private struct LVCOLUMN
{
public uint mask;
public int fmt;
public int cx;
public IntPtr pszText;
public int cchTextMax;
public int iSubItem;
public int iImage;
public int iOrder;
}
// Declare two overloaded SendMessage functions. The
// difference is in the last parameter.
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, UInt32 wParam, UInt32 lParam);
//sortIconImageList 中需要包括向下和向上的小图标
public static void SetHeaderSortIcon(ListView listView,
int sortColumnIndex,
ImageList sortIconImageList,
int sortIconIndex)
{
try
{
IntPtr hc;
int i;
// Assign the ImageList to the header control.
// The header control includes all columns.
// Get a handle to the header control.
hc = SendMessage(listView.Handle, LVM_GETHEADER, (UInt32)0, (UInt32)0);
// Add the image list to the header control.
SendMessage(hc, HDM_SETIMAGELIST, (UInt32)0, (UInt32)sortIconImageList.Handle);
// Set the image for each column.
//
// In the following code, we use successive images in the image list to place on
// successive columns in the ColumnHeader by looping through all columns.
//
// The LVCOLUMN is also used to define alignment,
// so by using it here, we are resetting the alignment if it was defined
// in the designer. If you need to set the alignment, you will need to change
// the code below to set it here.
//
for (i = 0; i < listView.Columns.Count; i++)
{
// Use the LVM_SETCOLUMN message to set the column's image index.
LVCOLUMN col;
// col.mask: include LVCF_FMT | LVCF_IMAGE
col.mask = LVCF_FMT | LVCF_IMAGE;
// LVCFMT_IMAGE
col.fmt = LVCFMT_IMAGE;
col.fmt |= 0x1000;
// The image to use from the image list.
if (i == sortColumnIndex)
col.iImage = sortIconIndex;
else
col.iImage = -1; //No image when it is -1
// Send the LVM_SETCOLUMN message.
// The column that we are assigning the image to is defined in the third parameter.
SendMessage(listView.Handle, LVM_SETCOLUMN, (UInt32)i, ref col);
}
}
class ListViewItemComparer : System.Collections.IComparer
{
private int col;
public ListViewItemComparer()
{
col = 0;
}
public ListViewItemComparer(int column)
{
col = column;
}
public int Compare(object x, object y)
{
return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
}
}