- Using Resources
- Updating Resources
- Creating a Resource List
- FindResourceA function (winbase.h)
- Syntax
- Parameters
- Return value
- Remarks
- TypeID
- Values
- Partition Types
- BIOS/MBR-Based Systems
- UEFI/GPT-Based Systems
- Valid Configuration Passes
- Parent Hierarchy
- Applies To
- XML Example
- Файлы ресурсов (C++) Resource Files (C++)
- Изменяемые ресурсы Editable Resources
- Ресурсы манифеста Manifest Resources
- Открытие ресурса манифеста To open a manifest resource
Using Resources
This section contains code snippets for the following tasks:
Updating Resources
The following example copies a dialog box resource from one executable file, Hand.exe, to another, Foot.exe, by following these steps:
- Use the LoadLibrary function to load the executable file Hand.exe.
- Use the FindResource and LoadResource functions to locate and load the dialog box resource.
- Use the LockResource function to retrieve a pointer to the dialog box resource data.
- Use the BeginUpdateResource function to open an update handle to Foot.exe.
- Use the UpdateResource function to copy the dialog box resource from Hand.exe to Foot.exe.
- Use the EndUpdateResource function to complete the update.
The following code implements these steps.
Security Warning: Using LoadLibrary incorrectly can compromise the security of your application by loading the wrong DLL. Refer to the LoadLibrary documentation for information on how to correctly load DLLs with different versions of Windows.
Creating a Resource List
The following example creates a list of every resource in the Hand.exe file. The list is written to the Resinfo.txt file.
The code demonstrates how to load the executable file, create a file in which to write resource information, and call the EnumResourceTypes function to send each resource type found in the module to the application-defined callback function EnumTypesFunc . See EnumResTypeProc for information on callback functions of this type. This callback function uses the EnumResourceNames function to pass the name of every resource within the specified type to another application-defined callback function, EnumNamesFunc . See EnumResNameProc for information on callback functions of this type. EnumNamesFunc uses the EnumResourceLanguages function to pass the language of every resource of the specified type and name to a third callback function, EnumLangsFunc . See EnumResLangProc for information on callback functions of this type. EnumLangsFunc writes information about the resource of the specified type, name, and language to the Resinfo.txt file.
Note that the lpszType in EnumResTypeProc is either a resource ID or a pointer to a string (containing a resource ID or type name); lpszType and lpszName in EnumResNameProc and EnumResLangProc are similar. To load an enumerated resource, just call the appropriate function. For example, if a menu resource (RT_MENU) was enumerated, then pass lpszName to LoadMenu. For custom resources, pass lpszType and lpszName to FindResource.
The Updating Resources code follows a similar pattern for a dialog box resource.
Security Warning: Using LoadLibrary incorrectly can compromise the security of your application by loading the wrong DLL. Refer to the LoadLibrary documentation for information on how to correctly load DLLs with different versions of Windows.
FindResourceA function (winbase.h)
Determines the location of a resource with the specified type and name in the specified module.
To specify a language, use the FindResourceEx function.
Syntax
Parameters
A handle to the module whose portable executable file or an accompanying MUI file contains the resource. If this parameter is NULL, the function searches the module used to create the current process.
The name of the resource. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where ID is the integer identifier of the resource. For more information, see the Remarks section below.
The resource type. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where ID is the integer identifier of the given
resource type. For standard resource types, see Resource Types. For more information, see the Remarks section below.
Return value
If the function succeeds, the return value is a handle to the specified resource’s information block. To obtain a handle to the resource, pass this handle to the LoadResource function.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
If IS_INTRESOURCE is TRUE for x = lpName or lpType, x specifies the integer identifier of the name or type of the given resource. Otherwise, those parameters are long pointers to null-terminated strings. If the first character of the string is a pound sign (#), the remaining characters represent a decimal number that specifies the integer identifier of the resource’s name or type. For example, the string «#258» represents the integer identifier 258.
To reduce the amount of memory required for a resource, an application should refer to it by integer identifier instead of by name.
An application can use FindResource to find any type of resource, but this function should be used only if the application must access the binary resource data by making subsequent calls to LoadResource and then to LockResource.
To use a resource immediately, an application should use one of the following resource-specific functions to find the resource and convert the data into a more usable form.
Function | Action |
---|---|
FormatMessage | Loads and formats a message-table entry. |
LoadAccelerators | Loads an accelerator table. |
LoadBitmap | Loads a bitmap resource. |
LoadCursor | Loads a cursor resource. |
LoadIcon | Loads an icon resource. |
LoadMenu | Loads a menu resource. |
LoadString | Loads a string-table entry. |
В
For example, an application can use the LoadIcon function to load an icon for display on the screen. However, the application should use FindResource and LoadResource if it is loading the icon to copy its data to another application.
String resources are stored in sections of up to 16 strings per section. The strings in each section are stored as a sequence of counted (not necessarily null-terminated) Unicode strings. The LoadString function will extract the string resource from its corresponding section.
TypeID
Use TypeID to manually specify a hard-drive partition type, such as a utility partition type.
Five partition types are already built in: primary, extensible firmware interface (EFI), extended, logical, and Microsoft Reserved (MSR). To use these built-in partition types, enter a value in the setting: microsoft-windows-setup-/DiskConfiguration/Disk/CreatePartitions/CreatePartition/Type.
Some partition types are not assigned a drive letter by default. Without a drive letter, these partitions do not appear in some common lists of devices, such as in Windows Explorer or in Open or Save file dialog boxes. If you assign a letter to the partition, the partition appears in these common lists of devices.
Values
Specifies the partition type. See the Partition Types section later in this topic.
TypeID is a string.
Partition Types
The following tables describe how to set common partition types by using the microsoft-windows-setup-/DiskConfiguration/Disk settings:
BIOS/MBR-Based Systems
Partition type | How to set the value | Used for | Receives a drive letter by default? | ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Partition type | How to set the value | Used for | Receives a drive letter by default? | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Имя файла File name | Описание Description |
---|---|
.rc .rc | Файлы скриптов ресурсов Resource script files |
.rct .rct | Файлы шаблонов ресурсов Resource template files |
RES .res | Файлы ресурсов Resource files |
.resx .resx | Управляемые файлы ресурсов Managed resource files |
EXE .exe | Исполняемые файлы Executable files |
DLL .dll | Файлы библиотек динамической компоновки Dynamic-link library files |
. bmp,. ico,. DIB,. cur .bmp, .ico, .dib, .cur | Точечные рисунки, значки, панели инструментов и файлы курсоров Bitmap, icon, toolbar, and cursor files |
При редактировании ресурсов среда Visual Studio работает с и влияет на следующие файлы: When editing resources, the Visual Studio environment works with and affects the following files:
Имя файла File name | Описание Description |
---|---|
Resource.h Resource.h | Файл заголовка, созданный средой разработки, которая содержит определения символов. Header file generated by the development environment that contains symbol definitions. Включить этот файл в систему управления версиями. Include this file in source control. |
Filename.aps Filename.aps | Двоичная версия текущего файла скрипта ресурсов, используемая для быстрой загрузки. Binary version of the current resource script file used for quick loading. Редакторы ресурсов не читают файлы RC или resource. h напрямую. Resource editors don’t directly read .rc or resource.h files. Компилятор ресурсов компилирует их в APS файлы, используемые редакторами ресурсов. The resource compiler compiles them into .aps files that are consumed by the resource editors. Этот файл представляет собой этап компиляции и содержит только символьные данные. This file is a compile step and only stores symbolic data. Как и в случае обычного процесса компиляции, сведения, не являющиеся символьными, например комментарии, удаляются во время компиляции. As with a normal compile process, information that isn’t symbolic, such as commenting, is discarded during the compile process. Если файл APS не синхронизирован с RC-файлом, RC-файл создается повторно. Whenever the .aps file is out of synch with the .rc file, the .rc file is regenerated. Например, при сохранении редактор ресурсов перезаписывает файл. RC и файл Resource. h. For example, when you Save, the resource editor overwrites the .rc file and the resource.h file. Любые изменения в ресурсах остаются включенными в RC-файл, но при перезаписании RC-файла комментарии всегда будут потеряны. Any changes to the resources themselves remain incorporated in the .rc file, but comments will always be lost once the .rc file is overwritten. Сведения о том, как сохранять комментарии, см. в разделе Включение ресурсов во время компиляции. For information on how to preserve comments, see Include Resources at Compile Time. Как правило, файл APS не должен включаться в систему управления версиями. Typically, you shouldn’t include the .aps file in source control. |
.rc .rc | Файл описания ресурсов, содержащий скрипт для ресурсов в текущем проекте. Resource script file that contains script for the resources in your current project. Этот файл перезаписывается APS-файлом при каждом сохранении. This file is overwritten by the .aps file whenever you save. Включить этот файл в систему управления версиями. Include this file in source control. |
Ресурсы манифеста Manifest Resources
В проектах классических приложений C++ Ресурсы манифеста представляют собой XML-файлы, описывающие зависимости, используемые приложением. In C++ desktop projects, manifest resources are XML files that describe the dependencies an application uses. Например, в Visual Studio созданный мастером MFC файл манифеста определяет, какую версию библиотек DLL общих элементов управления Windows должно использовать приложение: For example, in Visual Studio this MFC wizard-generated manifest file defines which version of the Windows common control DLLs the application should use:
Для приложения Windows XP или Windows Vista ресурс манифеста должен указывать последнюю версию стандартных элементов управления Windows для использования приложением. For a Windows XP or Windows Vista application, the manifest resource should specify the most current version of the Windows common controls for the application to use. В приведенном выше примере используется версия 6.0.0.0 , которая поддерживает элемент управления Syslink. The example above uses version 6.0.0.0 , which supports the Syslink control.
Допускается иметь только один ресурс манифеста на каждый модуль. You can only have one manifest resource per module.
Чтобы просмотреть сведения о версии и типе, содержащиеся в ресурсе манифеста, откройте файл в средстве просмотра XML-данных или в текстовом редакторе Visual Studio. To view the version and type information contained in a manifest resource, open the file in an XML viewer or the Visual Studio text editor. Если вы откроете ресурс манифеста из представления ресурсов, этот ресурс откроется в двоичном формате. If you open a manifest resource from Resource View, the resource will open in binary format.
Открытие ресурса манифеста To open a manifest resource
Откройте проект в Visual Studio и перейдите к Обозреватель решений. Open your project in Visual Studio and navigate to Solution Explorer.
Разверните папку файлы ресурсов , а затем: Expand the Resource Files folder, then:
Чтобы открыть его в текстовом редакторе, дважды щелкните файл . manifest . To open in the text editor, double-click the .manifest file.
Чтобы открыть в другом редакторе, щелкните правой кнопкой мыши файл manifest и выберите команду Открыть с помощью. To open in another editor, right-click the .manifest file and select Open With. Укажите используемый редактор и нажмите кнопку Открыть. Specify the editor to use and select Open.