通过C++编程更改exe文件的图标

5
我有一个在MFC中创建的应用程序,需要为exe设置几个图标中的其中一个。我不知道要使用哪个图标,直到该应用程序安装在用户的计算机上。我已经按照几个网站(包括https://learn.microsoft.com/en-us/windows/win32/menurc/using-resources)上的说明进行了编程。
在应用程序的.rc文件中,exe使用的图标是IDR_MAINFRAME(ID 128),只是一个标准的.ico文件。运行更新代码后,当我在Visual Studio中打开exe时,我看到IDR_MAINFRAME的图标已更新为正确的图标,但在资源管理器中使用的exe图像仍显示旧(原始)图标。我没有看到更新后的exe中任何关于原始图标的引用。
我错过了什么?
HGLOBAL hResLoad;   // handle to loaded resource
HMODULE hExe;       // handle to existing .EXE file
HRSRC hRes;         // handle/ptr. to res. info. in hExe
HANDLE hUpdateRes;  // update resource handle
LPVOID lpResLock;   // pointer to resource data
BOOL result;

hExe = LoadLibrary(TEXT("app.exe"));
if (hExe == NULL)
{
  return;
}

// Locate the icon resource in the .EXE file.
hRes = FindResource(hExe, MAKEINTRESOURCE(IDI_TB_SAVE), RT_GROUP_ICON);
if (hRes == NULL)
{
  return;
}

// Load the resource into global memory.
hResLoad = LoadResource(hExe, hRes);
if (hResLoad == NULL)
{
  return;
}

// Lock the resourcex into global memory.
lpResLock = LockResource(hResLoad);
if (lpResLock == NULL)
{
  return;
}
 
// Open the file to which you want to add the icon resource.
hUpdateRes = BeginUpdateResource(TEXT("app_updated.exe"), FALSE);
if (hUpdateRes == NULL)
{
  return;
}

result = UpdateResource(hUpdateRes,    // update resource handle
  RT_GROUP_ICON,                         // change icon resource
  MAKEINTRESOURCE(IDR_MAINFRAME),         // resource id
  MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),  // english
  lpResLock,                         // ptr to resource info
  SizeofResource(hExe, hRes));       // size of resource info

if (result == FALSE)
{
  return;
}

// Write changes to app_updated.exe and then close it.
if (!EndUpdateResource(hUpdateRes, FALSE))
{
  return;
}

// Clean up.
if (!FreeLibrary(hExe))
{
  return;
}

3
资源管理器会暂时缓存图标。如果不这样做,打开包含大量可执行文件的文件夹会变得非常缓慢(因为需要逐个读取和解析每个文件)。可以尝试使用 https://superuser.com/questions/499078/refresh-icon-cache-without-rebooting 来刷新图标缓存,无需重启计算机。 - Richard Critten
是的,这是一个缓存问题。谢谢! - Tony Nelson
1
这是一个难得的机会,可以为一个形式良好、措辞恰当、范围明确的问题点赞。 - IInspectable
1个回答

0
根据@RichardCritten的建议,我刷新了图标缓存(只是重新启动了explorer.exe),更新后的图标正确显示了。代码没有问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接