i have these function for get the string size:

SIZE GetStringSize(string text, HWND hdccontrol=GetForegroundWindow())
{
    RECT textrect={0};
    HDC txthdc=GetDC(hdccontrol);
    DrawText (txthdc,text.c_str(),-1,&textrect,DT_CALCRECT);
    ReleaseDC(hdccontrol,txthdc);
    SIZE a={textrect.right-textrect.left, textrect.bottom-textrect.top};
    return a;
}

the 1st string size isn't correct. then i get the correct one. so why i get, sometimes, the wrong size?
something to do with my HDC's font's or something. so i can't control it correctly :( can anyone advice me?

i did several mistakes. and i resolve the problem. see my new function:

SIZE GetStringSize(const string text, string ControlName="", int PartID=0, int StateID=0)
{

    RECT textrect={0};
    HDC txthdc=GetDC(GetForegroundWindow());

    if(ControlName=="")
    {
        DrawText (txthdc,text.c_str(),-1 ,&textrect,DT_CALCRECT| DT_EXPANDTABS);

    }
    else
    {
        HTHEME hTheme = OpenThemeData(GetForegroundWindow(), towstring(ControlName).c_str());

        GetThemeTextExtent(hTheme,txthdc, PartID , StateID,towstring(text).c_str(),text.size(),DT_CALCRECT | DT_EXPANDTABS,NULL, &textrect);

        DrawThemeText(hTheme, txthdc, PartID , StateID, towstring(text).c_str(),text.size(),DT_LEFT,0,&textrect);
        CloseThemeData(hTheme);
    }
    ReleaseDC(GetDesktopWindow(),txthdc);
    SIZE a={textrect.right-textrect.left, textrect.bottom-textrect.top};
    return a;
}

these function is prepared for GDI and THEME. my problem was with my Region function(again) :(

i did a mistake with DrawThemeText():

SIZE GetStringSize(const string text, string ControlName="", int PartID=0, int StateID=0)
{

    RECT textrect={0};
    HDC txthdc=GetDC(GetForegroundWindow());

    DrawText (txthdc,text.c_str(),-1 ,&textrect,DT_CALCRECT| DT_EXPANDTABS);

    if(ControlName=="")
    {
        DrawText (txthdc,text.c_str(),-1 ,&textrect,DT_CALCRECT| DT_EXPANDTABS);

    }
    else
    {
        HTHEME hTheme = OpenThemeData(GetForegroundWindow(), towstring(ControlName).c_str());

        GetThemeTextExtent(hTheme,txthdc, PartID , StateID,towstring(text).c_str(),text.size(),DT_CALCRECT | DT_EXPANDTABS,NULL, &textrect);

        //DrawThemeText(hTheme, txthdc, PartID , StateID, towstring(text).c_str(),text.size(),DT_CALCRECT | DT_EXPANDTABS | DT_LEFT,0,&textrect);
        CloseThemeData(hTheme);
    }
    ReleaseDC(GetDesktopWindow(),txthdc);
    SIZE a={textrect.right-textrect.left, textrect.bottom-textrect.top};
    return a;
}

if we do not use DT_CALCRECT flag, the text is drawed on focus window or parent window.

just a tip: if you choose the font on control, and the control isn't resize. just use\select the same font to txthdc and then calculate the size ;)
thanks to all

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.