Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This tutorial will show how use the CStatic class in a very basic dialog based application. It will cover the following points:

This tutorial assumes that you are comfortable with creating a dialog based application using the VC++ 6 Class Wizard. If you require information on this topic consult the article A Beginners Guide to Dialog Base Applications - Part 1.

Make sure you enable ActiveX control if you wish to use Enhanced Meta Files.

As the name implies, Static controls are mostly used for displaying information in a dialog, and are basically a Read Only controls, and will accept no input like Edit controls. The CStatic class however has a number of notification messages as you will see below.

The different types of CStatic control

There are a variety of Static control ranging from plain text to ones that display images, as you can see in the image below.

I have included the Group Box in this tutorial because it is often used as static for decorative purposes. It does however have some interesting properties that are worth mentioning, and can be useful.

Adding a CStatic to your dialog

When your dialog-based application is generated, go to the Resources in the Workspace window. Select the dialog IDD_STATICCTRLTUTORIAL_DIALOG in the Dialog section. To insert the Static control, select it from the Control palette. The cross shaped cursor indicates where the centre of the Static control will be placed.

Static Text is used for placing areas of text on the dialog.

Picture covers Frames, Icons, Bitmaps, Rectangles and Enhanced Meta Files

Drag the edges of the control out the desired size.

By default these controls are given a resource ID of -1 (IDC_STATIC). If you require any notifications from the control or want to change text at runtime etc. this ID must be changed keeping in mind the usual restrictions for resource Ids.

CStatic Styles

Picture

Plain Text

All

If you have a look at the resource script you will see the following entry for one of the controls. Note that the SS_CENTER style is implied by the CTEXT control type.

    CTEXT           "Plain Text Label - SS_CENTER | SS_CENTERIMAGE",
                    IDC_STATIC,10,135,175,15,SS_CENTERIMAGE,WS_EX_STATICEDGE

The alternative entry which results in the same visual effect is as follow. Here the styles are fully specified and the control type is specified as Static.

    CONTROL         "Plain Text Label - SS_CENTER | SS_CENTERIMAGE",IDC_STATIC,
                    "Static",SS_CENTER | SS_CENTERIMAGE,10,135,175,15,WS_EX_STATICEDGE

Other Etched Style

These 2 styles can not be set using the VC++ 6 resource editor, and if you edit the RC file in text mode these styles will be replaced by SS_ETCHEDFRAME the next time you use the resource editor. You can use them however in the Create() function.

If you wish to have an etched looking vertical or horizontal line use the SS_ETCHEDFRAME style an make the rectangle 1 unit high or wide.

Useful Group Box properties

As stated above a Group Box is in actual fact a button control, so it is out of place in this tutorial. However is does give the appearance of a static control and is mostly used in the same way.

You will notice in the demo program that "Group 1" has an accelerator key associated with it as indicated by the underlined 1. The Group Box also has the WS_TAPSTOP style. This results in the feature, that when the accelerator key 'ALT+1' is press, focus is given to the first control in that group or as in this case the selected radio button.

The first (top) control in the group must have the WS_GROUP style and the first control after the end of the group must also have the WS_GROUP style, to indicate the first control in the next group.

Changing Edit control Styles at Runtime

It is possible to change some styles at runtime using ModifyStyle( DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0 ), although this is not done frequently.

The code segment below toggles the SS_CENTER style of the control, making the jump between the left and the center of the control. It checks the current style of the control and then adds or removes the SS_CENTER style accordingly.

void CStaticCtrlTutorialDlg::OnCheckBox1() 
{
	UpdateData(TRUE);
	DWORD dw = m_Var.GetStyle();
	m_strVar = _T("Testing");
	if( dw & SS_CENTER )
		m_Var.ModifyStyle(SS_CENTER,0);
	else
		m_Var.ModifyStyle(0,SS_CENTER|SS_CENTERIMAGE);

	m_Var.Invalidate();
	UpdateData(FALSE);
}

Note for this trick to work you must force a redraw of the control by calling Invalidate(). Also if UpdateData() is not called at the start of the function GetStyle() will not return the correct value.

Changing Contents of a CStatic at Runtime

The code segment above also demonstrates the simplest way to change the text in the control. By using Data Exchange simply attach a string variable to the control, assign a string to it and call UpdateData(FALSE).

.
	m_strVar = _T("Testing");
.
.
	UpdateData(FALSE);
.

Alternatively use

	m_Var.SetWindowText( "The New Text" );

To change images in SS_ICON, SS_BITMAP and SS_ENHMETAFILE styles have functions that can be called.

The code below toggles the icon between the application's icon and the system 'query' icon, using SetIcon(). SetCursor() can also be used. Bitmaps and icons can be assigned in the resource editor, and this is the usual method when they are not changed.

void CStaticCtrlTutorialDlg::OnToggleicon() 
{
	TRACE("CStaticCtrlTutorialDlg::OnToggleicon()\n");
	UpdateData(TRUE);
	if( m_bToggleIcon )
		m_Icon.SetIcon(::LoadIcon(NULL, IDI_QUESTION));
	else
		m_Icon.SetIcon(m_hIcon);

	m_Icon.Invalidate();
	UpdateData(FALSE);
}

For bitmaps use SetBitmap() and use SetEnhMetaFile() for enhanced meta files.

	if (m_EMF.GetEnhMetaFile() == NULL)
	   m_EMF.SetEnhMetaFile( ::GetEnhMetaFile(_T("ms.emf")) );

Note for enhanced meta files to work like this AfxEnableControlContainer() must be called in the Application InitInstance() function, to enable ActiveX (OLE) controls.

Handling CStatic messages

The notification messages available for Static controls are the following. The Static control must have SS_NOTIFY style

STN_CLICKED notification message when the user clicks on the Static control.

STN_DBLCLK notification message when the user double-clicks on the Static control.

STN_ENABLED notification message when a Edit control loses the keyboard focus.

STN_DISABLED notification message when the user cancels the selection in a Edit control.

Class Wizard will only set up a function to handle the STN_CLICKED notification. If you look at the demo you will note that Class Wizard inserts the following lines to handle the clicked message on the Static controls.

	ON_BN_CLICKED(IDC_STATICBITMAP, OnStaticbitmap)
	ON_BN_CLICKED(IDC_STATICICON, OnStaticicon)

The following Macros are supported in VC++ 6 for static notifications but must be entered manually.

	ON_STN_CLICKED(IDC_STATICBITMAP, OnStaticbitmap)
	ON_STN_DBLCLK(IDC_STATICBITMAP, OnBitmapDblClk)
	ON_STN_ENABLE(IDC_STATICBITMAP, OnBitmapEnabled)
	ON_STN_DISABLE(IDC_STATICBITMAP, OnBitmapDisabled)

The handlers in the demo do nothing more than report they have been called, by executing a TRACE statement and changing the text in another Static control.

Conclusion

The CStatic class is quite simple. You will find fancier versions of Static controls elsewhere on this site.

Happy programming!

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralHow to handle WM_CREATE or WM_SHOWWINDOW?
wufeng0524
0:26 12 Jun '07  
Hello,

Is it possible to handle WM_CREATE or WM_SHOWWINDOW?
If it is possible, how?

Thanks.
GeneralRe: How to handle WM_CREATE or WM_SHOWWINDOW?
Wolfram Steinke
1:50 12 Jun '07  
Yes – you have to subclass CStatic and override the function in the derived class.

Happy programming!!

QuestionSTATIC-Control with bitmap doesn't resize itself
entwicklung@zamik.de
5:49 13 Apr '07  
Hello,

I develop with VS 2005 MFC for PocketPC 2003. Now my problem: On my dialog there is a static control with a bitmap. On a PocketPC with a resolution of 240x320 the bitmap is right resized but on a PocketPC with a resolution of 480x640 the bitmap is not right resized. When I compile the same application with VS 2003 (embedded visual c++ 4.00) and transfer it on the PocketPC with the resolution of 480x640, it works fine. What are the difference between embedded visual c++ 4.00 and VS 2005 and what can I do?
Questionwhy the image doesn't appear ????
singersinger
2:19 11 Feb '07  
i want to srtatically load an image in a Static picture control
what i have done is:
1- drag a picture control to the dialog
2- in the dialog properties set the type to BitMap and gave the bitmap ID to the image comboBox
3- and now the image is displayed corecctly in the dialog but when running the dialog it doesn't appear

so why is that???
and FYI the dialog is modeless

thnx alot 4 ur time and concern.
GeneralHow to chage a icon assigned to CStatic through global function???
gloriousgopi
0:23 30 Oct '06  

Hi

Can any one provide me some help as how to chage the icon assigned to a CStatc control from a global function.

I have created a CStatic control and assigned a Icon image to it by changing its type to Icon.

Now i want to change the another icon from a global fuction. i already gathered the icon by using the LoadIcon() fuction.

Thanks in advance,



Gopinath MV

GeneralHandling single click and double click both
mandabi
1:35 17 Jul '06  
Whenever some operation (e.g message box is shown) is done in the ON_STN_CLICKED handler then always ON_STN_CLICKED is performed, i.e. even on double click operation it never enters ON_STN_DBLCLK handler. Please let me know how to solve this?

Thanks in advance

mandabi
GeneralHow to set the color of the border of a static control
huutribk2001
21:59 17 May '06  
Hi,
I need to draw a red border to a static frame control in C++(MFC)
Please help me to do this with some code or suggestions.
 

Tri
GeneralRe: How to set the color of the border of a static control
Wolfram Steinke
10:34 18 May '06  
Subclass the control and provide your own Paint method.

Have a look at

http://www.codeproject.com/staticctrl/XColorStatic.asp

and

http://www.codeproject.com/staticctrl/coloredit_colorstatic.asp


Happy programming!!
GeneralHow to get the X & Y clicked position
smesser
20:58 31 May '05  
Do you know how to capture the XY coordinate of a mouse click in a static control?
GeneralRe: How to get the X & Y clicked position
Wolfram Steinke
21:57 31 May '05  
Add a handler for WM_MOVEMOUSE message OnMoveMouse to you class for the static control. One of the parameters is the co-ordinates for the mouse hotspot.

Happy programming!!
GeneralRe: How to get the X & Y clicked position
smesser
21:59 31 May '05  
I tried that but it never gets called.

Also how do you get a HDC to a static control?

Thanks
GeneralRe: How to get the X & Y clicked position
Wolfram Steinke
22:20 31 May '05  
Trap it in a PreTranslateMessage and direct it to the control when it's within window's boundary.

Happy programming!!
GeneralRe: How to get the X & Y clicked position
smesser
22:30 31 May '05  

Thanks got the click part working.

How about the other question.

I am trying to write a program that uses Sonique Visualizations. It's render function

needs:

BOOL BASSVISDEF(BASS_SONIQUEVIS_Render)(HVIS handle, DWORD channel, HDC canvas);

an HDC, How do you get an HDC from a cstatic control?

I have tried:

HDC hdc = VisWindow.GetDC();

Where VisWindow is the control variable for my CStatic control.

The compiler complains that

c:\BassVisMFC\BassVisMFC\BassVisMFCDlg.cpp(514): error C2440: 'initializing' : cannot convert from 'CDC *' to 'HDC'

Any ideas?

Thanks
GeneralRe: How to get the X & Y clicked position
CosmoNova
22:33 25 Jul '05  
I have exactly the same problem and wanna use CStatic as a bitmap button. Where should I trap the PreTranslateMessage? In the background's CDialog? or the CStatic control's?
thx!
GeneralRe: How to get the X & Y clicked position
Wolfram Steinke
23:04 25 Jul '05  
The CStatic control does have a 'clicked' notification message which is the simplest way. It won't of course change the image like a CButton does. If you need to know the co-ordinates of the mouse also you could call GetCursorPos. However by this time it may have moved after the original click.

Use the PreTranslateMessage in the dialog. Here you can intercept before the control gets the WM_KEYDOWN message and read the cursor postion and then allow normal processing to contiue.


Happy programming!!
GeneralRe: How to get the X & Y clicked position
santoshedwin
22:25 15 Jan '07  
hi ..
y dont u try this............

BOOL CMyStatic::PreCreateWindow(CREATESTRUCT& cs)
{
cs.lpszClass = _T("STATIC");
cs.style |= SS_NOTIFY;
return CStatic::PreCreateWindow(cs);
}

XMe

Generalhow to select text (CStatic) from afxmessagebox or dialog box
Rodrick
4:58 5 Apr '05  
hello everyone. i need to if there is a way to select static text (CStatic Object) from a dialog box or an afxmessagebox without using the ? i have searched and i can't quit figure out how to find more about this. i have tried 'copy text from dialog', 'select text from dialog', 'make static text selectable' and none of this works. any suggestions would be greatly appreciated.
GeneralRe: how to select text (CStatic) from afxmessagebox or dialog box
Wolfram Steinke
9:47 5 Apr '05  
I'm not sure exactly what you wish to achieve. Very simply, the Static control is not intended for selecting text. One thing you can do however if you know the ID if the control is read the entire text from the control using
GetDlgItem(id)->GetWindowText(string);

Happy programming!!
Generalwhy to add SS_CENTERIMAGE?
vividtang
14:58 15 May '04  
void CStaticCtrlTutorialDlg::OnCheckBox1()
{
......
else
m_Var.ModifyStyle(0,SS_CENTER|SS_CENTERIMAGE);

.......}
why to add SS_CENTERIMAGE,when running ,not see any image in static control?
GeneralCStatic runtime
dob_lalema
3:56 29 Mar '04  
ok, i want to create a cstatic bitmap at runtime:

void CTestDlg::OnButton1() {
CStatic *x = new CStatic();
x->Create(NULL,WS_CHILD|WS_VISIBLE|SS_BITMAP|SS_CENTERIMAGE, CRect(20,20,150,150), this);
CBitmap b;
b.LoadBitmap(IDB_BITMAP1);
x->SetBitmap((HBITMAP)b);
}

it works fine, but whenever i move the window, the picture just disappear... any clue?
GeneralRe: CStatic runtime
BoomyJee
5:21 5 Feb '05  
the same problem
that because of CBitmap
it deletes the bitmap on destruction
try this :
CBitmap* b = new CBitmap;
b->LoadBitmap(IDB_TOOLBAR);
x->SetBitmap((HBITMAP)(*b));

it should definitely work
GeneralChange font and size
gildan2020
6:01 12 Mar '04  
Hi, how do i change the font and size of my static text?

thx
GeneralRe: Change font and size
Wolfram Steinke
11:13 12 Mar '04  
In your Initialization create the font with the paramaters you need, using CreateFont or CreatePointFont etc. Then call SetFont for the control in question.

Happy programming!!
GeneralRe: Change font and size
Rohit Singh
22:51 5 Apr '05  

CFont font;
VERIFY(font.CreateFont(
0, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_BOLD, // nWeight
TRUE, // bItalic
TRUE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
PROOF_QUALITY, // nQuality
DEFAULT_PITCH|FF_DONTCARE, // nPitchAndFamily
"ARIAL")); // lpszFacename

; // lpszFacename

m_CtrlEdit.SetFont(&font,true);

I am doing the above font setting but the text in the Edit box is not getting modified for underline and italic which I have set as TRUE?

GeneralRe: Change font and size
Anonymous
12:51 1 Aug '05  
I have the same problem, ever get an answer?


Last Updated 24 Mar 2001 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010