Measurement Studio for VC++

cancel
Showing results for 
Search instead for 
Did you mean: 

How to size a command-styled NiButton according to text ?

My program creates dynamically some command-styled NiButtons with variable OnText and OffText strings inside. I would like to resize programmatically the buttons so that they fit correctly the text.

With classic Windows button, I would probably retrieve the text and the font then call the DrawText() or the CDC::DrawText functions with DT_CALCRECT flag in order to find the size of the string in pixel.

But with NiButtons, how can I do the same ?
Can I cast a CNiFont object to CFont and proceed as above ?

Thank you in advance for your answer...
0 Kudos
Message 1 of 3
(3,026 Views)
You could measure the size of the string with the Win32 GetTextExtentPoint32 function, then resize the control accordingly.

One thing that's kinda weird about this approach, though, is that you're going to have a switch or led (or whatever style you chose for the button) changing size based on the width of a string. Do you really want the whole control's size to change, or are you really just wanting the size of the control to change so that it can fit the string? If the latter, I think a better way to do this would be to use a CStatic. That way you can resize the static control to compensate for the size of the string without having to change the size of
the control, hence affecting the layout of your UI.

- Elton
0 Kudos
Message 2 of 3
(3,026 Views)
Yes, I want to change the whole control's size. My program has an entirely dynamic interface because it includes some kind of tables of buttons and other controls, with variable captions. I finally use GetTextExtentPoint32, or actually the MFC version of it : CDC::GetOutputTextExtent. For those who are interested, here is the code I use to re-calculate the size of a CNiButton according to the text in it:

// Assigning new text to the button
m_pMyNiButton->OnText = "Some new text...";

// Create a CFont object based on the CNiFont object that is attached to the CNiButton
// Assuming CNiFont has a regular style (no italic, nor bold, etc.), so that CFont::CreatePointFont is sufficient here.
CNiFont NiFontButton = m_pMyN
iButton->Font;
CFont FontButton;
FontButton.CreatePointFont(10 * NiFontButton.GetSize(), NiFontButton.GetName());

// Calculate the size in pixels of both the ON and OFF strings.
CDC *pDC = GetDC();
CFont *pOldFont = pDC->SelectObject(&FontButton);
CSize sizeOn = pDC->GetOutputTextExtent(m_pMyNiButton->OnText);
CSize sizeOff = pDC->GetOutputTextExtent(m_pMyNiButton->OnText);
pDC->SelectObject(pOldFont);
ReleaseDC(pDC);
FontButton.DeleteObject();

// Calculate the new size of the CNiButton.
// NIBUTTON_MARGIN_xx adds a border around the text.
CSize sizeOptimal;
sizeOptimal.cx = max(sizeOn.cx, sizeOff.cx) + 2 * NIBUTTON_MARGIN_CX;
sizeOptimal.cy = max(sizeOn.cy, sizeOff.cy) + 2 * NIBUTTON_MARGIN_CY;
0 Kudos
Message 3 of 3
(3,026 Views)