We help IT Professionals succeed at work.

C++ in VS2008, using GDI+ DrawString

MOSSPOINT
MOSSPOINT asked
on
Hi Experts,

I'm new to C++ and finding most things a lot harder than vb.net.

I have a clock duration in variable tDuration of type clock_t and I’ve build a plain win32 application and created a hdcWindow that I’m drawing to using GDI+.

                   clock_t tDuration = clock() - tStart;
              
              Font drawFont(L"Arial", 16);
              RectF layoutRect(0.0f, 0.0f, 200.0f, 50.0f);
              StringFormat format;
              format.SetAlignment(StringAlignmentCenter);
              SolidBrush drawBrush( Color::Black );

                  graphics.DrawString(tDuration, 11, &drawFont, layoutRect, &format, &drawBrush);

I get an error when this code runs because the graphics.DrawString wants to convert the tDuration (see error below).  

So can someone give me some code that shows me how to get the variable tDuration into a string format that DrawString can use?

Error      1      error C2664: 'Gdiplus::Status Gdiplus::Graphics::DrawString(const WCHAR *,INT,const Gdiplus::Font *,const Gdiplus::RectF &,const Gdiplus::StringFormat *,const Gdiplus::Brush *)' : cannot convert parameter 1 from 'clock_t' to 'const WCHAR *'


Comment
Watch Question

Commented:
tDuration is clock_t. DrawString receives a text as the first parameter.
The time is minimal in your case. Use sprintf to convert clock_t to a string. For example, so:

char szText[100] = { 0 };
snprintf(szText, "Duration: %d", tDuration");

If your project is a Unicode project you need wchar_t type and _swnprintf function.

clock_t and clock() function is not a native Win32. I'd say to use GetTickCount() for such case in the pure Win32 application. It is the same:
DWORD nStart = GetTickCount();
//code here
DWORD nDuration = GetTickCount() - nStart;

Commented:
Sorry, the function name for Unicode is _snwprintf:
http://msdn.microsoft.com/en-us/library/2ts7cx93(VS.71).aspx

DrawString in MSDN:
http://msdn.microsoft.com/en-us/library/ms535991(VS.85).aspx

There is an example that you are using. You will see WCHAR there. So
WCHAR szText[100] = { 0 };
_snwprintf(szText, 100, L"Duration: %d msec", nDuration);

Commented:
short tutorial if you need:
GDI+ Example: Using GDI+ Brushes to Draw Text
http://www.ucancode.net/faq/GDI+_Example.htm

Author

Commented:
pgnatyuk,

Thanks seems to work apart from I only get one digit after the duration?  Any ideas?

Commented:
I didn't understand. Can you post the string you got here?
one digit?

Maybe in DrawString you need to set a bigger rectangle. In the debugger you can check the string itself.

Author

Commented:
No problem got it working.