Why does Microsoft's code examples have errors, and how do I fix these?

CDev-8220 220 Reputation points
2024-04-08T08:44:10.4733333+00:00

The code examples on this page all seem to have errors, some of which I don't have a clue how to fix.

How do I fix the following:

code:

hResult = StringCchLength(pmyitem->psz, STRSAFE_MAX_CCH, pcch);

error:

argument of type "LPSTR"is incompatible with parameter of "STRSAFE_PCNZWCH"

code:

GetTextExtentPoint32(hdc, pmyitem->psz, *pcch, &size);
ExtTextOut(
	lpdis->hDC, 
	nTextX, 
	nTextY, 
	ETO_OPAQUE, 
	&lpdis->rcItem, 
	pmyitem->psz, 
	*pcch, NULL
);

error:

argument of type "LPSTR"is incompatible with parameter of "LPCWSTR"

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,730 questions
{count} votes

Accepted answer
  1. RLWA32 45,571 Reputation points
    2024-04-08T09:28:40.9233333+00:00

    Windows API functions usually have two versions. There is a "W" version when building for UNICODE and an "A" version for non-UNICODE builds. For example, when building for UNICODE the compiler sees a function named ExtTextOutW which expects wide-character strings. However, the example code declares some variables as LPSTR which means it is a pointer to a narrow string. This causes the compiler errors.

    The simplest solution is to change the character set that you are building for to either "Not Set" or MBCS. That should eliminate the kinds of errors you have described.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Castorix31 85,136 Reputation points
    2024-04-08T09:18:44.29+00:00

    Use WCHAR (LPTSTR) everywhere :

    typedef struct _MYITEM
    {
    	HFONT hfont;
    	LPTSTR psz;
    } MYITEM;   
    

  2. Minxin Yu 11,746 Reputation points Microsoft Vendor
    2024-04-08T09:19:44.9933333+00:00

    Hi, @CDev-8220

    The sample uses ANSI. StringCchLengthA and GetTextExtentPoint32A
    Set MBCS or use wchar
    User's image

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.