刘华世的官方博客

C++实例 单文档模式生成消息窗口和消息响应

#include <afxwin.h>
#include "resource.h"
#include <afxtempl.h> //CArray使用的头文件

class MyDocument:public CDocument
{
public:
    CArray<CPoint, CPoint &> pArray; //记录点轨迹容器

    void AddPoint(CPoint p) //将轨迹点添加到容器里
    {
        pArray.Add(p);
    }

    CPoint GetPoint(int i)
    {
        return pArray[i]; //将轨迹点从容器中取出
    }

    int GetSize()
    {
        return pArray.GetSize(); //获得容器大小
    }

    DECLARE_DYNCREATE(MyDocument) //定义为run-time类别
    DECLARE_MESSAGE_MAP() //声明消息映射
};

IMPLEMENT_DYNCREATE(MyDocument, CDocument) //建立run-time类别
BEGIN_MESSAGE_MAP(MyDocument, CDocument) //建立消息映射
END_MESSAGE_MAP()



class MyView:public CView 
{
public:
    void OnDraw(CDC* pDC) //重写OnDraw虚函数(这个是必须要重写的)
    {
        MyDocument *doc = (MyDocument*)GetDocument(); //获得当前Document控件的指针

        int num = doc->GetSize(); //取得当前轨迹点数
        int i;

        for(i=0;i<num;i++) //将Document中储存的轨迹点重绘到视窗上
        {
            CPoint point = doc->GetPoint(i); //获得相应点
            pDC->SetPixel(point, RGB(255, 0, 0)); //画点到单文档中
        }
    }

    afx_msg void OnLButtonDown(UINT nFlags, CPoint point)
    {
        SetCapture(); //取得鼠标消息接收权
    }

    afx_msg void OnMouseMove(UINT nFlags, CPoint point)
    {
        if(this==GetCapture())
        {
            CClientDC aDC(this); //建立画布
            aDC.SetPixel(point, RGB(255, 0, 0)); //将点画在画布上
            MyDocument *doc = (MyDocument*)GetDocument(); //取得当前Document控件的指针
            doc->AddPoint(point);//将轨迹点加入到Document控件中

        }
    }

    afx_msg void OnLButtonUp(UINT nFlags, CPoint point)
    {
        ReleaseCapture(); //释放鼠标消息控件权
    }

    DECLARE_DYNCREATE(MyView)
    DECLARE_MESSAGE_MAP()
};

IMPLEMENT_DYNCREATE(MyView, CView)
BEGIN_MESSAGE_MAP(MyView, CView)
    ON_WM_LBUTTONDOWN()
    ON_WM_MOUSEMOVE()
    ON_WM_LBUTTONUP()
END_MESSAGE_MAP()


class MyFrame:public CFrameWnd
{
    DECLARE_DYNCREATE(MyFrame)
    DECLARE_MESSAGE_MAP()
};

IMPLEMENT_DYNCREATE(MyFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(MyFrame, CFrameWnd)
END_MESSAGE_MAP()


class MyApp : public CWinApp
{
public:

    BOOL InitInstance()
    {
        CDocument *doc;
        CSingleDocTemplate * DocTemplate;
        DocTemplate = new CSingleDocTemplate( //单文档初始化
            IDR_MENU1, 
            RUNTIME_CLASS(MyDocument), 
            RUNTIME_CLASS(MyFrame), 
            RUNTIME_CLASS(MyView));
        AddDocTemplate(DocTemplate); //将文件样版加入到应用程序
        doc = DocTemplate->CreateNewDocument(); //建立新文件
        m_pMainWnd = DocTemplate->CreateNewFrame(doc, NULL); //建立新的视窗框架
        DocTemplate->InitialUpdateFrame((CFrameWnd*)m_pMainWnd, doc); //起始化View控件

        m_pMainWnd->ShowWindow(SW_SHOW); //显示视窗

        return true;
    }

};

MyApp a_app;

 

posted @ 2013-03-12 17:41  pythonschool  阅读(324)  评论(0编辑  收藏  举报
刘华世的官方博客