如何在Visual C++ 2010中打开资源字符串?

Ste*_*das 4 c++ string resources visual-c++

我在Visual C++中创建了一个基本的字符串表资源.我正在尝试访问该资源.但是,我的程序似乎无法找到资源.这里:

int main(int argc, char* argv[])
{
    HRSRC hRsrc;
    hRsrc = FindResource(NULL, MAKEINTRESOURCE(IDS_STRING102), RT_STRING);
    if (hRsrc == NULL) {
        printf("Not found\n");
    } else {
        printf("Found\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

此程序找不到资源并始终返回null.

我创建了一个简单的位图资源,这个新程序识别出来就好了.这里:

int main(int argc, char* argv[])
{
    HRSRC hRsrc;
    hRsrc = FindResource(NULL, MAKEINTRESOURCE(IDB_BITMAP1), RT_BITMAP);
    if (hRsrc == NULL) {
        printf("Not found\n");
    } else {
        printf("Found\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

这会找到位图.

是否以不同的方式处理字符串表资源?

Cap*_*ous 6

假设您不想使用LoadString(),这应该有帮助......

使用FindResource()和FindResourceEx()时,字符串和字符串表确实被区别对待.来自这篇知识库文章:

字符串资源存储为字符串块.每个块最多可包含16个字符串,表示可以加载/更新的字符串资源的最小粒度.每个块由标识符(ID)标识,从一(1)开始.我们在调用FindResource,LoadResource和UpdateResource函数时使用此ID.

ID为nStringID的字符串位于ID为nBlockID的块中,由以下公式给出:

nBlockID =(nStringID/16)+ 1; //注意整数除法.

nStringID的低4位表示块中的哪个条目包含实际字符串.一旦计算出要传递给FindResource()的块ID和字符串所在块中的索引,就必须扫描它的内容以找到您要查找的字符串.

以下代码可以帮助您入门.

const WCHAR *stringPtr;
WCHAR stringLen;

//  Get the id of the string table block containing the target string
const DWORD blockID = (nID >> 4) + 1;

//  Get the offset of teh target string in the block
const DWORD itemID = nID % 0x10;

//  Find the resource
HRSRC hRes = FindResourceEx(
    hInst,
    RT_STRING,
    MAKEINTRESOURCE(blockID),
    wLanguage);
if (hRes)
{
    HGLOBAL hBlock = LoadResource(hInst, hRes);
    const WCHAR *tableDataBlock = reinterpret_cast<LPCWSTR>(LockResource(hBlock));
    const DWORD tableBlockSize = SizeofResource(hInst, hRes);
    DWORD searchOffset = 0;
    DWORD stringIndex = 0;

    //  Search through the section for the appropriate entry.
    //  The first two bytes of each entry is the length of the string
    //  followed by the Unicode string itself. All strings entries 
    //  are stored one after another with no padding.
    while(searchOffset < tableBlockSize)
    {
        if (stringIndex == itemID)
        {
            //  If the string has size. use it!
            if (tableDataBlock[searchOffset] != 0x0000)
            {
                stringPtr = &tableDataBlock[searchOffset + 1];
                stringLen = tableDataBlock[searchOffset];
            }
            //  Nothing there -
            else
            {
                stringPtr = NULL;
                stringLen = 0;
            }

            //  Done
            break;
        }

        //  Go to the next string in the table
        searchOffset += tableDataBlock[searchOffset] + 1;

        //  Bump the index
        stringIndex++;
    }
}
Run Code Online (Sandbox Code Playgroud)