跳到主要內容

在程式裡嵌入二進位檔(VC++)

Import:
1. 切換到 Resource Tab
2. (VC6)在專案名稱上按下 mouse 右鍵,選擇 "Import..."
2. (VC2005)在專案名稱上按下 mouse 右鍵,選擇 Add,再選擇 Resource,或是直接選擇 rc 按下右鍵,選擇 Add Resource,點下 "Import..."
3. 點選所要嵌入的檔案後,Resource Type 填入 RCDATA,存檔/編譯即完成。

解開:

int ExtractFile(int nResourceId, LPCTSTR lpType, LPCTSTR strOutputName)
{
    DWORD dwWritten = 0;

    HRSRC hRsrc = FindResource(NULL, MAKEINTRESOURCE(nResourceId), lpType);
    if(NULL == hRsrc)
    {
        OutputDebugString(_T("FindResource fail !!!"));
        return 1;
    }

    DWORD dwImageSize = SizeofResource(NULL, hRsrc);
    if(dwImageSize == 0)
    {
        OutputDebugString(_T("FSize is 0 !!!"));
        return 1;
    }

    HGLOBAL hBinImage = LoadResource(NULL, hRsrc);
    if(NULL == hBinImage)
    {
        OutputDebugString(_T("Couldn't load binary image from resources!!!"));
        return 1;
    }

    PVOID pBinImage = LockResource(hBinImage);
    if(NULL == pBinImage)
    {
        OutputDebugString(_T("Couldn't lock binary image from resources!!!"));
        return 1;
    }

    // create a new file
    HANDLE hFile = CreateFile(strOutputName,
                              (GENERIC_READ | GENERIC_WRITE),
                              0,
                              NULL,
                              CREATE_ALWAYS,
                              FILE_ATTRIBUTE_NORMAL,
                              NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        OutputDebugString(_T("Create file fail!!!"));
        return 1;
    }

    // write the content to the file
    if (!WriteFile(hFile, pBinImage, dwImageSize, &dwWritten, NULL))
    {
        OutputDebugString(_T("Failed to write file!!!"));
        CloseHandle(hFile);
        return 1;
    }

    CloseHandle(hFile);

    FreeResource((HANDLE)hRsrc);

    return 0;
}

留言