11.2.1 Updating Resources

The following code fragment copies a dialog box resource from the executable file hand.exe to the executable file foot.exe.

The fragment uses the LoadLibrary function to load the executable file “hand.exe”. Then, FindResource and LoadResource locate and load the dialog box resource named “MyDialog” from the file. LockResource returns a pointer to the dialog box resource data.

The fragment uses the BeginUpdateResource function to open an update handle for the file “foot.exe”. UpdateResource copies the dialog box resource from “hand.exe” to “foot.exe”, and EndUpdateResource completes the update.

HRSRC hResLoad; /* handle to loaded resource */

HANDLE hExe; /* handle to existing exe */

HICON hRes; /* handle/ptr to res info in hExe */

HANDLE hUpdateRes; /* update resource handle */

char *lpResLock; /* pointer to resource data */

/* Load the .exe file whose dialog box you want to copy. */

hExe = LoadLibrary("hand.exe");

if (hExe == NULL) {

ErrorHandler("Could not load exe.");

}

/* Locate the dialog box resource in the .exe file. */

hRes = FindResource(hExe, "MyDialog", RT_DIALOG);

if (hRes == NULL) {

ErrorHandler("Could not locate dialog box.");

}

/* Load dialog box into global memory. */

hResLoad = LoadResource(hExe, hRes);

if (hResLoad == NULL) {

ErrorHandler("Could not load dialog box.");

}

/* Lock dialog box in global memory. */

lpResLock = LockResource(hRes);

if (lpResLock == NULL) {

ErrorHandler("Could not lock dialog box.");

}

/* Open file you wish to add dialog box resource to. */

hUpdateRes = BeginUpdateResource("foot.exe");

if (hUpdateRes == NULL) {

ErrorHandler("Could not open file for writing.");

}

/* Add dialog box resource. */

result = UpdateResource(hUpdateRes, /* update res handle */

RT_DIALOG, /* change dialog box resource */

"MyDialog", /* dialog box name */

MAKELANGID(LANG_NEUTRAL,

SUBLANG_NEUTRAL), /* neutral language id */

(PVOID) lpResLock, /* ptr to resource info */

SizeofResource(hExe, hRes)); /* size of res info */

if (result == FALSE) {

ErrorHandler("Could not add resource.");

}

/* Close altered file. */

if (!EndUpdateResource(hUpdateRes, FALSE)) {

ErrorHandler("Could not write changes to file.");

}

/* Clean up. */

if (!FreeLibrary(hExe)) {

ErrorHandler("Could not free executable.");

}