What you need to know about LPCTSTR in Windows API (Specially for Qt users)

Posted on Posted in Qt Tutorials, Tutorials

This question comes up a lot and is sometimes very confusing but if you just pay attention for a few seconds you’ll get past this forever, I promise you.

LPCTSTR is the string type used by most of the Windows API functions so if you are going to do anything using Microsoft Windows API functions then you have to know what it is.

Here it is, LPCTSTR is actually a shape-shifter. Depending on the UNICODE flag it becomes an ANSI string (LPCSTR) or a string consisting of wide characters (LPCWSTR).





In many cases you can use the TEXT() macro to convert literals to LPCTSTR, as seen in the example below:

MessageBox(h, TEXT(“This is a test message!”), TEXT(“Info”), 0);

The above line is the simple MessageBox function found in Win32 API and as you can see I have used TEXT() macro to make sure the string type is always correct.

What if it is not a literal? What if you are on Qt and you want to pass a QString to MessageBox?(or any other Windows API functions for that matter)

Here it is:

QString str = “www.amin-ahmadi.com”;

#ifdef UNICODE
MessageBox(h, str.toStdWString().c_str(), TEXT(“Cap”), 0);
#else
MessageBox(h, str.toStdString().c_str(), TEXT(“Cap”), 0);
#endif

As you can see I have made use of the same UNICODE flag and thus my code will work under any circumstances.





For more on converting a QString to C type string also see the following posts:

HOW TO CONVERT QSTRING TO C STRING (CHAR *)

HOW TO CONVERT QSTRING TO WIDE C STRING (WCHAR_T *)

Leave a Reply

Your email address will not be published. Required fields are marked *