65.9K
CodeProject 正在变化。 阅读更多。
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (24投票s)

2000年2月15日

CPOL
viewsIcon

371309

downloadIcon

4303

一个简单的教程,演示如何在 Doc/View 应用程序中使用网格控件。

gridctrl example image

我收到很多、很多问题,询问如何在视图而不是对话框中使用我的 MFC 网格控件,希望这能有所帮助。

我认为最简单的方法如下:

  1. 将一个类型为 CGridCtrl* 的成员变量添加到你的视图类中
    CGridCtrl* m_pGrid;
  2. 在你的视图类的构造函数中将其初始化为 NULL
    CMyView::CMyView
    {
        m_pGrid = NULL;
    }
    
  3. 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 情况)。

  4. 我们希望网格占据视图的整个客户端区域,因此为视图添加一个 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.
        }
    }
    
  5. 记住在完成操作后删除对象
    CMyView::~CMyView
    {
        delete m_pGrid;
    }
    
  6. 你可能还需要在你的视图类中添加一个 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 框架的打印预览

© . All rights reserved.