Knowledge Base Nr: 00212 superstatic.cpp - http://www.swe-kaiser.de

MFC: flexibles Static-Control für Dialoge (Farbe, Font, Text, ... änderbar)

  
Control verwenden:
==================
- ../cpp_classes/ColorStatic.h und cpp in projekt einfügen
- in dialogeditor 'normales' static-control einfügen
- mit classwizard membervariabe anlegen
- in h-file des dialogs:
- ../cpp_classes/ColorStatic.h includieren
- typ der membervariable CStatic durch CColorStatic ersetzen
- benutzen (z.b. in OnInitDialog()
m_dvm.SetColor(RGB(255,0,0), RGB(255,255,255));
m_dvm.SetText("---");
m_dvm.SetFont("Times", 38);

eigenes control erzeugen:
=================
/*
Mit ClassWizard:
- neue Klasse erzeugen CColorStatic abgeleitet von CStatic
- Memberfunktion für WM_PAINT anlegen: OnPaint()

Im Dialogeditor
- StaticText-Elemente einfügen und mit ClassWizard Membervariablen vom
Typ Control|ColorStatic anlegen
*/

//CColorStatic editieren:
class CColorStatic : public CStatic
{
...
public:
void SetColor(COLORREF cref, COLORREF crefBk);
void SetText(const char* lpszText);
void SetFont(const char* lpszFont, int nSize);
...
protected:
CString m_strText;
COLORREF m_cref;
COLORREF m_crefBk;
CString m_strFont;
int m_nFontSize;
...
};

CColorStatic::CColorStatic()
{
m_cref = ::GetSysColor(COLOR_WINDOWTEXT);
m_crefBk = ::GetSysColor(COLOR_BTNFACE);
m_strText = "ColorStatic";
//m_strFont = "Arial";
m_nFontSize = -1;
}

void CColorStatic::SetColor(COLORREF cref, COLORREF crefBk)
{
m_cref = cref;
m_crefBk = crefBk;
Invalidate();
}

void CColorStatic::SetText(const char* lpszText)
{
m_strText = lpszText;
Invalidate();
}

void CColorStatic::SetFont(const char* lpszFont, int nSize)
{
m_strFont = lpszFont;
m_nFontSize = nSize;
Invalidate();
}

void CColorStatic::OnPaint()
{
CPaintDC dc(this);

//hintergrund einfärben/löschen
RECT rect;
GetClientRect(&rect);
dc.FillSolidRect(&rect, m_crefBk);

//text ausgeben
dc.SetBkColor(m_crefBk);
dc.SetTextColor(m_cref);

CFont cfNew;
LOGFONT lf;
CFont* cfOld;

if (m_nFontSize > 0)
{
memset(&lf, 0, sizeof(LOGFONT));
lf.lfHeight = m_nFontSize;
strcpy(lf.lfFaceName, m_strFont);
cfNew.CreateFontIndirect(&lf);

cfOld = dc.SelectObject(&cfNew);
}

dc.TextOut(0, 0, m_strText);

if (m_nFontSize > 0)
{
dc.SelectObject(cfOld);
cfNew.DeleteObject();
}
}

//in Dialogfunktionen benutzen
void CColorcontroltestDlg::OnButtonred()
{
m_text.SetColor(RGB(255,0,0), RGB(0,255,0));
m_text.SetText("blubber");
m_text.SetFont("Arial", 32);
Invalidate();
}

void CColorcontroltestDlg::OnButton2()
{
m_text.SetColor(RGB(0,255,0), RGB(155,155,155));
m_text.SetText("alles nix?");
m_text.SetFont("System", 12);
Invalidate();
}