MFC Grid control 2.27

原文链接地址:http://www.codeproject.com/Articles/8/MFC-Grid-control

MFCGridCtrl是个强大的类,用于数据的表格显示。

1.类特征

    • Cell selection using the mouse, with optional Control and Shift key combinations. Selection can be disabled.
    • Row and Column resizing. Sizing can be disabled for row, columns or both.
    • Auto row or column sizing when dividers are double-clicked.
    • Any number of fixed rows and columns.
    • Individual cells can have separate text and background colours.
    • Individual cells can have separate fonts.
    • Individual cells can be marked "Read-Only", or have their modification status set and checked.
    • OLE Drag and drop.
    • Ctrl-C, Ctrl-X and Ctrl-V perform clipboard copy, cut and paste, and Ctrl-A for "Select All"
    • In place editing of cell contents. If a character key is pressed while a cell has focus, editing will start on that cell, and the arrow keys will allow navigation to other keys. If the current focus cell is clicked on, editing will start and the arrow keys will move the carat inside the edit control. Editing can be disabled.
    • Support for Microsoft intellimouse.
    • Optional grid lines.
    • Images in any cell
    • "Virtual" mode for large datasets
    • Full printing support, for either a Doc/View environment (inc Print preview) or a standalone dialog based app (no print preview).
    • Optional "List mode", including full row selection, single row selection, and sort on column header click.
    • Numerous virtual functions to allow this control to be extended very easily.
    • Unicode support.
    • WinCE support
    • Titletips for cells that are too small to display their data.
    • Hidden rows and columns
    • Compiles under VC 4.2, 5.0, 6.0 and under the CE toolkit version 2.0 and 3.0

2.构造

CGridCtrl grid;
grid.Create(rect, pParentWnd, nID);

3.行列数相关函数

int GetRowCount() const            //Returns the number of rows (including fixed rows)
int GetColumnCount() const //Returns the number of columns (including fixed columns)
int GetFixedRowCount() const //Returns the number of fixed rows
int GetFixedColumnCount() const //Returns the number of fixed columns
BOOL SetRowCount(int nRows) //Sets the number of rows (including fixed rows), Returning TRUE on success.
BOOL SetColumnCount(int nCols) //Sets the number of columns (including fixed columns), Returning TRUE on success.
BOOL SetFixedRowCount(int nFixedRows = 1) //Sets the number of fixed rows, returning TRUE on success.
BOOL SetFixedColumnCount(int nFixedCols = 1) //Sets the number of columns, returning TRUE on success.

4.大小与位置

int GetRowHeight(int nRow) const        //Gets the height of row nRow.
BOOL SetRowHeight(int row, int height) //Sets the height of row nRow.
int GetColumnWidth(int nCol) const //Gets the width of column nCol
BOOL SetColumnWidth(int col, int width) //Sets the width of column nCol.
int GetFixedRowHeight() const //Gets the combined height of the fixed rows.
int GetFixedColumnWidth() const //Gets the combined width of the fixed columns.
long GetVirtualHeight() const //Gets the combined height of all the rows.
long GetVirtualWidth() const //Gets the combined width of all the columns.

获取cell位置及矩形

BOOL GetCellOrigin(int nRow, int nCol, LPPOINT p);
BOOL GetCellOrigin(const CCellID& cell, LPPOINT p); BOOL GetCellRect(int nRow, int nCol, LPRECT pRect);
BOOL GetCellRect(const CCellID& cell, LPRECT pRect); BOOL GetTextRect(const CCellID& cell, LPRECT pRect);
BOOL GetTextRect(int nRow, int nCol, LPRECT pRect); CSize GetTextExtent(int nRow, int nCol, LPCTSTR str);
CSize GetCellTextExtent(int nRow, int nCol);

5.行列排序

void Reorder(int From, int To); //Reorders a row 'From' to row 'To'
void AllowReorderColumn(bool b=true) // Whether or not columns can be reordered
void EnableDragRowMode(bool b=true) //Whether or not rows can be reordered via drag and drop
int GetLayer(int** pLayer) // Returns a pointer to an array of ints representing the current ordering of the grid. Do not forget to delete *pLayer when you are finished
void SetLayer(int* pLayer) //Sets the ordering of the grid based on a previous saved state.

6.虚模式

void SetVirtualMode(BOOL bVirtual) //Places the grid in or out of virtual mode.
BOOL GetVirtualMode() //Returns TRUE if the grid is in virtual mode

虚模式需要回调函数,如果不设置则会给父窗口发送GVN_GETDISPINFO通知消息

回调函数格式如下:

void SetCallbackFunc(GRIDCALLBACK pCallback,
LPARAM lParam)
GRIDCALLBACK GetCallbackFunc()

GV_DISPINFO结构如下:

typedef struct tagGV_DISPINFO {
NMHDR hdr;
GV_ITEM item;
} GV_DISPINFO;

在显示cell时,Grid会发送GVN_ODCACHEHINT消息

GV_CACHEHINT结构如下:

typedef struct tagGV_CACHEHINT {
NMHDR hdr;
CCellRange range;
} GV_CACHEHINT;

处理这些消息的一个例子:

// m_Grid is a member variable of a dialog class that is handling
// this message
BOOL CGridCtrlDemoDlg::OnNotify(WPARAM wParam, LPARAM lParam,
LRESULT* pResult)
{
if (wParam == (WPARAM)m_Grid.GetDlgCtrlID())
{
*pResult = 1;
GV_DISPINFO *pDispInfo = (GV_DISPINFO*)lParam;
if (GVN_GETDISPINFO == pDispInfo->hdr.code)
{
//TRACE2("Getting Display info for cell %d,%d\n",
pDispInfo->item.row, pDispInfo->item.col);
pDispInfo->item.strText.Format(_T("Message %d,%d"),
pDispInfo->item.row, pDispInfo->item.col);
return TRUE;
}
else if (GVN_ODCACHEHINT == pDispInfo->hdr.code)
{
GV_CACHEHINT *pCacheHint = (GV_CACHEHINT*)pDispInfo;
TRACE(_T("Cache hint received for cell range %d,%d - %d,%d\n"),
pCacheHint->range.GetMinRow(),
pCacheHint->range.GetMinCol(),
pCacheHint->range.GetMaxRow(),
pCacheHint->range.GetMaxCol());
}
} return CDialog::OnNotify(wParam, lParam, pResult);
}

你可以通过SetCallbackFunc()设置回调函数来直接替代发送GVN_GETDISPINFO消息,但是GVN_ODCACHEHINT消息依旧会发送。

回调函数格式如下:

BOOL CALLBACK CallbackFunction(GV_DISPINFO * pDispInfo, LPARAM lParam);

回调函数例子:

BOOL CALLBACK CGridCtrlDemoDlg::GridCallback(GV_DISPINFO *pDispInfo,
LPARAM /*lParam*/)
{
pDispInfo->item.strText.Format(_T("Callback %d,%d"),
pDispInfo->item.row, pDispInfo->item.col);
return TRUE;
}

当调用SetCallbackFunc,可以指定LPARAM参数发送给回调函数。

7.一般函数

void SetImageList(CImageList* pList)            //Sets the current image list for the grid. The control only takes a copy of the pointer to the image list, not a copy of the list itself.
CImageList* GetImageList() //Gets the current image list for the grid.
void SetGridLines(int nWhichLines = GVL_BOTH) //Sets which (if any) gridlines are displayed. See here for possible values.
int GetGridLines() //Gets which (if any) gridlines are displayed. See here for possible return values.
void SetEditable(BOOL bEditable = TRUE) //Sets if the grid is editable.
BOOL IsEditable() //Gets whether or not the grid is editable.
void SetListMode(BOOL bEnableListMode = TRUE) //Sets the grid into (or out of) List mode. When the grid is in list mode, full row selection is enabled and clicking on the column header will sort the grid by rows.
BOOL GetListMode() //Get whether or not the grid is in list mode.
void SetSingleRowSelection(BOOL bSing = TRUE) //Sets the grid into (or out of) Single row selection mode. This mode is only effective when in ListMode. When in this mode, only a single row at a time can be selected, so the grid behaves somewhat like a multicolumn listbox.
BOOL GetSingleRowSelection() //Get whether or not the grid is in single row selection mode.
void SetSingleColSelection(BOOL bSing = TRUE) //Sets the grid into (or out of) Single column selection mode. When in this mode, only a single column at a time can be selected.
BOOL GetSingleColSelection() //Get whether or not the grid is in single column selection mode.
void EnableSelection(BOOL bEnable = TRUE) //Sets whether or not the grid cells can be selected.
BOOL IsSelectable() //Get whether or not grid cells are selectable.
void SetFixedRowSelection(BOOL bSelect) //Set whether or not clicking on a fixed row selects the cells next to it.
BOOL GetFixedRowSelection() //Get whether or not clicking on a fixed row selects the cells next to it.
void SetFixedColumnSelection(BOOL bSelect) //Set whether or not clicking on a fixed column selects the cells underneath.
BOOL GetFixedColumnSelection() //Get whether or not clicking on a fixed column selects the cells underneath.
void EnableDragAndDrop(BOOL bAllow = TRUE) //Sets whether drag and drop is enabled.
BOOL GetDragAndDrop() //Get whether drag and drop is allowed.
void SetRowResize(BOOL bResize = TRUE) //Sets whether or not rows can be resized.
BOOL GetRowResize() //Gets whether or not rows can be resized.
void SetColumnResize(BOOL bResize = TRUE) //Sets whether or not columns can be resized.
BOOL GetColumnResize() //Gets whether or not columns can be resized.
void SetHandleTabKey(BOOL bHandleTab = TRUE) //Sets whether or not the TAB key is used to move the cell selection.
BOOL GetHandleTabKey() //Gets whether or not the TAB key is used to move the cell selection.
void SetDoubleBuffering(BOOL bBuffer = TRUE) //Sets whether or not double buffering is used when painting (avoids flicker).
BOOL GetDoubleBuffering() //Gets whether or not double buffering is used when painting.
void EnableTitleTips(BOOL bEnable = TRUE) //Sets whether or not titletips are used.
BOOL GetTitleTips() //Gets whether or not titletips are used.
void SetTrackFocusCell(BOOL bTrack) //Sets whether or not the fixed cells on the same row/column as the current focus cell are highlighted with a sunken border
BOOL GetTrackFocusCell() //Gets whether or not the fixed cells on the same row/column as the current focus cell are highlighted with a sunken border
void SetFrameFocusCell(BOOL bFrame) //Sets whether or not the cell with the focus is highlighted with a framed border
BOOL GetFrameFocusCell() //Gets whether or not the focus cell is highlighted with a framed border
void SetAutoSizeStyle(int nStyle = GVS_BOTH) //Sets how the auto-sizing should be performed. GVS_BOTH = use fixed and non fixed cells; GVS_HEADER = use only the fixed cells; GVS_DATA = use only non-fixed cells.
int GetAutoSizeStyle() //Gets how the auto-sizing should be performed
void EnableHiddenColUnhide(BOOL bEnable = TRUE) //Sets whether or not hidden (0-width) columns can be unhidden by the user resizing the column.
BOOL GetHiddenColUnhide() //Gets whether or not hidden (0-width) columns can be unhidden by the user resizing the column.
void EnableHiddenRowUnhide(BOOL bEnable = TRUE) //Sets whether or not hidden (0-height) rows can be unhidden by the user resizing the row.
BOOL GetHiddenRowUnhide() //Gets whether or not hidden (0-height) rows can be unhidden by the user resizing the row.
void EnableColumnHide(BOOL bEnable = TRUE) //Sets whether or columns can be contracted to 0 width via mouse.
BOOL GetColumnHide() //Gets whether or not columns can be contracted to 0 width via mouse.
void EnableRowHide(BOOL bEnable = TRUE) //Sets whether or not rows can be contracted to 0 height via mouse.
BOOL GetRowHide() //ets whether or not rows can be contracted to 0 height via mouse.

8.颜色相关

void SetGridBkColor(COLORREF clr)                    //Sets the background colour of the control (the area outside fixed and non-fixed cells).
COLORREF GetGridBkColor() //Gets the background colour of the control.
void SetGridLineColor(COLORREF clr) //Sets the colour of the gridlines.
COLORREF GetGridLineColor() //Gets the colour of the grid lines.
COLORREF GetTitleTipBackClr() //Gets the background colour of the titletips.
void SetTitleTipBackClr(COLORREF clr = CLR_DEFAULT) //Sets the background colour of the titletips.
COLORREF GetTitleTipTextClr() //Gets the text colour of the titletips.
void SetTitleTipTextClr(COLORREF clr = CLR_DEFAULT) //Sets the text colour of the titletips.

以下函数不再支持:可以通过GetDefaultCell 再设置响应的颜色

void SetTextColor(COLORREF clr)            //Sets the colour of the text in non-fixed cells.
COLORREF GetTextColor() //Gets the colour of the text in non-fixed cells.
void SetTextBkColor(COLORREF clr) //Sets the background colour of the non-fixed cells.
COLORREF GetTextBkColor() //Gets the background colour of the non-fixed cells.
void SetFixedTextColor(COLORREF clr) //Sets the colour of the text in fixed cells.
COLORREF GetFixedTextColor() //Gets the colour of the text in fixed cells.
void SetFixedBkColor(COLORREF clr) //Sets the background colour of the fixed cells.
COLORREF GetFixedBkColor() //Gets the background colour of the fixed cells.
void SetBkColor(COLORREF clr) //Sets the background colour of the control (the area outside fixed and non-fixed cells).
COLORREF GetBkColor() //Gets the background colour of the control.
void SetGridColor(COLORREF clr) //Sets the colour of the gridlines.
COLORREF GetGridColor() //Gets the colour of the grid lines.

9.获取Cell相关信息

CGridCellBase* GetDefaultCell(BOOL bFixedRow,BOOL bFixedCol) const
//Gets a pointer to the default cell implementation for the desired cell type. bFixedRow and bFixedCol specify whether the cell is fixed (in row, column or both) or unfixed.
//Use this to set default properties for the grid. Actual cells in the grid have their values set as default values when they are first created.
//They will use GetDefaultCell to query the grids default cell properties and use these values for drawing themselves. CGridCellBase* GetCell(int nRow, int nCol) const //Gets the actual cell for the given row/column (or NULL on failure)
BOOL SetCellType(int nRow, int nCol,CRuntimeClass* pRuntimeClass); //Sets the cell class type.
BOOL SetDefaultCellType(CRuntimeClass* pRuntimeClass); //Sets the default cell class type for new cells.
void SetModified(BOOL bModified = TRUE, int nRow = -1, int nCol = -1)
//Sets the modified flag for a cell. If no row or columns is specified, then change affects the entire grid.
BOOL GetModified(int nRow = -1, int nCol = -1) //Sets the modified flag for a cell, or if no cell, it returns the status for the entire grid.
BOOL IsCellFixed(int nRow, int nCol) //Returns TRUE if the cell is a fixed cell.
BOOL IsItemEditing(int nRow, int nCol) //Returns TRUE if the cell is currently being edited.
BOOL SetItem(const GV_ITEM* pItem) //Sets the contents of a cell with the values from the GV_ITEM structure.
//Note that the value of the mask field will determine which values are actually changed (cf. CListCtrl::SetItem).
BOOL GetItem(GV_ITEM* pItem) //Fills the GV_ITEM structure with values from the specified cell.
//Note that the value of the mask field will determine which values are actually retrieved (cf. CListCtrl::GetItem).
BOOL SetItemText(int nRow, int nCol, LPCTSTR str) //Sets the text for the given cell. Returns TRUE on success
virtual CString GetItemText(int nRow, int nCol) //Gets the text for the given cell. This function is virtual in order to aid extensibility.
// No more messing around with LVN_GETDISPINFO messages or string pooling! BOOL SetItemData(int nRow, int nCol, LPARAM lParam) //Sets the lParam (user-defined data) field for the given cell. Returns TRUE on success. See also GV_ITEM.
LPARAM GetItemData(int nRow, int nCol) const //Gets the lParam (user-defined data) field for the given cell. See also GV_ITEM. BOOL SetItemImage(int nRow, int nCol, int iImage) // Sets the image index for the given cell. Returns TRUE on success. See also GV_ITEM.
int GetItemImage(int nRow, int nCol) const //Gets the image index for the given cell. BOOL SetItemState(int nRow, int nCol, UINT state) // Sets the state of the given cell. Returns TRUE on success. See also GV_ITEM.
UINT GetItemState(int nRow, int nCol) const // Gets the state of the given cell. See also GV_ITEM. BOOL SetItemFormat(int nRow, int nCol, UINT nFormat) //Sets the format of the given cell. Returns TRUE on success.
// Default implementation of cell drawing uses CDC::DrawText, so any of the DT_* formats are available. See also GV_ITEM.
UINT GetItemFormat(int nRow, int nCol) const //Gets the format of the given cell (default returns a CDC::DrawText DT_* format). See also GV_ITEM.
int GetSelectedCount() //Gets the number of selected cells.
CCellID GetFocusCell() //Gets the cell with the focus. See also CCellID. CCellID SetFocusCell(CCellID cell);
CCellID SetFocusCell(int nRow, int nCol); //Sets the cell with the focus BOOL SetItemBkColour(int nRow, int nCol, COLORREF cr = CLR_DEFAULT) //Sets the background colour of the given cell. Returns TRUE on success. See also GV_ITEM.
COLORREF GetItemBkColour(int nRow, int nCol) //const Gets the background colour of the given cell. See also GV_ITEM. BOOL SetItemFgColour(int nRow, int nCol,COLORREF cr = CLR_DEFAULT) //Sets the foreground colour of the given cell. Returns TRUE on success. See also GV_ITEM.
COLORREF GetItemFgColour(int nRow, int nCol) const //Gets the foreground colour of the given cell. See also GV_ITEM. BOOL SetItemFont(int nRow, int nCol, LOGFONT* lf) //Sets the font of the given cell. Returns TRUE on success. See also GV_ITEM.
LOGFONT* GetItemFont(int nRow, int nCol) const //Gets the font of the given cell. See also GV_ITEM.
BOOL IsItemEditing(int nRow, int nCol) //Returns TRUE if the cell is currently being edited.
void EnsureVisible(CCellID &cell) //Ensures that the specified cell is visible. BOOL IsCellVisible(CCellID &cell) const
BOOL IsCellVisible(CCellID cell) const //Returns TRUE if the cell is visible. BOOL IsCellEditable(CCellID &cell) const
BOOL IsCellEditable(CCellID cell) const //Returns TRUE if the cell is editable. BOOL IsCellSelected(CCellID &cell) const
BOOL IsCellSelected(CCellID cell) const //Returns TRUE if the cell is selected
void EnsureVisible(int nRow, int nCol) //Ensures that the specified cell is visible.
BOOL IsCellFixed(int nRow, int nCol) //Returns TRUE if the given cell is a fixed cell
int GetDefCellHeight() const //Returns the default cell height (for new cells)
void SetDefCellHeight(int nHeight) //Sets the default cell height (for new cells). This will be overridden if SetFont is called
int GetDefCellWidth() const //Returns the default cell width (for new cells)
void SetDefCellWidth(int nWidth) //Sets the default cell width (for new cells). This will be overridden if SetFont is called
int GetDefCellWidth() const //Returns the default cell internal margin
void SetDefCellMargin(int nMargin) //Sets the default cell internal margin.

10.操作

int InsertColumn(LPCTSTR strHeading,UINT nFormat, int nColumn = -1)
//Inserts a column at the position given by nCol, or at the end of all columns if nCol is < 0.
//strHeading is the column heading and nFormat the format. Returns the position of the inserted column. int InsertRow(LPCTSTR strHeading,int nRow = -1)
//Inserts a row at the position given by nRow, or at the end of all rows if nRow is < 0.
// strHeading is the row heading. The format of each cell in the row will be that of the cell in the first row of the same column. Returns the position of the inserted row. BOOL DeleteColumn(int nColumn) //Deletes column "nColumn", return TRUE on success.
BOOL DeleteRow(int nRow) //Deletes row "nRow", return TRUE on success.
BOOL DeleteAllItems() //Deletes all rows and contents in the grid.
BOOL DeleteNonFixedRows() //Deletes all non-fixed rows in the grid.
BOOL AutoSizeRow(int nRow, BOOL bResetScroll=TRUE)
// Auto sizes the row to the size of the largest item.
//If bResetScroll is TRUE then the scroll bars will be reset. BOOL AutoSizeColumn(int nCol, INT nAutoSizeStyle = GVS_DEFAULT, BOOL bResetScroll = TRUE)
//Auto sizes the column to the size of the largest item. nAutoSizeStyle sets the way the autosize will occur (see AutoSizing options).
//If bResetScroll is TRUE then the scroll bars will be reset. void AutoSizeRows() //Auto sizes all rows.
void AutoSizeColumns(UINT nAutoSizeStyle=GVS_DEFAULT)
// Auto sizes all columns. nAutoSizeStyle sets the way the autosize will occur. (see AutoSizing options)
void AutoSize(UINT nAutoSizeStyle = GVS_DEFAULT)
//Auto sizes all rows and columns. nAutoSizeStyle sets the way the autosize will occur. (see AutoSizing options) void ExpandColumnsToFit(BOOL bExpandFixed=TRUE)
//Expands the column widths to fit the grid area.
// If bExpandFixed is TRUE then fixed columns will be modified, otherwise they will not be affected. void ExpandLastColumn() //Expands the last column width to fill any remaining grid area.
void ExpandRowsToFit(BOOL bExpandFixed=TRUE)
// Expands the row heights to fit the grid area.
//If bExpandFixed is TRUE then fixed rows will be modified, otherwise they will not be affected. void ExpandToFit(BOOL bExpandFixed = TRUE)
// Expands the rows and columns to fit the grid area.
//If bExpandFixed is TRUE then fixed cells will be modified, otherwise they will not be affected.< CSize GetTextExtent(int nRow, int nCol, LPCTSTR str)// Gets the size of the text pointed to by str for the given cell
CSize GetCellTextExtent(int nRow, int nCol) //Gets the size of the text of the given cell void SetRedraw(BOOL bAllowDraw, BOOL bResetScrollBars = FALSE)
//Stops/starts redraws on things like changing the number of rows and columns and autosizing, but not for user-intervention such as resizes. BOOL RedrawCell(int nRow, int nCol, CDC* pDC = NULL)
//Redraws the given cell. Drawing will be via the pDC if one is supplied. BOOL RedrawCell(const CCellID& cell, CDC* pDC = NULL)
//Redraws the given cell. Drawing will be via the pDC if one is supplied.
BOOL RedrawRow(int row) //Redraws the given row.
BOOL RedrawColumn(int col) // Redraws the given column
BOOL Refresh() // Redraws the entire grid.
CCellRange GetCellRange() //Gets the range of cells for the entire grid. See also CCellRange. void SetSelectedRange(const CCellRange& Range,BOOL bForceRepaint = FALSE);
//Sets the range of selected cells. See also CCellRange. void SetSelectedRange(int nMinRow, int nMinCol,int nMaxRow, int nMaxCol,BOOL bForceRepaint = FALSE);
//Sets the range of selected cells.
BOOL IsValid(int nRow, int nCol) //Returns TRUE if the given row and column is valid.
BOOL IsValid(const CCellID& cell) //Returns TRUE if the given cell is valid.
BOOL IsValid(const CCellRange& range) //Returns TRUE if the given cell range is valid. CCellID GetNextItem(CCellID& cell, int nFlags)const
//Searches for a cell that has the specified properties and that bears the specified relationship to a given item.
//(See also CListCtrl::GetNextItem and Cell Searching options)

11.排序

void SetHeaderSort(BOOL bSortOnClick = TRUE)    //Sets whether or not rows are sorted on column header clicks in ListMode.
BOOL GetHeaderSort() //Gets whether or not rows are sorted on column header clicks in ListMode.
SetSortColumn(int nCol ) //Sets the index of the currently sorted column.
int GetSortColumn() //Gets the index of the currently sorted column.
void SetSortAscending(BOOL bAscending) //Sets whether the current sort column is sorted ascending.
BOOL GetSortAscending() //Gets whether the current sort column is sorted ascending. BOOL SortTextItems(int nCol, BOOL bAscending,LPARAM data = 0)
//Sorts the grid on the given column based on cell text. Returns TRUE on success. BOOL SortItems(int nCol, BOOL bAscending, LPARAM data = 0)
//Sorts the grid on the given column based using the current comparison function.
//If no function has been specified then the rows are sorted by text. Returns TRUE on success. void SetCompareFunction(PFNLVCOMPARE pfnCompare) //Sets the callback function that will be used to sort the grid rows. See below for more details.
void SetVirtualCompare(PVIRTUALCOMPARE VirtualCompare) // Sets the callback function that will be used to sort the grid rows in virtual mode. See below for more details. BOOL SortItems(PFNLVCOMPARE pfnCompare, int nCol,BOOL bAscending, LPARAM data = 0)
//Sorts the grid on the given column using the supplied compare function pfnCompare.
//See CListCtrl::SortItems for information in the form of this function. Returns TRUE on success.

List模式时,也可点击列头部进行排序。

排序可以通过cell比较(SetCompareFunctionSetVirtualCompare),然后调用SortItems(int nCol, BOOL bAscending, LPARAM data = 0)进行排序,nCol表示需要排序的列,bAscending表示升序还是降序,data表示将要传给比较函数的数据

比较函数声明如下:

int CALLBACK pfnCellCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)

参数说明:lParam1lParam2是指向CGridCellBase类的指针,lParamSort是需要传递到SortItems参数中的data,如果带一个cell值小于第二个则返回-1,相等返回0;其他返回1。

比较函数例子如下:

int CALLBACK MyClass::pfnCellNumericCompare(LPARAM lParam1,
LPARAM lParam2,
LPARAM lParamSort)
{
CGridCellBase* pCell1 = (CGridCellBase*) lParam1;
CGridCellBase* pCell2 = (CGridCellBase*) lParam2;
if (!pCell1 || !pCell2) return 0; int nValue1 = _ttol(pCell1->GetText());
int nValue2 = _ttol(pCell2->GetText()); if (nValue1 < nValue2)
return -1;
else if (nValue1 == nValue2)
return 0;
else
return 1;
}

排序文本值和数字(itoa强制转换

int CALLBACK CGridCtrl::pfnCellTextCompare(LPARAM lParam1,
LPARAM lParam2,
LPARAM lParamSort)
int CALLBACK CGridCtrl::pfnCellNumericCompare(LPARAM lParam1,
LPARAM lParam2,
LPARAM lParamSort)

grid设置比较函数:

m_Grid.SetCompareFunction(CGridCtrl::pfnCellNumericCompare);

如果比较函数设置为NULL,pfnCellTextCompare被设置为默认的。

虚模式下排序,需要为SetVirtualCompare提供一个bool (*PVIRTUALCOMPARE)(int, int) 签名,当数据较大时,此函数还需要优化

例子:

m_Grid.SetVirtualCompare(VirtualCompare);

bool CGridCtrlDemoDlg::VirtualCompare(int c1, int c2)
{
//CGridCtrl *pThis = CGridCtrl::m_This; // Mmm, in big virtual mode you must well optimize this function
//int col = pThis->m_CurCol; // a first version with CStrings was catastrophic....
return (c1<c2); // strange order, whatever the column number...
}

12.打印

void EnableWysiwygPrinting(BOOL bEnable = TRUE)        //Set WYSIWYG Printing
BOOL GetWysiwygPrinting() //Returns TRUE if WYSIWYG Printing is set void Print()
//Prints the grid control on the user selected device. (Useful where the control is used in a dialog) virtual void OnBeginPrinting(CDC *pDC, CPrintInfo *pInfo)
//Used in a Doc/View environment. Call in your CView dervied class' OnBeginPrinting. virtual void OnPrint(CDC *pDC, CPrintInfo *pInfo)
//Used in a Doc/View environment. Call in your CView dervied class' OnPrint. virtual void OnEndPrinting(CDC *pDC, CPrintInfo *pInfo)
//Used in a Doc/View environment. Call in your CView dervied class' OnEndPrinting. void SetShadedPrintOut(BOOL bEnable = TRUE)
//If TRUE, colored cells will print as-is. If FALSE, all text prints as black on white. BOOL GetShadedPrintOut() //Get's whether or not cells are printed shaded or as-is. void SetPrintMarginInfo(int nHeaderHeight,
int nFooterHeight, int nLeftMargin,
int nRightMargin, int nTopMargin,
int nBottomMargin, int nGap)
//Set printing margin info. void GetPrintMarginInfo(int &nHeaderHeight,
int &nFooterHeight, int &nLeftMargin,
int &nRightMargin, int &nTopMargin,
int &nBottomMargin, int &nGap)
//Get printing margin info.

13.CGridCellBase类

CGridCellBase 是cell的基类,该类几乎所有的方法都是虚函数,不用来直接调用。

1)属性

virtual void SetText(LPCTSTR szText);
virtual void SetImage(int nImage);
virtual void SetData(LPARAM lParam);
virtual void SetState(DWORD nState);
virtual void SetFormat(DWORD nFormat);
virtual void SetTextClr(COLORREF clr);
virtual void SetBackClr(COLORREF clr);
virtual void SetFont(const LOGFONT* plf);
virtual void SetGrid(CGridCtrl* pGrid);
virtual void SetCoords(int nRow, int nColumn);
virtual void SetMargin(UINT nMargin); virtual LPCTSTR GetText() const // returns the text in the cell
virtual LPCTSTR GetTipText() const // return alternate tooltip text
// if you wish
virtual int GetImage() const // returns image index for cell
virtual LPARAM GetData() const // returns data associated with cell
virtual DWORD GetState() const // returns cell state
virtual DWORD GetFormat() const // returns cell format
virtual COLORREF GetTextClr() const // returns cell text color
virtual COLORREF GetBackClr() const // returns cell background color
virtual LOGFONT* GetFont() const // returns cell font as a LOGFONT
virtual CFont* GetFontObject() const // returns a CFont object with the
// cell's font
virtual UINT GetMargin() const // returns internal margin for cell
virtual CGridCtrl* GetGrid() const // returns grid that cell is associated
// with
virtual CWnd* GetEditWnd() const // returns editing window for cell,
// or NULL virtual BOOL IsEditing() const
virtual BOOL IsFocused() const
virtual BOOL IsFixed() const
virtual BOOL IsFixedCol() const
virtual BOOL IsFixedRow() const
virtual BOOL IsSelected() const
virtual BOOL IsReadOnly() const
virtual BOOL IsModified() const
virtual BOOL IsDropHighlighted() const
virtual BOOL IsDefaultFont() const // TRUE if cell is using default
// font in grid virtual CGridCellBase* GetDefaultCell() const;

2)赋值

virtual void operator=(CGridCellBase& cell);

3)方法

virtual void Reset();

virtual BOOL Draw(CDC* pDC, int nRow, int nCol, CRect rect,
BOOL bEraseBkgnd = TRUE);
virtual BOOL GetTextRect( LPRECT pRect) - dimensions of text
within cell
virtual BOOL GetTipTextRect( LPRECT pRect) - boundary for tooltips
virtual CSize GetTextExtent(LPCTSTR str) - size of text
virtual CSize GetCellExtent(CDC* pDC) - size of cell // start and stop cell editing
virtual BOOL Edit(int nRow, int nCol, CRect rect,
CPoint point, UINT nID, UINT nChar)
virtual void EndEdit() // Validates the results of an edit. If "str" is not a valid
// value for the
// cell then return FALSE to have the edit rejected
virtual BOOL ValidateEdit(LPCTSTR str); virtual BOOL PrintCell(CDC* pDC, int nRow, int nCol, CRect rect); // This can ONLY be called by CGridCellBase derived classes, and
// not CGridCellBase itself.
LRESULT SendMessageToParent(int nRow, int nCol, int nMessage);

4)重载

virtual void OnEndEdit();
virtual void OnMouseEnter();
virtual void OnMouseOver();
virtual void OnMouseLeave();
virtual void OnClick( CPoint PointCellRelative);
virtual void OnClickDown( CPoint PointCellRelative);
virtual void OnRClick( CPoint PointCellRelative);
virtual void OnDblClick( CPoint PointCellRelative);
virtual BOOL OnSetCursor();

这样建立特定的cell将会很简单,你可以重写CGridCtrl::CreateCell创建派生于CGridCellBase的派生类;也可以CGridCtrl::SetCellTypeCGridCtrl::SetDeafaultCellType自动实现。

MyGrid.SetCellType(row, column, RUNTIME_CLASS(CMyGridCell));

(row,colum)将是CMyGridCell类的单元格。CMyGridCell是基于CGridCellBaseCGridCell的子类

14.CGridCell

继承与CGridCellBase,为使用CGridCtrl提供一默认的实现。

15.CCellID

这是一个方便的帮助类,用来引用单个cell,所有成员都是公开的

class CCellID
{
public:
int row, col; // The zero based row and column of the cell. CCellID(int nRow = -1, int nCol = -1) int IsValid();
int operator==(const CCellID& rhs);
int operator!=(const CCellID& rhs);
}

16.CCellRange

这是一个方便的帮助类,用于引用单元格的范围

class CCellRange
{
public:
CCellRange(int nMinRow = -1, int nMinCol = -1,
int nMaxRow = -1, int nMaxCol = -1);
void Set(int nMinRow = -1, int nMinCol = -1,
int nMaxRow = -1, int nMaxCol = -1); int IsValid() const;
int InRange(int row, int col) const; // Is the row/col in the range?
int InRange(const CCellID& cellID) const; // is the cell in the range? CCellID GetTopLeft() const; // Get topleft cell in range
CCellRange Intersect(const CCellRange& rhs) const;
// Returns the intersection of
// two cell ranges int GetMinRow() const; // Self explanatory
void SetMinRow(int minRow);
int GetMinCol() const;
void SetMinCol(int minCol);
int GetMaxRow() const;
void SetMaxRow(int maxRow);
int GetMaxCol() const;
void SetMaxCol(int maxCol); int GetRowSpan() const; // Number of rows spanned
int GetColSpan() const; // Number of columns spanned void operator=(const CCellRange& rhs);
int operator==(const CCellRange& rhs);
int operator!=(const CCellRange& rhs);
}

GV_ITEM 结构如下,用于Get/SetItem 调用

typedef struct _GV_ITEM {
int row,col; // Row and Column of item
UINT mask; // Mask for use in getting/setting cell data
UINT state; // cell state (focus/hilighted etc)
UINT nFormat; // Format of cell. Default imaplentation
// used CDC::DrawText formats
CString szText; // Text in cell
int iImage; // index of the list view item’s icon
COLORREF crBkClr; // Background colour (or CLR_DEFAULT)
COLORREF crFgClr; // Forground colour (or CLR_DEFAULT)
LPARAM lParam; // 32-bit value to associate with item
LOGFONT lfFont; // cell font
} GV_ITEM;

网格线和滚动条选择

GVL_NONE      // No grid lines
GVL_HORZ // Horizontal lines only
GVL_VERT // Vertical lines only
GVL_BOTH // Both vertical and horizontal lines

Autosizing

GVS_DEFAULT   // default
GVS_HEADER // Size using column fixed cells data only
GVS_DATA // Size using column non-fixed cells data only
GVS_BOTH // Size using column fixed and non-fixed

Cell数据过滤

GVIF_TEXT      // Cell text will be accessed
GVIF_IMAGE // Cell image number will be accessed
GVIF_PARAM // Cell user data (lParam) will be accessed
GVIF_STATE // Cell state will be accessed
GVIF_BKCLR // Cell background colour will be accessed
GVIF_FGCLR // Cell foreground colour will be accessed
GVIF_FORMAT // Cell format field will be accessed
GVIF_FONT // Cell logical font will be accessed
GVIF_MARGIN // Cell margin information will be accessed
GVIF_ALL // All information will be accessed

Cell 状态

GVIS_FOCUSED     // Cell has focus
GVIS_SELECTED // Cell is selected
GVIS_DROPHILITED // Cell is drop highlighted
GVIS_READONLY // Cell is read-only and cannot be edited
GVIS_FIXED // Cell is fixed
GVIS_FIXEDROW // Cell is part of a fixed row
GVIS_FIXEDCOL // Cell is part of a fixed column
GVIS_MODIFIED // Cell has been modified

Cell搜索选项

GVNI_FOCUSED     // Search for focus cell
GVNI_SELECTED // Search for selected cells
GVNI_DROPHILITED // Search for drop highlighted cells
GVNI_READONLY // Search for read-only cells
GVNI_FIXED // Search for fixed cells
GVNI_MODIFIED // Search for modified cells GVNI_ABOVE // Search above initial cell
GVNI_BELOW // Search below initial cell
GVNI_TOLEFT // Search to the left of the initial cell
GVNI_TORIGHT // Search to the right of the initial cell
GVNI_ALL // Search all cells in the grid starting from
// the given cell
GVNI_AREA // Search all cells below and to the right of
// the given cell

通知消息

GVN_BEGINDRAG      // Sent when dragging starts
GVN_BEGINLABELEDIT // Sent when inplace editing starts
GVN_ENDLABELEDIT // Sent when inplace editing stops
GVN_SELCHANGING // Sent just before cell selection changes
GVN_SELCHANGED // Sent after cell selection changes
GVN_GETDISPINFO // A request for cell information when the grid is
// in virtual mode
GVN_ODCACHEHINT // Cache hint when in virtual mode

这些消息和LVN….是相同的,只是用的NM_GRIDVIEW结构

typedef struct tagNM_GRIDVIEW {
NMHDR hdr;
int iRow;
int iColumn;
} NM_GRIDVIEW;

17.保护的重载函数

打印相关-在OnPrint中调用

virtual void PrintColumnHeadings(CDC *pDC, CPrintInfo *pInfo);
virtual void PrintHeader(CDC *pDC, CPrintInfo *pInfo);
virtual void PrintFooter(CDC *pDC, CPrintInfo *pInfo);
virtual void PrintRowButtons(CDC *pDC, CPrintInfo* pInfo);

拖放

// No longer necessary but I thought the code was cool so kept it :).
virtual CImageList* CreateDragImage(CPoint *pHotSpot)

鼠标点击

virtual void OnFixedColumnClick(CCellID& cell);
virtual void OnFixedRowClick(CCellID& cell);

编辑

// Starting edit
virtual void OnEditCell(int nRow, int nCol, CPoint point,
UINT nChar)
// ending edit
virtual void OnEndEditCell(int nRow, int nCol, CString str)
// Create the inplace edit control
virtual void CreateInPlaceEditControl(CRect& rect, DWORD dwStyle,
int nRow, int nCol,
LPCTSTR szText, int nChar)

绘图

virtual void OnDraw(CDC& origDC);  // Draws everything

创建删除

// Creates a new cell and initialises it.
virtual CGridCellBase* CreateCell(int nRow, int nCol) // Destroys a cell and performs any cleanup necessary
virtual void DestroyCell(int nRow, int nCol)

18.剪贴板

virtual void OnEditCut()        //Copies contents of selected cells to clipboard and deletes the contents of the selected cells. (Ctrl-X)
virtual void OnEditCopy() //Copies contents of selected cells to clipboard. (Ctrl-C)
virtual void OnEditPaste() //Pastes the contents of the clipboard to the grid. (Ctrl-V)
virtual void OnEditSelectAll() //Not actually a clipboard function, but handy nevertheless. This routine selects all cells in the grid. (Ctrl-A)

19.cell编辑和验证

SetEditable(BOOL)可直接设置编辑与否,可以通过设置cell的GVIS_READONLY属性

例子:

int row = 1;
int col = 10;
m_Grid.SetItemState(row,col, m_Grid.GetItemState(row,col) | GVIS_READONLY);

进一步控制可以通过处理GVN_BEGINLABELEDIT消息,如果该消息的返回值小于0,如果尝试编辑改cell,则会拒绝,则该cell被认为是只读的,该消息每个单元格发送一次编辑尝试。

例子:主窗口中处理

BEGIN_MESSAGE_MAP(CGridCtrlDemoDlg, CDialog)
...
// Add a handler
ON_NOTIFY(GVN_ENDLABELEDIT, IDC_GRID, OnGridEndEdit)
END_MESSAGE_MAP() ... // GVN_ENDLABELEDIT
void CGridCtrlDemoDlg::OnGridStartEdit(NMHDR *pNotifyStruct,
LRESULT* pResult)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNotifyStruct; // AllowCellToBeEdited is a fictional routine that should return TRUE
// if you want to allow the cell to be edited.
BOOL bAllowEdit = AllowCellToBeEdited(pItem->iRow, pItem->iColumn); *pResult = (bAllowEdit)? 0 : -1;
}

也可通过处理GVN_ENDLABELEDIT消息来处理

// GVN_ENDLABELEDIT
void CGridCtrlDemoDlg::OnGridEndEdit(NMHDR *pNotifyStruct,
LRESULT* pResult)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNotifyStruct; // AcceptChange is a fictional routine that should return TRUE
// if you want to accept the new value for the cell.
BOOL bAcceptChange = AcceptChange(pItem->iRow, pItem->iColumn); *pResult = (bAcceptChange)? 0 : -1;
}

源代码链接:http://download.csdn.net/detail/wuyuan2011woaini/9594247

上一篇:ecshop商品详情相册顺序调整


下一篇:阿里云VPC默认网关问题