创建插入符、输出不同效果的文字

 

 

创建一个MFC单文档应用程序

  1. 创建插入符

    在窗口创建完成之后,再创建插入符,在View类当中去完成,增加一个Windows Message Handle…..,WM_CREATE消息处理函数。

    1.创建一个文字插入符

    CClientDC dc(this);//构造一个DC

    /* The CClientDC class is derived from CDC and takes care of calling the Windows functionsGetDC at construction time andReleaseDC at destruction time. This means that the device context associated with a CClientDC object is the client area of a window. */

    TEXTMETRIC tm;

    /* The TEXTMETRIC structure contains basic information about a physical font. All sizes are given in logical units; that is, they depend on the current mapping mode of the display context.

    typedef struct tagTEXTMETRIC { // tm

    LONG tmHeight;

    LONG tmAscent;

    LONG tmDescent;

    LONG tmInternalLeading;

    LONG tmExternalLeading;

    LONG tmAveCharWidth;

    LONG tmMaxCharWidth;

    LONG tmWeight;

    LONG tmOverhang;

    LONG tmDigitizedAspectX;

    LONG tmDigitizedAspectY;

    BCHAR tmFirstChar;

    BCHAR tmLastChar;

    BCHAR tmDefaultChar;

    BCHAR tmBreakChar;

    BYTE tmItalic;

    BYTE tmUnderlined;

    BYTE tmStruckOut;

    BYTE tmPitchAndFamily;

    BYTE tmCharSet;

    } TEXTMETRIC; */

    dc.GetTextMetrics(&tm);

    /* The GetTextMetrics function fills the specified buffer with the metrics for the currently selected font.

     

    BOOL GetTextMetrics(

    HDC hdc, // handle to device context

    LPTEXTMETRIC lptm // pointer to text metrics structure

    ); */

    CreateSolidCaret(tm.tmAveCharWidth/8,tm.tmHeight);//创建文字插入符

    /* void CreateSolidCaret( int nWidth, int nHeight );

     

    Parameters

     

    nWidth

    Specifies the width of the caret (in logical units). If this parameter is 0, the width is set to the system-defined window-border width.

     

    nHeight

    Specifies the height of the caret (in logical units). If this parameter is 0, the height is set to the system-defined window-border height.

     

    Creates a solid rectangle for the system caret and claims ownership of the caret. The caret shape can be a line or block. */

    ShowCaret();

    /* The ShowCaret function makes the caret visible on the screen at the caret's current position. When the caret becomes visible, it begins flashing automatically.

     

    BOOL ShowCaret(

    HWND hWnd // handle of window with caret

    ); */

     

    2.创建一个位图插入符

    在View类中加入一个CBitmap 成员变量,

    //    CBitmap bitmap;//这个对象与资源相关,析构时就删除了

     

        bitmap.LoadBitmap(IDB_BITMAP1);//IDB_BITMAP1是在资源中导入的位图

    /* BOOL LoadBitmap( LPCTSTR lpszResourceName );

     

    BOOL LoadBitmap( UINT nIDResource );

     

    Return Value

    Nonzero if successful; otherwise 0.

     

    Parameters

     

    lpszResourceName

    Points to a null-terminated string that contains the name of the bitmap resource.

     

    nIDResource

    Specifies the resource ID number of the bitmap resource.

     

    Loads the bitmap resource named by lpszResourceName or identified by the ID number in nIDResource from the application's executable file. The loaded bitmap is attached to the CBitmap object.

     

    If the bitmap identified by lpszResourceName does not exist or if there is insufficient memory to load the bitmap, the function returns 0. */

        CreateCaret(&bitmap);//创建位图插入符

    /* The CreateCaret function creates a new shape for the system caret and assigns ownership of the caret to the specified window. The caret shape can be a line, a block, or a bitmap.

     

    BOOL CreateCaret(

    HWND hWnd, // handle to owner window

    HBITMAP hBitmap, // handle to bitmap for caret shape

    int nWidth, // caret width

    int nHeight // caret height

    ); */

        ShowCaret();

     

     

    3.使输出的文字与图形始终能够被看到

    在View类中提供的OnDraw函数来始终显示我们要输出的字符串,加入

        CString str;

    /* The CString class is derived from the CData class. The data in this object is a null-terminated string. */

        str="HELLO ,NICE TO MEET YOU !";

        pDC->TextOut(0,140,str);//pDC是OnDraw函数传入的

    /* The TextOut function writes a character string at the specified location, using the currently selected font, background color, and text color.

     

    BOOL TextOut(

    HDC hdc, // handle to device context

    int nXStart, // x-coordinate of starting position

    int nYStart, // y-coordinate of starting position

    LPCTSTR lpString, // pointer to string

    int cbString // number of characters in string

    ); */

     

    4.通过输出字符中表中的字符输出,在资源中插入字符串,

        CSize sz=pDC->GetTextExtent(str);//返回一个CSize对象,即返回特定字符串的宽度和高度

/* Return Value: The dimensions of the string (in logical units) in a CSize object.

Call this member function to compute the width and height of a line of text using the current font to determine the dimensions. The information is retrieved from m_hAttribDC, the attribute device context.

 

The current clipping region does not affect the width and height returned by GetTextExtent. */

    str.LoadString(IDS_HELLOHELLO);//HELLOHELLO是字符串表ID

/* Reads a Windows string resource, identified by nID, into an existing CString object. */

    pDC->TextOut(0,320,str);

5.//在路径层或说路径支架中输出文字

    pDC->BeginPath();

/* The BeginPath function opens a path bracket in the specified device context.

 

Opens a path bracket in the device context. After a path bracket is open, an application can begin calling GDI drawing functions to define the points that lie in the path. An application can close an open path bracket by calling the EndPath member function. When an application calls BeginPath, any previous paths are discarded. */

    pDC->Rectangle(0,140,sz.cx,140+sz.cy);//在路径层中画一个矩形

 

    pDC->EndPath();

 

    pDC->SelectClipPath(RGN_XOR);//剪切区域,还有GRN_DIFF、RGN_AND、RGN_OR等

/* The SelectClipPath function selects the current path as a clipping region for a device context, combining the new region with any existing clipping region by using the specified mode.

 

BOOL SelectClipPath(

HDC hdc, // handle of device context

int iMode // clipping mode

);

 

Parameters

hdc :Handle to the device context of the path.

iMode :Specifies the way to use the path. The following values are allowed:

RGN_AND The new clipping region includes the intersection (overlapping areas) of the current clipping region and the current path.

RGN_COPY The new clipping region is the current path.

RGN_DIFF The new clipping region includes the areas of the current clipping region with those of the current path excluded.

RGN_OR The new clipping region includes the union (combined areas) of the current clipping region and the current path.

RGN_XOR The new clipping region includes the union of the current clipping region and the current path but without the overlapping areas.

 

Return Values:If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. */

  1. //画网格状的线条覆盖输出的文字

        for(int i=0;i<300;i+=10)

        {

            //画横线

            pDC->MoveTo(0,i);//横坐标是0,纵坐标是300

            pDC->LineTo(300,i);

            //画竖线

            pDC->MoveTo(i,0);

            pDC->LineTo(i,300);

        }

  2. //在屏幕上输出字符串

    在View类中捕获一个WM_CHAR消息,增加一个CString 成员变量m_strLine,并在其构造函数在将置空,m_strLine="";

    //在输入文字的时候移动插入符,在View类捕获一个WM_LBUTTONDOWN消息,

    SetCaretPos(point);//移动插入符

    /* The SetCaretPos function moves the caret to the specified coordinates. If the window that owns the caret was created with the CS_OWNDC class style, then the specified coordinates are subject to the mapping mode of the device context associated with that window.

     

    SetCaretPos moves the caret whether or not the caret is hidden. */

    m_strLine.Empty();//清空m_strLine中保存的字符

    //将当前鼠标点击的位置保存下来,加一个CStrng成员变量m_ptOrigin,并在构造函数中将它赋零

    m_ptOrigin=point; //将当前鼠标点击的位置保存下来

     

  3.     CClientDC dc(this);//定义这个CHAR响应的DC对象

        CFont font;//定义一个字体的对象

        font.CreatePointFont(300,"微软简行楷",NULL);

    /* This function provides a simple way to create a font of a specified typeface and point size. It automatically converts the height in nPointSize to logical units using the CDC object pointed to by pDC. */

        CFont *pOldFont=dc.SelectObject(&font);//将字体选到设备描述表中

        TEXTMETRIC tm;//定义一个字体度量对象

        dc.GetTextMetrics(&tm); //返回获取的度量的值到tm对象中去

    /* The GetTextMetrics function fills the specified buffer with the metrics for the currently selected font. */

    //回车处理

        if(0x0d==nChar)

        {

            m_strLine.Empty();

            m_ptOrigin.y+=tm.tmHeight;

        }

        //退格处理

        else if(0x08==nChar)

        {

            COLORREF clr=dc.SetTextColor(dc.GetBkColor());

    /* The GetBkColor function returns the current background color for the specified device context. Returns the current background color. If the background mode is OPAQUE, the system uses the background color to fill the gaps in styled lines, the gaps between hatched lines in brushes, and the background in character cells. The system also uses the background color when converting bitmaps between color and monochrome device contexts.

    Sets the text color to the specified color. The system will use this text color when writing text to this device context and also when converting bitmaps between color and monochrome device contexts. */

            dc.TextOut(m_ptOrigin.x,m_ptOrigin.y,m_strLine);

        m_strLine=m_strLine.Left(m_strLine.GetLength()-1);//对字符串取左边的部分

            dc.SetTextColor(clr);//将先前的颜色设回来

        }

        else

        {

            m_strLine+=nChar;//把字符加到m_strLine后边

        }

        CSize sz=dc.GetTextExtent(m_strLine);//获取文本在屏幕上显示的宽度

        CPoint pt;

        pt.x=m_ptOrigin.x+sz.cx;//加入一串字符后的x坐标

        pt.y=m_ptOrigin.y;//y坐标不变

        

        SetCaretPos(pt);//重置插入符

        dc.TextOut(m_ptOrigin.x,m_ptOrigin.y,m_strLine);

        dc.SelectObject(pOldFont);//把字体设回来

     

  4. 在View中增加一个WM_TIMER消息,增加一个int型成员变量m_nWidth,并在构造函数中赋初值等于零。

    在OnCreate函数中设置一个定时器:

    SetTimer(1,100,NULL);

    /* The SetTimer function creates a timer with the specified time-out value.

    UINT SetTimer(

    HWND hWnd, // handle of window for timer messages

    UINT nIDEvent, // timer identifier

    UINT uElapse, // time-out value

    TIMERPROC lpTimerFunc // address of timer procedure

    );

    An application can process WM_TIMER messages by including a WM_TIMER case statement in the window procedure or by specifying a TimerProc callback function when creating the timer. When you specify a TimerProc callback function, the default window procedure calls the callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, even when you use TimerProc instead of processing WM_TIMER. */

    在OnTimer函数中插入:

    m_nWidth+=5;//按5个像数点增加

        CClientDC dc(this);

        TEXTMETRIC tm;

        dc.GetTextMetrics(&tm);

        CRect rect;

        rect.left=0;

        rect.top=320;

        rect.right=m_nWidth;

        rect.bottom=rect.top+tm.tmHeight;

     

        dc.SetTextColor(RGB(255,0,0));

        CString str;

        str.LoadString(IDS_HELLOHELLO);

        //dc.DrawText(str,rect,DT_LEFT);//从左边开始延伸显示

        dc.DrawText(str,rect,DT_CENTER);//从中间开始向两边延伸显示

    /* The DrawText function draws formatted text in the specified rectangle. It formats the text according to the specified method (expanding tabs, justifying characters, breaking lines, and so forth). Call this member function to format text in the given rectangle. It formats text by expanding tabs into appropriate spaces, aligning text to the left, right, or center of the given rectangle, and breaking text into lines that fit within the given rectangle. The type of formatting is specified by nFormat.

    int DrawText(

    HDC hDC, // handle to device context

    LPCTSTR lpString, // pointer to string to draw

    int nCount, // string length, in characters

    LPRECT lpRect, // pointer to struct with formatting dimensions

    UINT uFormat // text-drawing flags

    ); */

        rect.top=350;

        rect.bottom=rect.top+tm.tmHeight;

        dc.DrawText(str,rect,DT_RIGHT);

     

        CSize sz=dc.GetTextExtent(str);

        if(m_nWidth>sz.cx)//比较在屏幕上显示的宽度是否大于字符串的宽度

        {

            m_nWidth=0;

            dc.SetTextColor(RGB(0,255,0));//设置文本的颜色

            dc.TextOut(0,320,str);

        }

     

    OK. ^_^

     

    源程序地址:http://down.qiannao.com/space/file/luowei505050/Text.rar/.page

posted @ 2011-09-07 17:46  维唯为为  阅读(360)  评论(0编辑  收藏  举报