I have an MFC application which is support multi-language. To support multi-language, I have developed an API that can calculate drawing width of a String(CString). It works perfectly for English language only. For other unicode language like Russian,Hindi,Arabic(RTL) etc. it cannot calculate exact width of a String. Here below is the API code:
CRect MyUtil::GetTextRect(LPCTSTR str, CRect* rect, UINT format, MyFontClass *textFont /*, BOOL getActualRect*/)
{
if (str == NULL || _tcslen(str) == 0 || rect == NULL || rect->Width() <= 0 || rect->Height() <= 0 || textFont == NULL)
return CRect(0, 0, 0, 0);
CFont *font = textFont->GetCFont();
HDC textHDC = ::GetDC(NULL);
if (textHDC == NULL)
return CRect(0, 0, 0, 0);
HFONT hfont = (HFONT)(font->GetSafeHandle());
HFONT hOldFont = (HFONT)::SelectObject(textHDC, hfont);
CRect textRect(rect->left, rect->top, rect->Width(), rect->Height());
int result = ::DrawText(textHDC, str, -1, &textRect, format | DT_CALCRECT);
::SelectObject(textHDC, hOldFont);
::ReleaseDC(NULL, textHDC);
CRect retRect(textRect.left, textRect.top, textRect.Width() + 1, textRect.Height() + 1);
//if(getActualRect == FALSE)
//{
// retRect.SetRect(retRect.left, retRect.top
// , retRect.Width() / textFont->GetDPIEnlargeRate(), retRect.Height() / textFont->GetDPIEnlargeRate());
//}
return result == 0 ? CRect(0, 0, 0, 0) : retRect;
}
Here below is the calling method: Suppose I have a string ID named: "SOFTWARE_LICENSE" in *.resx file having text below:
Text for English:
<data name="SOFTWARE_LICENSE" xml:space="preserve">
<value>Software Licence</value>
</data>
Text for Russian:
<data name="SOFTWARE_LICENSE" xml:space="preserve">
<value>Лицензия программного обеспечения</value>
</data>
Calling Method:
CString strSL = AfxGetStrRes(_T("SOFTWARE_LICENSE"));
MyFontClass txtFont14Regular = MyFontTemplate::CreateFont(_T("Segoe UI"), -14, FW_NORMAL);
int textWidth = MyUtil::GetTextRect(strSL, &CRect(0, 0, 1000, 1000), DT_LEFT | DT_VCENTER | DT_SINGLELINE,txtFont14Regular).Width();
I need this text width to set the Size of the UI controls like button, Checkbox etc for multi-language (All UI controls are customized).
MyUtil::GetTextRect can calculate the width for English language only. For other language calculated width is not perfect, either large or too small.
Is there any way to calculate the accurate text width for Unicode String?