Link to home
Start Free TrialLog in
Avatar of MOSSPOINT
MOSSPOINTFlag for United Kingdom of Great Britain and Northern Ireland

asked on

C++ in VS2008, using GDI+ DrawString

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 *'


Avatar of pgnatyuk
pgnatyuk
Flag of Israel image

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;
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);

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

ASKER

pgnatyuk,

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

ASKER CERTIFIED SOLUTION
Avatar of pgnatyuk
pgnatyuk
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No problem got it working.