
How can I change the font of a CEdit control
Why are you doing this in OnSetFocus? That's a well and truly weird place to do it. In any
case, you are doing a SetFont of a local variable, which is being destroyed immediately,
so by the time the drawing code in the OnPaint handler gets around to trying to draw, the
font is long gone and therefore irrelevant. Also, -1 is not an interesting height for a
font, since it creates a 1-pixel-high font, which is pretty hard to read.
Create variable for the font in the CGreyEdit control itself. Initialize it only once,
when the control is created (in MFC, this is best done in the PreSubclassWindow handler).
If you need to change it, then change it and set it someplace, but the OnFocus handler is
irrelevant here.
It seems odd that you are not setting the text until the user clicks in the window; this
is an odd sort of interface which would not be obvious to most users. If you have thought
carefully about this, fine, but in general it is a bad idea to do something like this.
Just set the text whenever you have it. This otherwise results in startling behavior and a
cognitive disconnect with expected GUI behavior.
Also, ::ZeroMemory is preferrable to memset because it is a bit more obvious.
joe
Quote:
>Hello all:
>I want to change the font of the CEdit control, but the following code
>doesn't work for me, could anyone tell me what's wrong?
>Besides, how can I change the color of the text color?
>Thanks in advance
>Kevin
>==>>
>void CGreyEdit::OnSetFocus(CWnd* pOldWnd)
>{
> // TODO: Add your message handler code here
> TRACE("OnSetFocus\n");
> LOGFONT lf;
> CFont fontItalic;
> memset(&lf, 0, sizeof(LOGFONT));
> lf.lfHeight = -1;
> lf.lfWeight = FW_NORMAL;
> strcpy(lf.lfFaceName, "MS Sans Serif"); //Font face doesn't take effect!
> lf.lfItalic = TRUE; //The text in the control is still normal, not
>italic!
> VERIFY(fontItalic.CreateFontIndirect(&lf));
> this->SetWindowText(this->m_strDefaultText);
> this->SetFont(&fontItalic, TRUE);
> CEdit::OnSetFocus(pOldWnd);
> Invalidate(FALSE);
>}
><<==
Joseph M. Newcomer [MVP]
Web: http://www3.pgh.net/~newcomer
MVP Tips: http://www3.pgh.net/~newcomer/mvp_tips.htm