今天在做東西的時(shí)候,用LoadString遇到了一些問(wèn)題.可能大家日后也會(huì)用到,分享一下.
LoadString 從資源載入字符串,我們一般這么用。
舉個(gè)例子:
TCHAR str[20];
LoadString(hInstance, IDS_STR, str, 20);
如果我們的字符串的長(zhǎng)度不知道,或許它會(huì)變化的話,我們?cè)趺磥?lái)獲得資源ID對(duì)應(yīng)的字符串呢?這就要用到
LoadString的另一種用法,我們可以這樣用
LPCTSTR lpcStr = (LPCTSTR)LoadString(hInstance, IDS_STR, NULL, 0);
感覺(jué)上沒(méi)有什么問(wèn)題啊?
但是實(shí)際應(yīng)用中又出現(xiàn)問(wèn)題了,讀出的字符串沒(méi)有截?cái)嗵幚恚讼乱粋€(gè)ID包含的字符串或者更多。
怎么辦?在MSDN中,LoadString已經(jīng)清楚地指出
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.
同時(shí)它也給出了解決辦法:
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.
一開(kāi)始我沒(méi)有太明白the –n flag must be set with the resource compiler, RC.的含義,很迷惑,不知道如何解決。但是在網(wǎng)上尋找方法的時(shí)候,發(fā)現(xiàn)這么一篇文章http://lak4cyut.blogspot.com/2008/08/wm-api-loadstring.html(WM API : LoadString() 另一種使用方式),我才徹底明白過(guò)來(lái)。
我使用的是VS2005,在project->properties->Resource->Command Line中添加一個(gè) “-n”,即可。
在運(yùn)行程序,正常顯示了。
大家如遇相同問(wèn)題,可以試試這個(gè)方法。
posted on 2008-12-17 20:07
Sandy 閱讀(6641)
評(píng)論(8) 編輯 收藏 引用 所屬分類:
windows學(xué)習(xí)