LoadString用法
LoadString 从资源载入字符串,我们一般这么用。
举个例子:
TCHAR str[20];
LoadString(hInstance, IDS_STR, str, 20);
如果我们的字符串的长度不知道,或许它会变化的话,我们怎么来获得资源ID对应的字符串呢?这就要用到
LoadString的另一种用法,我们可以这样用
LPCTSTR lpcStr = (LPCTSTR)LoadString(hInstance, IDS_STR, NULL, 0);
感觉上没有什么问题啊?
但是实际应用中又出现问题了,读出的字符串没有截断处理,它包含了下一个ID包含的字符串或者更多。
怎么办?在MSDN中,LoadString已经清楚地指出
lpBuffer is set to NULL, the return value is a pointer to the requested string. The caller should cast the return value to an LPCTSTR. This pointer points directly to the resource, so the string is read-only. The length of the string, not including any terminating null character, can be found in the word preceding the string.
同时它也给出了解决办法:
To use the lpBuffer pointer, the –n flag must be set with the resource compiler, RC.
Note String resources are not null-terminated by default. When lpBuffer is set to NULL, verify whether the string resource represented by the pointer returned by LoadString is null-terminated, and if necessary, append a terminating null character to the resource before using it in your application.
一开始我没有太明白the –n flag must be set with the resource compiler, RC.的含义,很迷惑,不知道如何解决。但是在网上寻找方法的时候,发现这么一篇文章http://lak4cyut.blogspot.com/2008/08/wm-api-loadstring.html(WM API : LoadString() 另一種使用方式),我才彻底明白过来。
我使用的是VS2005,在project->properties->Resource->Command Line中添加一个 “-n”,即可。
在运行程序,正常显示了。
大家如遇相同问题,可以试试这个方法。