Windows common controls manifest

Манифест приложения на ассемблере

Когда я, в процессе своего обучения, подошел к написанию приложений, активно использующих различные графические элементы управления, раз за разом начал обращать внимание на одну интересную проблему. Дело в том, что при запуске двоичного исполняемого файла, все элементы, находящиеся в окне, выглядели «плоско», то есть имели упрощенный стиль, а-ля Windows 95/98. Долгое время я как-то не мог сообразить, почему у меня из раза в раз оформление окон получается каким-то упрощенным, без выпуклого объема кнопок, теней, объемных полос прокруток, элегантных тонких линий-рамок у групп элементов, а у подавляющего большинства сторонних оконных приложений, видимых мною в Сети, тема оформления окна как раз была «объемной»? Особенно это заметно в диалоговых окнах, где группируется большое количество разнообразных дочерних элементов управления, волей-неволей начинаешь к ним присматриваться, изучать детали.. и тут вот осознаешь, что в твоих то приложениях они получаются не такими элегантными. Оказалось, что если не предпринимать каких-либо дополнительных действий, то приложения, компилируемые FASM и использующие оконный графический интерфейс, все как на подбор получаются с упрощенной стилизацией интерфейса. Что я только не делал, уже и все стили элементов перебрал вдоль и поперек, ставя в параметры ресурсов всяческие мыслимые и немыслимые комбинации, эффект был разный, но неизменно далекий от желаемого. Как заставить приложение выглядеть в новом, современном стиле? В ходе практических изысканий, когда уже все варианты кончились, наконец-то начал думать 🙂 Как оказалось, ответ кроется в изменившихся принципах работы с общими элементами управления, подключаемых посредством механизма под названием манифест приложения.

Поскольку темой серии статей является изучение программирования под Windows на языке ассемблера, то и рассматривать мы будем тут преимущественно особенности подключения манифеста приложения применительно к приложению на ассемблере. Для начала обратимся к официальным источникам, согласно определению манифеста с сайта Microsoft:

Упрощенно, основной функциональной особенностью манифеста приложения является связывание нашего приложения с определенными общими и частными версиями библиотек. «Ну и что?» ,- скажете Вы, как это влияет на визуальное оформление элементов управления окна? Дело в том, что среди прочих в системе имеется библиотека общих элементов оформления (контролов), регламентирующая внешний вид этих самых элементов.

Использование тем оформления

Чтобы указать приложению использовать темы оформления, необходимо использовать comctl32.dll версии 6 или более поздней. Осуществляется подключение библиотеки Common Controls при помощи задания в манифесте имени атрибута Microsoft.Windows.Common-Controls с непосредственным указанием версии 6.0.0.0 , тем самым инициируя связывание процесса приложения (на стадии подготовки/выполнения) с библиотекой comctl32.dll шестой версии . Вследствие подобного связывания, все стандартные контролы рисуются в соответствии с активированной в системе темой оформления. Эта особенность впервые появилась в Windows XP и до сих пор актуальна для более поздних её версий.

Алгоритм настройки манифеста приложения

Давайте непосредственно от теории перейдем к практике и попытаемся сконфигурировать манифест приложения на ассемблере.

Загрузка общих элементов управления

В самом начале листинга программы, до вызова функции GetModuleHandle , добавляем строку:

Enabling Visual Styles

This topic explains how to configure your application to ensure that common controls are displayed in the user’s preferred visual style.

This topic includes the following sections.

Using Manifests or Directives to Ensure That Visual Styles Can Be Applied to Applications

To enable your application to use visual styles, you must use ComCtl32.dll version 6 or later. Because version 6 is not redistributable, it is available only when your application is running on a version of Windows that contains it. Windows ships with both version 5 and version 6. ComCtl32.dll version 6 contains both the user controls and the common controls. By default, applications use the user controls defined in User32.dll and the common controls defined in ComCtl32.dll version 5. For a list of DLL versions and their distribution platforms, see Common Control Versions.

If you want your application to use visual styles, you must add an application manifest or compiler directive that indicates that ComCtl32.dll version 6 should be used if it is available.

An application manifest enables an application to specify which versions of an assembly it requires. In Microsoft Win32, an assembly is a set of DLLs and a list of versionable objects that are contained within those DLLs.

Manifests are written in XML. The name of the application manifest file is the name of your executable followed by the file name extension .manifest; for example, MyApp.exe.manifest. The following sample manifest shows that the first section describes the manifest itself. The following table shows the attributes set by the assemblyIdentity element in the manifest description section.

Attribute Description
version Version of the manifest. The version must be in the form major.minor.revision.build (that is, n.n.n.n, where n section. This technique also applies to content packaged as HTML Applications (HTAs). To turn off visual styles, the META tag must be as follows:

If the browser setting and the tag setting do not agree, the page will not apply visual styles. For example, if the META tag is set to «no» and the browser is set to enable visual styles, visual styles will not be applied to the page. However, if either the browser or META tag is set to «yes» and the other item is not specified, visual styles will be applied.

Visual styles might change the layout of your content. Also, if you set certain attributes on intrinsic HTML controls, such as the width of a button, you might find that the label on the button is unreadable under certain visual styles.

You must thoroughly test your content using visual styles to determine whether applying visual styles has an adverse effect on your content and layout.

When Visual Styles are not Applied

To avoid applying visual styles to a top level window, give the window a non-null region (SetWindowRgn). The system assumes that a window with a non-NULL region is a specialized window that does not use visual styles. A child window associated with a non-visual-styles top level window may still apply visual styles even though the parent window does not.

If you want to disable the use of visual styles for all windows in your application, call SetThemeAppProperties and do not pass the STAP_ALLOW_NONCLIENT flag. If an application does not call SetThemeAppProperties, the assumed flag values are STAP_ALLOW_NONCLIENT | STAP_ALLOW_CONTROLS | STAP_ALLOW_WEBCONTENT. The assumed values cause the nonclient area, the controls, and web content to have a visual style applied.

Making Your Application Compatible with Earlier Versions of Windows

Much of the visual style architecture is designed to make it simple to continue to ship your product on earlier versions of Windows that do not support changing the appearance of controls. When shipping an application for more than one operating system, be aware of the following:

Application Manifests

An application manifest is an XML file that describes and identifies the shared and private side-by-side assemblies that an application should bind to at run time. These should be the same assembly versions that were used to test the application. Application manifests may also describe metadata for files that are private to the application.

For a complete listing of the XML schema, see Manifest File Schema.

Application manifests have the following elements and attributes.

Element Attributes Required
assembly Yes
manifestVersion Yes
noInherit No
assemblyIdentity Yes
type Yes
name Yes
language No
processorArchitecture No
version Yes
publicKeyToken No
compatibility No
application No
supportedOS Id No
maxversiontested Id No
dependency No
dependentAssembly No
file No
name No
hashalg No
hash No
activeCodePage No
autoElevate No
disableTheming No
disableWindowFiltering No
dpiAware No
dpiAwareness No
gdiScaling No
highResolutionScrollingAware No
longPathAware No
printerDriverIsolation No
ultraHighResolutionScrollingAware No
msix No
heapType No

File Location

Application manifests should be included as a resource in the application’s EXE file or DLL.

File Name Syntax

The name of an application manifest file is the name of the application’s executable followed by .manifest.

For example, an application manifest that refers to example.exe or example.dll would use the following file name syntax. You can omit the field if resource ID is 1.

example.exe. .manifest

example.dll. .manifest

Elements

Names of elements and attributes are case-sensitive. The values of elements and attributes are case-insensitive, except for the value of the type attribute.

assembly

A container element. Its first subelement must be a noInherit or assemblyIdentity element. Required.

The assembly element must be in the namespace «urn:schemas-microsoft-com:asm.v1». Child elements of the assembly must also be in this namespace, by inheritance or by tagging.

The assembly element has the following attributes.

Attribute Description
manifestVersion The manifestVersion attribute must be set to 1.0.

noInherit

Include this element in an application manifest to set the activation contexts generated from the manifest with the «no inherit» flag. When this flag is not set in an activation context, and the activation context is active, it is inherited by new threads in the same process, windows, window procedures, and Asynchronous Procedure Calls. Setting this flag prevents the new object from inheriting the active context.

The noInherit element is optional and typically omitted. Most assemblies do not work correctly using a no-inherit activation context because the assembly must be explicitly designed to manage the propagation of their own activation context. The use of the noInherit element requires that any dependent assemblies referenced by the application manifest have a noInherit element in their assembly manifest.

If noInherit is used in a manifest, it must be the first subelement of the assembly element. The assemblyIdentity element should come immediately after the noInherit element. If noInherit is not used, assemblyIdentity must be the first subelement of the assembly element. The noInherit element has no child elements. It is not a valid element in assembly manifests.

assemblyIdentity

As the first subelement of an assembly element, assemblyIdentity describes and uniquely identifies the application owning this application manifest. As the first subelement of a dependentAssembly element, assemblyIdentity describes a side-by-side assembly required by the application. Note that every assembly referenced in the application manifest requires an assemblyIdentity that exactly matches the assemblyIdentity in the referenced assembly’s own assembly manifest.

The assemblyIdentity element has the following attributes. It has no subelements.

Attribute Description
type Specifies the application or assembly type. The value must be Win32 and all in lower case. Required.
name Uniquely names the application or assembly. Use the following format for the name: Organization.Division.Name. For example Microsoft.Windows.mysampleApp. Required.
language Identifies the language of the application or assembly. Optional. If the application or assembly is language-specific, specify the DHTML language code. In the assemblyIdentity of an application intended for worldwide use (language neutral) omit the language attribute.
In an assemblyIdentity of an assembly intended for worldwide use (language neutral) set the value of language to «*».
processorArchitecture Specifies the processor. Valid values include x86 , amd64 , arm and arm64 . Optional.
version Specifies the application or assembly version. Use the four-part version format: mmmmm.nnnnn.ooooo.ppppp. Each of the parts separated by periods can be 0-65535 inclusive. For more information, see Assembly Versions. Required.
publicKeyToken A 16-character hexadecimal string representing the last 8 bytes of the SHA-1 hash of the public key under which the application or assembly is signed. The public key used to sign the catalog must be 2048 bits or greater. Required for all shared side-by-side assemblies.

compatibility

Contains at least one application. It has no attributes. Optional. Application manifests without a compatibility element default to Windows Vista compatibility on Windows 7.

application

Contains at least one supportedOS element. Starting in Windows 10, version 1903, it can also contain one optional maxversiontested element. It has no attributes. Optional.

supportedOS

The supportedOS element has the following attribute. It has no subelements.

Attribute Description
Id Set the Id attribute to to run the application using Vista functionality. This can enable an application designed for Windows Vista to run on a later operating system.
Set the Id attribute to to run the application using Windows 7 functionality.
Applications that support Windows Vista, Windows 7, and Windows 8 functionality do not require separate manifests. In this case, add the GUIDs for all the Windows operating systems.
For info about the Id attribute behavior in Windows, see the Windows 8 and Windows Server 2012 Compatibility Cookbook.
The following GUIDs correspond with the indicated operating systems:
-> Windows 10, Windows Server 2016 and Windows Server 2019
-> Windows 8.1 and Windows Server 2012 R2
-> Windows 8 and Windows Server 2012
-> Windows 7 and Windows Server 2008 R2
-> Windows Vista and Windows Server 2008
You can test this on Windows 7 or Windows 8.x by running Resource Monitor (resmon), going to the CPU tab, right-clicking on the column labels, «Select Column. «, and check «Operating System Context». On Windows 8.x, you can also find this column available in the Task Manager (taskmgr). The content of the column shows the highest value found or «Windows Vista» as the default.

maxversiontested

The maxversiontested element specifies the maximum version of Windows that the application was tested against. This is intended to be used by desktop applications that use XAML Islands and that are not deployed in an MSIX package. This element is supported in Windows 10, version 1903, and later versions.

The maxversiontested element has the following attribute. It has no subelements.

Attribute Description
Id Set the Id attribute to a 4-part version string that specifies the maximum version of Windows that the application was tested against. For example, «10.0.18226.0».

dependency

Contains at least one dependentAssembly. It has no attributes. Optional.

dependentAssembly

The first subelement of dependentAssembly must be an assemblyIdentity element that describes a side-by-side assembly required by the application. Every dependentAssembly must be inside exactly one dependency. It has no attributes.

Specifies files that are private to the application. Optional.

The file element has the attributes shown in the following table.

Attribute Description
name Name of the file. For example, Comctl32.dll.
hashalg Algorithm used to create a hash of the file. This value should be SHA1.
hash A hash of the file referred to by name. A hexadecimal string of length depending on the hash algorithm.

activeCodePage

Force a process to use UTF-8 as the process code page.

activeCodePage was added in Windows Version 1903 (May 2019 Update). You can declare this property and target/run on earlier Windows builds, but you must handle legacy code page detection and conversion as usual. See Use the UTF-8 code page for details.

This element has no attributes. UTF-8 is only valid value for activeCodePage element.

autoElevate

Specifies whether auto elevate is enabled. TRUE indicates that it is enabled. It has no attributes.

disableTheming

Specifies whether giving UI elements a theme is disabled. TRUE indicates disabled. It has no attributes.

disableWindowFiltering

Specifies whether to disable window filtering. TRUE disables window filtering so you can enumerate immersive windows from the desktop. disableWindowFiltering was added in Windows 8 and has no attributes.

dpiAware

Specifies whether the current process is dots per inch (dpi) aware.

Windows 10, version 1607: The dpiAware element is ignored if the dpiAwareness element is present. You can include both elements in a manifest if you want to specify a different behavior for Windows 10, version 1607 than for an earlier version of the operating system.

The following table describes the behavior that results based upon the presence of the dpiAware element and the text that it contains. The text within the element is not case-sensitive.

State of the dpiAware element Description
Absent The current process is dpi unaware by default. You can programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.
Contains «true» The current process is system dpi aware.
Contains «false» Windows Vista, Windows 7 and Windows 8: The behavior is the same as when the dpiAware is absent.
Windows 8.1 and Windows 10: The current process is dpi unaware, and you cannot programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.
Contains «true/pm» Windows Vista, Windows 7 and Windows 8: The current process is system dpi aware.
Windows 8.1 and Windows 10: The current process is per-monitor dpi aware.
Contains «per monitor» Windows Vista, Windows 7 and Windows 8: The behavior is the same as when the dpiAware is absent.
Windows 8.1 and Windows 10: The current process is per-monitor dpi aware.
Contains any other string Windows Vista, Windows 7 and Windows 8: The behavior is the same as when the dpiAware is absent.
Windows 8.1 and Windows 10: The current process is dpi unaware, and you cannot programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.

For more information about dpi awareness settings, see Comparison of DPI Awareness Levels.

dpiAware has no attributes.

dpiAwareness

Specifies whether the current process is dots per inch (dpi) aware.

The minimum version of the operating system that supports the dpiAwareness element is Windows 10, version 1607. For versions that support the dpiAwareness element, the dpiAwareness overrides the dpiAware element. You can include both elements in a manifest if you want to specify a different behavior for Windows 10, version 1607 than for an earlier version of the operating system.

The dpiAwareness element can contain a single item or a list of comma-separated items. In the latter case, the first (leftmost) item in the list recognized by the operating system is used. In this way, you can specify different behaviors supported in future Windows operating system versions.

The following table describes the behavior that results based upon the presence of the dpiAwareness element and the text that it contains in its leftmost recognized item. The text within the element is not case-sensitive.

dpiAwareness element status: Description
Element is absent The dpiAware element specifies whether the process is dpi aware.
Contains no recognized items The current process is dpi unaware by default. You can programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.
First recognized item is «system» The current process is system dpi aware.
First recognized item is «permonitor» The current process is per-monitor dpi aware.
First recognized item is «permonitorv2» The current process uses the per-monitor-v2 dpi awareness context. This item will only be recognized on Windows 10 version 1703 or later.
First recognized item is «unaware» The current process is dpi unaware. Youcannot programmatically change this setting by calling the SetProcessDpiAwareness or SetProcessDPIAware function.

For more information about dpi awareness settings supported by this element, see DPI_AWARENESS and DPI_AWARENESS_CONTEXT.

dpiAwareness has no attributes.

gdiScaling

Specifies whether GDI scaling is enabled. The minimum version of the operating system that supports the gdiScaling element is Windows 10 version 1703.

The GDI (graphics device interface) framework can apply DPI scaling to primitives and text on a per-monitor basis without updates to the application itself. This can be useful for GDI applications no longer being actively updated.

Non-vector graphics (such as bitmaps, icons, or toolbars) cannot be scaled by this element. In addition, graphics and text appearing within bitmaps dynamically constructed by applications also cannot be scaled by this element.

TRUE indicates that this element is enabled. It has no attributes.

highResolutionScrollingAware

Specifies whether high-resolution-scrolling aware is enabled. TRUE indicates that it is enabled. It has no attributes.

longPathAware

Enables long paths that exceed MAX_PATH in length. This element is supported in Windows 10, version 1607, and later. For more information, see this article.

printerDriverIsolation

Specifies whether printer driver isolation is enabled. TRUE indicates that it is enabled. It has no attributes. Printer driver isolation improves the reliability of the Windows print service by enabling printer drivers to run in processes that are separate from the process in which the print spooler runs. Support for printer driver isolation started in Windows 7 and Windows Server 2008 R2. An app can declare printer driver isolation in its app manifest to isolate itself from the printer driver and improve its reliability. That is, the app won’t crash if the printer driver has an error.

ultraHighResolutionScrollingAware

Specifies whether ultra-high-resolution-scrolling aware is enabled. TRUE indicates that it is enabled. It has no attributes.

Specifies the identity info of a sparse MSIX package for the current application. This element is supported in Windows 10, version 2004, and later versions.

The msix element must be in the namespace urn:schemas-microsoft-com:msix.v1 . It has the attributes shown in the following table.

Attribute Description
publisher Describes the publisher information. This value must match the Publisher attribute in the Identity element in your sparse package manifest.
packageName Describes the contents of the package. This value must match the Name attribute in the Identity element in your sparse package manifest.
applicationId The unique identifier of the application. This value must match the Id attribute in the Application element in your sparse package manifest.

heapType

Overrides the default heap implementation for the Win32 heap APIs to use.

  • The value SegmentHeap indicates that segment heap will be used. Segment heap is a modern heap implementation that will generally reduce your overall memory usage. This element is supported in Windows 10, version 2004 (build 19041) and later.
  • All other values are ignored.
Читайте также:  Virtualbox для windows 10 домашняя
Оцените статью