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

具有焦点感知的 EditBox 类

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.42/5 (9投票s)

2003年5月20日

viewsIcon

61271

downloadIcon

2394

当编辑框获得焦点时改变背景颜色,失去焦点时恢复为另一种颜色

Sample Image - CoolEdit.jpg

引言

我想要一个焦点敏感的Editbox来使我的GUI程序更具吸引力。我在codetools中找到一个,该工具由Warren J. Hebert发布。但是,我下载后发现它只有在Editbox是单行样式时才能完美工作。但我的应用程序希望EditBox是多行的。所以我自己写了一个!这就是CEditEx,具有以下特性:

  • 当编辑框获得焦点时改变背景颜色,失去焦点时恢复背景颜色。
  • 使用扁平滚动条代替默认行为。

该类的实现

以下代码片段用于跟踪鼠标
CEditEx::OnMouseMove(UINT nFlags, CPoint point)
{
    CEdit::OnMouseMove(nFlags, point);

    if (m_bIsFocused)
        return;

    if (GetCapture() != this)
    {
        // come in for the first time
        m_bMouseOver = TRUE;
        SetCapture();
        Invalidate(TRUE);
    }
    else
    {
        CRect rect;

        GetClientRect(&rect);

        if (!rect.PtInRect(point))
        {
            //Mouse move out of Edit control
            m_bMouseOver = FALSE;
            Invalidate(TRUE);
            ReleaseCapture();
        }
    }
}

void CEditEx::OnSetFocus(CWnd* pOldWnd) 
{
    CEdit::OnSetFocus(pOldWnd);

    m_bMouseOver=TRUE;
    Invalidate(TRUE);
}

void CEditEx::OnKillFocus(CWnd* pNewWnd)
{
    CEdit::OnKillFocus(pNewWnd);

    m_bMouseOver=FALSE;
    Invalidate(TRUE);
}
Change the scrollbar appearance
// In the Message map
ON_CONTROL_REFLECT(EN_VSCROLL, OnVscroll)

void CEditEx::OnVscroll()
{
    InitializeFlatSB(GetSafeHwnd());
    // Use the flat scrollbar feature provided by Microsoft.
    // See MSDN for this API
}
//Change the background color of EditBox according to different contex.
// In the Message map
ON_WM_CTLCOLOR_REFLECT()

CEditEx::CEditEx()
{
    m_bMouseOver = FALSE;
    brHot.CreateSolidBrush(RGB(255, 255, 255));
    br.CreateSolidBrush(RGB(221, 221, 221));
}

HBRUSH CEditEx::CtlColor(CDC* pDC, UINT nCtlColor)
{
    if (m_bMouseOver)
    {
        pDC->SetBkColor(RGB(255, 255, 255));
        return brHot;
    }
    else
    {
        pDC->SetBkColor(RGB(221, 221, 221));
        return br;
    }
}

要使用CEditEx类,您应该按以下步骤操作:

  • 将一个EditBox添加到您的应用程序中。将样式更改为多行、无边框、需要回车键、垂直滚动条。
  • 在您的应用程序中添加一个从CEditEx派生的成员变量。例如,请参阅testDlg.cpp
CEditEx m_ctlEdit1;

关注点

我现在是中国武汉大学的高年级学生。我使用MFC、TCP/IP、PHP、javascript、C、HTML进行编程,并且对网络安全、DirectX等也感兴趣。
© . All rights reserved.