Using comments the problem has been clarified and I will give a summary here as solution.
The
Invalid Parameter error code 2 indicates that one or more of the
DrawString()
parameters are invalid. So they must be checked. Many GDI+ plus objects are constructed with parameters. Because constructors does not return a value and no exceptions are thrown, GDI+ plus provides
GetLastStatus()
member functions that can be used after construction to check for success. So the code can be updated with error checking:
Gdiplus::SolidBrush SolidBrush2(Color(255,51,51,51));
Status st = SolidBrush2.GetLastStatus();
if (Gdiplus::Ok == st)
{
Gdiplus::FontFamily fontFamily(L"宋体");
st = fontFamily.GetLastStatus();
if (Gdiplus::Ok == st)
{
Gdiplus::Font font(&fontFamily,12,
Gdiplus::FontStyleRegular,Gdiplus::UnitPixel);
st = font.GetLastStatus();
if (Gdiplus::Ok == st)
{
grap.SetSmoothingMode( SmoothingModeHighSpeed );
StringFormat _strformat;
_strformat.SetTrimming(StringTrimmingEllipsisWord);
_strformat.SetLineAlignment(StringAlignmentCenter);
st = grap.DrawString(sTest.c_str(),sTest.length(),&font,gRect,
&_strformat,&SolidBrush2);
}
}
}
if (Gdiplus::Ok != st)
{
}
A potential error candidate is the
FontFamily
construction. The specified family may be not present on all systems. To avoid errors on such systems, a fallback using a generic type face may be used:
Gdiplus::FontFamily fontFamily(L"宋体");
Gdiplus::Font font(Gdiplus::Ok == fontFamily.GetLastStatus() ?
&fontFamily : Gdiplus::FontFamily::GenericSansSerif(),
12,Gdiplus::FontStyleRegular,Gdiplus::UnitPixel);