컨텐츠 바로가기

그리드 콘트롤(Grid Control) 사용법

http://potato1004.egloos.com/5874308

MFC Grid control (derived from CWnd)

 역시 www.codeguru.com에서 가져온 건데요. codeguru에선 설명이 좀 부실하더군요. 뭐 필요한 사람이 우물을 파야하니 어쨌든 사용해보기로 하죠. 다음 글의 일부는 원문을 재편집한 것이고, 필요한 부분은 추가했습니다.

 샘플 프로젝트입니다.

1. Dialog Based 로 프로젝트를 하나 만듭니다. 프로젝트 이름은 Grid로 했습니다. 그리고 다음 파일들을 프로젝트에 추가시킵니다.

gridctrl.h / cpp , CellRange.h , MemDC.h , InPlaceEdit.h / cpp , GridDropTarget.h / cpp , Titletip.h / cpp

다음은 원문에 있는 설명을 임의로 번역한 겁니다. 뭐 짤막하니까 번역할 필요도 없었나요?

gridctrl.h / cpp Main grid control source and header files

CellRange.h

Definition of CCellID and CCellRange helper classes

MemDC.h

Keith Rule's memory DC helper class

InPlaceEdit.h / cpp

In-place edit windows source and header files

GridDropTarget.h / cpp

Grid control OLE drag and drop target.
gridctrl.h 파일에서 GRIDCONTROL_NO_DRAGDROP을 정의하지 않았을 경우만 필요

Titletip.h / cpp

Titletips for cells, from http://www.codeguru.com/
gridctrl.h 파일에서 GRIDCONTROL_NO_TITLETIPS을 정의하지 않았을 경우에만 필요

2. 다이얼로그 템플릿 위에 Custom Control을 하나 놓습니다. 그리고 컨트롤의 속성을 다음처럼 고칩니다. 여기서 고칠 것은 오른쪽의 Class: 항에 MFCGridCtrl 이라고 써넣어주는 것 뿐이죠.

3. GridDlg.h 파일에

    #include "GridCtrl.h"

를 포함시킵니다. 그리고 같은 파일에 다음처럼 CGridCtrl 클래스의 멤버변수를 포함시킵니다.

    CGridCtrl m_Grid;

4. GridDlg.cpp 파일에서 다음처럼 DDX_GridControl 함수를 사용해서 Custom Controlm_Grid 멤버변수를 연결시킵니다. 이 함수는 GridCtrl.cpp 파일에 구현되어 있습니다.

    void CGridDlg::DoDataExchange(CDataExchange* pDX)
    {
            CDialog::DoDataExchange(pDX);
            //{{AFX_DATA_MAP(CGridDlg)
            //}}AFX_DATA_MAP
            DDX_GridControl(pDX, IDC_GRID, m_Grid); //<-----
    }

5. GridDlg.cpp 파일의 OnInitDialog 함수에서 다음처럼 Grid 컨트롤의 초기화를 합니다. 물론 여기서는 한 예로서 써넣은 것이고, 원하는 대로 초기화를 하면 됩니다.

BOOL CGridDlg::OnInitDialog()
{
        CDialog::OnInitDialog();

        // Add "About..." menu item to system menu.

        // IDM_ABOUTBOX must be in the system command range.
        ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
        ASSERT(IDM_ABOUTBOX < 0xF000);

        CMenu* pSysMenu = GetSystemMenu(FALSE);
        if (pSysMenu != NULL)
        {
                CString strAboutMenu;
                strAboutMenu.LoadString(IDS_ABOUTBOX);
                if (!strAboutMenu.IsEmpty())
                {
                        pSysMenu->AppendMenu(MF_SEPARATOR);
                        pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
                }
        }

        // Set the icon for this dialog.  The framework does this automatically
        //  when the application's main window is not a dialog
        SetIcon(m_hIcon, TRUE);                 // Set big icon
        SetIcon(m_hIcon, FALSE);                // Set small icon
        
        // TODO: Add extra initialization here

        BOOL m_bEditable = TRUE;
        BOOL m_bListMode = TRUE;
        int m_nRows = 9;
        int m_nCols = 8;
        int m_nFixRows = 1;
        int m_nFixCols = 1;

        m_Grid.SetEditable(m_bEditable);
        m_Grid.SetListMode(m_bListMode);
        m_Grid.EnableDragAndDrop(TRUE);
        m_Grid.SetTextBkColor(RGB(0xFF, 0xFF, 0xE0));

        m_Grid.SetRowCount(m_nRows);
        m_Grid.SetColumnCount(m_nCols);
        m_Grid.SetFixedRowCount(m_nFixRows);
        m_Grid.SetFixedColumnCount(m_nFixCols);

        DWORD dwTextStyle = DT_RIGHT|DT_VCENTER|DT_SINGLELINE;

        // fill rows/cols with text
        for (int row = 0; row < m_Grid.GetRowCount(); row++) {
                for (int col = 0; col < m_Grid.GetColumnCount(); col++) {
                        GV_ITEM Item;
                        Item.mask = GVIF_TEXT|GVIF_FORMAT;
                        Item.row = row;
                        Item.col = col;

                        if (row < m_nFixRows) {
                                Item.nFormat = DT_LEFT|DT_WORDBREAK;
                                Item.szText.Format(_T("Column %d"),col);

                        } else if (col < m_nFixCols) {
                                Item.nFormat = dwTextStyle;
                                Item.szText.Format(_T("Row %d"),row);

                        } else {
                                Item.nFormat = dwTextStyle;
                                Item.szText.Format(_T("%d"),row*col);
                        }
                        m_Grid.SetItem(&Item);  

                        if (rand() % 10 == 1) {
                                COLORREF clr = RGB(rand() % 128+128,
                                                                rand() % 128+128,
                                                                rand() % 128+128);
                                m_Grid.SetItemBkColour(row, col, clr);
                                m_Grid.SetItemFgColour(row, col, RGB(255,0,0));
                        }
                }
        }
        // Make cell 1,1 read-only
        m_Grid.SetItemState(1,1, m_Grid.GetItemState(1,1) | GVIS_READONLY);

        m_Grid.AutoSize();
        m_Grid.SetRowHeight(0, 3*m_Grid.GetRowHeight(0)/2);

        
        return TRUE;  // return TRUE  unless you set the focus to a control
}

6. 여기까지 하고 컴파일하면 Grid가 보일 겁니다. 초기화 및 CGridCtrl 클래스의 멤버함수를 알아보기 전에 우선 이 클래스의 기능을 알아보죠. 역시 대강대강의 의역입니다.

  • Ctrl 키와 Shift 키의 조합과 함께 마우스로 셀 선택 가능. 선택이 안되게 할 수도 있음.
  • 열과 행의 크기조절 가능. 크기조절이 열이나 행 또는 둘다 안되게 할 수도 있음.
  • 셀 분할자를 더블클릭해서 열이나 행 크기의 자동조절이 가능.
  • 열이나 행의 고정된 셀의 수를 임의로 지정가능.
  • 각각의 셀은 텍스트와 배경색을 따로따로 사용할 수 있음.
  • 각각의 셀은 서로 다른 폰트를 사용할 수 있음.
  • 각각의 셀은 "읽기전용"으로 설정가능.
  • Drag and drop 지원
  • Ctrl-C : 복사, Ctrl-X : 잘라내기, Ctrl-V : 붙여넣기, Ctrl-A : 전체선택 의 기능 지원
  • 셀 내용의 편집 가능. 셀에 포커스가 있을 때 문자키를 누르면 그 셀에서 편집이 시작되고, 이때 화살표키를 누르면 다른 셀로 이동함. 현재 포커스가 있는 셀을 클릭하면 편집이 시작되고, 이때의 화살표 키는 편집하는 셀 내에서 캐럿을 이동시킴. 편집 불가능으로도 설정가능.
  • Microsoft intellimouse 지원
  • Grid 선의 표시여부 선택가능
  • 셀 안에 이미지 표시가능.
  • 도큐먼트/뷰 구조의 인쇄 미리보기나 인쇄 미리보기가 없는 다이얼로그 형태의 프로그램에서도 전체 인쇄 지원
  • 선택적인 "List mode" - 전체 행 선택, 한 행 선택, 컬럼 헤더를 클릭하면 정렬되는 기능 지원.
  • 확장을 용이하게  해주는 수많은 가상함수 제공.
  • UNICODE 지원.
  • WinCE 지원.
  • 값을 표시하기 위한 셀이 너무 작을 경우 툴팁으로 데이터를 표시하는 기능.
  • VC 4.2, 5.0, 6.0 과 CE toolkit version 2.0 , 3.0 버전에서 컴파일 해보았음.

 

7. CGridCtrl 클래스의 멤버함수들입니다.

Constuction

The underlying class of the grid control is CGridCtrl which is derived from CWnd. To use it, either use the MS Visual C++ dialog editor to place a custom control on a dialog, and enter "MFCGridCtrl" (no quotes) as the Class name, or use CGridCtrl::Create:

CGridCtrl(int nRows = 0, int nCols = 0, int nFixedRows = 0, int nFixedCols = 0); BOOL Create(const RECT& rect, CWnd* parent, UINT nID, DWORD dwStyle = WS_CHILD | WS_BORDER | WS_TABSTOP | WS_VISIBLE); void AFXAPI DDX_GridControl(CDataExchange* pDX, int nIDC, CGridCtrl&rControl);

DDX_GridControl is used where a DDX_Control call is needed. It is necessary to use DDX_GridControl instead of DDX_Control when creating the control via a dialog template in order to ensure that the grid is correctly registered as a drag and drop target. This is to avoid a strange COleDropTarget::Register error that occurs in win95.

Number of rows and columns

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.

Sizing and position functions

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.
BOOL GetCellOrigin(int nRow, int nCol, LPPOINT p)
Gets the topleft point for cell (nRow,nCol), returning TRUE if successful. (cell must be visible for success).
BOOL GetCellOrigin(const CCellID& cell, LPPOINT p)
Gets the topleft point for the given cell, returning TRUE if successful. (cell must be visible for success). See also CCellID.
BOOL GetCellRect(int nRow, int nCol, LPRECT pRect)
Gets the bounding rectangle for the given cell, returning TRUE if successful. (cell must be visible for success).
BOOL GetCellRect(const CCellID& cell, LPRECT pRect)
Gets the bounding rectangle for the given cell, returning TRUE if successful. (cell must be visible for success). See also CCellID.
BOOL GetTextRect(int nRow, int nCol, LPRECT pRect)t
Gets the bounding rectangle for the text in the given cell, returning TRUE if successful. (cell must be visible for success).
BOOL GetTextRect(const CCellID& cell, LPRECT pRect)
Gets the bounding rectangle for the text in the given cell, returning TRUE if successful. (cell must be visible for success). See also CCellID.

General appearance and features

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 geid is editable.
BOOL IsEditable()
Gets whether or not the grid is editable.
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.
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 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 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 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.
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 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.
void EnsureVisible(int nRow, int nCol)
Ensures that the specified cell is visible.
void EnableTitleTips(BOOL bEnable = TRUE)
Sets whether or not titletips are used.
BOOL GetTitleTips()
Gets whether or not titletips are used.
BOOL IsCellFixed(int nRow, int nCol)
Returns TRUE if the given cell is a fixed cell.

Colours

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.

See also the Individual Cell colour functions that allow an individual cell's colours to be changes seperate to the rest of the grid.

General cell information

int GetSelectedCount()
Gets the number of selected cells.
CCellID GetFocusCell()
Gets the cell with the focus. See also CCellID.
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.
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.

Operations

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)
Auto sizes the row to the size of the largest item.
BOOL AutoSizeColumn(int nCol)
Auto sizes the column to the size of the largest item.
void AutoSizeRows()
Auto sizes all rows.
void AutoSizeColumns()
Auto sizes all columns.
void AutoSize()
Auto sizes all rows and columns.
void ExpandColumnsToFit()
Expands the column widths to fit the grid area.
void ExpandRowsToFit()
Expands the row heights to fit the grid area.
void ExpandToFit()
Expands the rows and columns to fit the grid area.
CSize GetTextExtent(LPCTSTR str,   BOOL bUseSelectedFont = TRUE)
Gets the extent of the text pointed to by str. By default this uses the selected font (which is a bigger font).
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.
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)
BOOL SortTextItems(int nCol, BOOL bAscending)
Sorts the grid on the given column based on cell text. Returns TRUE on success.
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.

Printing

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.

Structures, defines and Messages

The CCellID class. This is a handy helper class used to reference individual cells. All members are public. This class is adapted from Joe Willcoxsons original implementation.

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);}

The CCellRange class. This is a handy helper class used to reference cell ranges. This class is adapted from Joe Willcoxsons original implementation.

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 int operator==(const CCellRange& rhs); int operator!=(const CCellRange& rhs);}

The GV_ITEM structure. This structure is used for Get/SetItem calls.

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;
Grid line selection
GVL_NONE - No grid linesGVL_HORZ - Horizontal lines onlyGVL_VERT - Vertical lines onlyGVL_BOTH - Both vertical and horizontal lines
Cell data mask
GVIF_TEXT - Cell text will be accessedGVIF_IMAGE - Cell image number will be accessedGVIF_PARAM - Cell user data (lParam) will be accessedGVIF_STATE - Cell state will be accessedGVIF_BKCLR - Cell background colour will be accessedGVIF_FGCLR - Cell foreground colour will be accessedGVIF_FORMAT - Cell format field will be accessedGVIF_FONT - Cell logical font will be accessed
Cell states
GVIS_FOCUSED - Cell has focusGVIS_SELECTED - Cell is selectedGVIS_DROPHILITED - Cell is drop highlightedGVIS_READONLY - Cell is read-only and cannot be editedGVIS_FIXED - Cell is fixed (not used)GVIS_MODIFIED - Cell has been modified
Cell Searching options
GVNI_FOCUSED - Search for focus cellGVNI_SELECTED - Search for selected cellsGVNI_DROPHILITED - Search for drop highlighted cellsGVNI_READONLY - Search for read-only cellsGVNI_FIXED - Search for fixed cells (not used)GVNI_MODIFIED - Search for modified cellsGVNI_ABOVE - Search above initial cellGVNI_BELOW - Search below initial cellGVNI_TOLEFT - Search to the left of the initial cellGVNI_TORIGHT - Search to the right of the initial cellGVNI_ALL - Search all cells in the grid starting from the given cellGVNI_AREA - Search all cells below and to the right of the given cell
Notification messages
GVN_BEGINDRAG - Sent when dragging startsGVN_BEGINLABELEDIT - Sent when inplace editing startsGVN_ENDLABELEDIT - Sent when inplace editing stops

These messages are exactly the same as their LVN_... counterparts, except they use an NM_GRIDVIEW structure:

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

Protected overridable functions

These functions have been made virtual to aid extensiblity.

Printing - called in OnPrint.

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

Drag n' drop

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

Mouse Clicks

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

Editing

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

Drawing

virtual CSize GetCellExtent(int nRow, int nCol, CDC* pDC) - Returns Size of cell according to cell contents.virtual void OnDraw(CDC& origDC); - Draws everythingvirtual BOOL DrawFixedCell(CDC* pDC, int nRow, int nCol, - Draws Fixed cells CRect rect, BOOL bEraseBk=FALSE) virtual BOOL DrawCell(CDC* pDC, int nRow, int nCol, - Draws normal cells CRect rect, BOOL bEraseBk=FALSE)

Construction and Cleanup

virtual CGridCell* CreateCell(int nRow, int nCol) - Creates a new cell and initialises it.virtual void EmptyCell(CGridCell* cell, int nRow, int nCol) - Performs any cleanup necessary before removing cells

Clipboard

A number of Clipboard functions have been included.

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)

 

- the end of this article -

 


덧글|덧글 쓰기|신고