Home > Software design >  Set wallpaper from resource image file
Set wallpaper from resource image file

Time:05-13

I would like to set the background wallpaper from a resource image. I found and tried this code, but FindResource() can't find anything. Can anybody help me please?

HINSTANCE hInstance = GetModuleHandle(NULL);

std::cout << hInstance << std::endl;

HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(IDB_PNG1), RT_BITMAP);

std::cout << hResInfo<< std::endl;

HGLOBAL hRes = LoadResource(hInstance, hResInfo);

std::cout << hRes << std::endl;

LPVOID memRes = LockResource(hResInfo);
DWORD sizeRes = SizeofResource(hInstance, hResInfo);

std::cout << memRes<< std::endl;
std::cout << sizeRes<< std::endl;

HANDLE hFile = CreateFile("C:\\Users\\Asus\\Desktop\\test.png", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwWritten = 0;
WriteFile(hFile, memRes, sizeRes, &dwWritten, NULL);
CloseHandle(hFile);

SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID) "C:\\Users\\Asus\\Desktop\\test.png", SPIF_UPDATEINIFILE);

resource file

#include "resource.h"


IDI_ICON1               ICON                    "chrome.ico"


IDB_PNG1                PNG                     "C:\\Users\\Asus\\Pictures\\jano.png"

resource.h

#define IDI_ICON1                       101
#define IDB_PNG1                        102

CodePudding user response:

There are two mistakes in your code:

  • You are creating the IDB_PNG1 resource as type PNG, but you are asking FindResource() to find a resource whose type is BITMAP instead. The types need to match, so replace RT_BITMAP with TEXT("PNG") in the call to FindResource(). Alternatively, use RCDATA instead of PNG in the .rc file, and then use RT_RCDATA instead of RT_BITMAP/"PNG" in the call to FindResource().

  • you are passing the wrong handle to LockResource(). You are passing in hResInfo that is returned by FindResource(), but you need to instead pass in hRes that is returned by LoadResource().

CodePudding user response:

RCDATA resource stores integers or strings of characters And the data is returned by LoadResource.
With the statement: IDR_PNG1 RCDATA {"pngwing.png"},
LoadResource returns pngwing.png while LockResource retrieves a pointer to the specified resource in memory.

  • Related