- Манифест приложения на ассемблере
- Использование тем оформления
- Алгоритм настройки манифеста приложения
- Загрузка общих элементов управления
- Enabling Visual Styles
- Using Manifests or Directives to Ensure That Visual Styles Can Be Applied to Applications
- When Visual Styles are not Applied
- Making Your Application Compatible with Earlier Versions of Windows
- Application Manifests
- File Location
- File Name Syntax
- Elements
- assembly
- noInherit
- assemblyIdentity
- compatibility
- application
- supportedOS
- maxversiontested
- dependency
- dependentAssembly
- activeCodePage
- autoElevate
- disableTheming
- disableWindowFiltering
- dpiAware
- dpiAwareness
- gdiScaling
- highResolutionScrollingAware
- longPathAware
- printerDriverIsolation
- ultraHighResolutionScrollingAware
- heapType
Манифест приложения на ассемблере
Когда я, в процессе своего обучения, подошел к написанию приложений, активно использующих различные графические элементы управления, раз за разом начал обращать внимание на одну интересную проблему. Дело в том, что при запуске двоичного исполняемого файла, все элементы, находящиеся в окне, выглядели «плоско», то есть имели упрощенный стиль, а-ля 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 AppliedTo 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 WindowsMuch 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 ManifestsAn 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.
File LocationApplication manifests should be included as a resource in the application’s EXE file or DLL. File Name SyntaxThe 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 ElementsNames of elements and attributes are case-sensitive. The values of elements and attributes are case-insensitive, except for the value of the type attribute. assemblyA 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.
noInheritInclude 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. assemblyIdentityAs 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.
compatibilityContains at least one application. It has no attributes. Optional. Application manifests without a compatibility element default to Windows Vista compatibility on Windows 7. applicationContains at least one supportedOS element. Starting in Windows 10, version 1903, it can also contain one optional maxversiontested element. It has no attributes. Optional. supportedOSThe supportedOS element has the following attribute. It has no subelements.
maxversiontestedThe 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.
dependencyContains at least one dependentAssembly. It has no attributes. Optional. dependentAssemblyThe 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.
activeCodePageForce 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. autoElevateSpecifies whether auto elevate is enabled. TRUE indicates that it is enabled. It has no attributes. disableThemingSpecifies whether giving UI elements a theme is disabled. TRUE indicates disabled. It has no attributes. disableWindowFilteringSpecifies 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. dpiAwareSpecifies 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.
For more information about dpi awareness settings, see Comparison of DPI Awareness Levels. dpiAware has no attributes. dpiAwarenessSpecifies 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.
For more information about dpi awareness settings supported by this element, see DPI_AWARENESS and DPI_AWARENESS_CONTEXT. dpiAwareness has no attributes. gdiScalingSpecifies 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. highResolutionScrollingAwareSpecifies whether high-resolution-scrolling aware is enabled. TRUE indicates that it is enabled. It has no attributes. longPathAwareEnables 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. printerDriverIsolationSpecifies 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. ultraHighResolutionScrollingAwareSpecifies 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.
heapTypeOverrides the default heap implementation for the Win32 heap APIs to use.
|