【问题标题】:What is the true way to create a child window in MFC?MFC中创建子窗口的真正方法是什么?
【发布时间】:2015-12-25 19:38:46
【问题描述】:

我已经为具有文档/视图架构的 SDI MFC 应用程序创建了项目。

现在,我想将主窗口和棋盘分开(我正在尝试编写棋盘游戏)。我想将板子放在子窗口中,以便进一步轻量级将它们居中取决于父(主)窗口的大小。

实际上我已经这样做了,但现在我有一个问题 - 我还想等待来自鼠标的消息。

class CGameView {
  // ...
  CGameView()
  {
    childWnd = new CWnd;
  }

  ~CGameView()
  {
    delete childWnd;
  }

  void CGameView::OnSize(UINT nType, int cx, int cy) {
    CGameDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if(!pDoc)
      return;
    // I bind the height of child window with height of parent
    RECT rcClient;
    GetClientRect(&rcClient);
    rcClient.left = 0;
    rcClient.right = pDoc->getWidth();
    childWnd->MoveWindow(&rcClient);

    childWnd->CenterWindow();

    return;
  }

  int CGameView::OnCreate(LPCREATESTRUCT lpCreateStruct)
  {
    if (CView::OnCreate(lpCreateStruct) == -1)
      return -1;

    CGameDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if(!pDoc)
      return -1;

    childWnd->Create(NULL, NULL, WS_CHILD | WS_VISIBLE,
       CRect(0, 0, pDoc->getWidth(), pDoc->getHeight()), this, 0);

    return 0;
  }

  void CGameView::OnDraw(CDC* pDC)
  {
    CGameDoc* pDoc = GetDocument();

    ASSERT_VALID(pDoc);
    if (!pDoc)
        return;

    CRect rcClient;
    GetClientRect(&rcClient);
    CClientDC cdc(childWnd);
  // The pOffScreen contains the bitmap that I just copy to specified CDC
    pOffScreen->print(&cdc, &rcClient);

  }
}

?我非常关心我做孩子窗口的方式的正确性。 ?现在,我不知道如何通过我的子窗口漂亮地监听鼠标消息?

【问题讨论】:

    标签: c++ mfc


    【解决方案1】:

    一般来说,您不应该直接创建CWnd 类型的对象。

    相反,创建CWnd 的子类并创建该类型的对象。然后,您可以使用该类的成员函数管理鼠标、绘画和任何其他事件。

    class CBoardWnd : public CWnd
    {
        DECLARE_MESSAGE_MAP()
        //...
    };
    BEGIN_MESSAGE_MAP(CBoardWnd, CWnd)
        ON_WM_MOUSEMOVE(...)
        //...
    END_MESSAGE_MAP()
    

    【讨论】:

    • 那么,除了使用 CBoardWnd 而不是 new CWnd; 之外,我写的所有内容都将保留下来,对吗?在view class 中制作窗口是正确的?
    • @RaimbekRakhimbek:是的,您可以根据需要构建CWnd 的任何子窗口。他们甚至可以继承CView 并使用UpdateDocument() 机制(每个文档有很多视图),但我通常不会太在意这些......
    • 哦,我又来了个棒子:如何将有关消息的信息传递给文档?
    • @RaimbekRakhimbek:我会在打电话给CWnd::Create() 之前做childWnd = new CBoardWnd(pDoc);。在您的班级中,您可以保存指向文档的指针并随意使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2021-08-30
    • 2014-08-28
    • 2010-11-19
    • 2010-10-08
    相关资源
    最近更新 更多