Extract file from resource in Windows module

2019-03-04 13:28发布

问题:

The below code executes, but it only extracts an empty bitmap file. Any ideas as to what is wrong with it?

void Extract(WORD wResId , LPSTR lpszOutputPath)
{ //example: Extract(IDB_BITMAP1, "Redrose.bmp");
    HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(wResId) , RT_BITMAP);
    HGLOBAL hLoaded = LoadResource( NULL,hrsrc);
    LPVOID lpLock =  LockResource( hLoaded);
    DWORD dwSize = SizeofResource(NULL, hrsrc);
    HANDLE hFile = CreateFile  (lpszOutputPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    DWORD dwByteWritten;
    WriteFile(hFile, lpLock , dwSize , &dwByteWritten , NULL);
    CloseHandle(hFile);
    FreeResource(hLoaded);
}

回答1:

You are asking for RT_RCDATA but I bet you didn't add your bitmap via a RCDATA statement. You probably added it via a BITMAP statement, which makes it RT_BITMAP.

In the future, please state which step failed rather than making people guess.



回答2:

Insert your raw file as a custom data. Give this custom data a text name, example "MyType", then:

HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(wResId) , _T("MyType"));


回答3:

The problem is in passing NULL as your HINSTANCE parameter to FindResource, LoadResource, and SizeOfResource.

If you have not already saved your HINSTANCE during startup (from WinMain or DllMain) you can get it using:

MFC:

HINSTANCE hInstance = AfxGetInstanceHandle();

Else:

HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);