在 Doc/View 框架中使用网格控件






4.78/5 (24投票s)
一个简单的教程,演示如何在 Doc/View 应用程序中使用网格控件。
 
 
我收到很多、很多问题,询问如何在视图而不是对话框中使用我的 MFC 网格控件,希望这能有所帮助。
我认为最简单的方法如下:
- 将一个类型为 CGridCtrl*的成员变量添加到你的视图类中CGridCtrl* m_pGrid; 
- 在你的视图类的构造函数中将其初始化为 NULLCMyView::CMyView { m_pGrid = NULL; }
- 在 CView函数OnInitialUpdate中,如果m_pGrid不为 NULL,则创建一个新的CGridCtrl对象,然后创建CGridCtrl窗口CMyView::OnInitialUpdate { CView::OnInitialUpdate(); if (m_pGrid == NULL) // Have we already done this bit? { m_pGrid = new CGridCtrl; // Create the Gridctrl object if (!m_pGrid ) return; CRect rect; // Create the Gridctrl window GetClientRect(rect); m_pGrid->Create(rect, this, 100); m_pGrid->SetRowCount(50); // fill it up with stuff m_pGrid->SetColumnCount(10); // ... etc } }这允许视图被重用(例如 SDI 情况)。 
- 我们希望网格占据视图的整个客户端区域,因此为视图添加一个 WM_SIZE消息处理程序,并编辑OnSize函数如下:CMyView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); if (m_pGrid->GetSafeHwnd()) // Have the grid object and window { // been created yet? CRect rect; GetClientRect(rect); // Get the size of the view's client // area m_pGrid->MoveWindow(rect); // Resize the grid to take up that // space. } }
- 记住在完成操作后删除对象CMyView::~CMyView { delete m_pGrid; }
- 你可能还需要在你的视图类中添加一个 OnCmdMsg重载,并让网格控件首先处理消息(这将自动连接诸如ID_EDIT_COPY之类的命令)BOOL CMyView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { if (m_pGrid && IsWindow(m_pGrid->m_hWnd)) if (m_pGrid->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; return CView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); }
如果你想要打印预览,请查看 Koay Kah Hoe 的文章 无需 Document/View 框架的打印预览。


