二級C++技巧:MFC實(shí)現(xiàn)畫線的實(shí)現(xiàn)方法

字號:

一.畫直線:
    步驟一:在視圖類中對WM_LBUTTONDOWN和WM_LBUTTONUP消息添加消息響應(yīng)函數(shù)OnLButtonDown和OnLButtonUp
    步驟二:在視圖類中利用添加成員向?qū)砑映蓡T變量。名字,例如m_StartPoint,類型為CPoint,訪問屬性設(shè)置為protected
    步驟三:在OnLButtonDown和OnLButtonUp 中寫如下代碼:
    void CswdfView::OnLButtonDown(UINT nFlags, CPoint point)
    {
    // TODO: Add your message handler code here and/or call default
    m_StartPoint=point;
    CView::OnLButtonDown(nFlags, point);
    }
    void CswdfView::OnLButtonUp(UINT nFlags, CPoint point)
    {
    // TODO: Add your message handler code here and/or call default
    //第一種,使用HDC和API函數(shù)
    /*HDC hdc;
    hdc=::GetDC(m_hWnd);
    ::MoveToEx(hdc,m_StartPoint.x,m_StartPoint.y,NULL);
    ::LineTo(hdc,point.x,point.y);
    ::ReleaseDC(m_hWnd,hdc);
    CView::OnLButtonUp(nFlags, point);*/
    //第二種,使用CDC類
    /*CDC *pDC=GetDC();
    pDC->MoveTo(m_StartPoint);
    pDC->LineTo(point);
    ReleaseDC(pDC);*/
    //第三種,使用CClientDC
    CClientDC aDC(this);
    aDC.MoveTo(m_StartPoint);
    aDC.LineTo(point);
    }
    OK,運(yùn)行程序,可以畫直線了。
    二.畫曲線
    步驟一:按照畫直線中介紹的方法在視圖類中添加對WM_MOUSEMOVE消息的響應(yīng)函數(shù)OnMouseMove
    步驟二:在OnMouseMove中寫如下代碼:
    void CswdfView::OnMouseMove(UINT nFlags, CPoint point)
    {
    // TODO: Add your message handler code here and/or call default
    if(nFlags==MK_LBUTTON) //判斷鼠標(biāo)左鍵是否按下,如果按下,則移動(dòng)時(shí)畫線
    {
    CClientDC aDC(this);
    aDC.MoveTo(m_StartPoint);
    aDC.LineTo(point);
    m_StartPoint=point; //將畫線的起點(diǎn)移動(dòng)到鼠標(biāo)移動(dòng)后的點(diǎn)
    }
    CView::OnMouseMove(nFlags, point);
    }