Name microsoft windows common controls

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

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

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

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

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

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

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

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

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

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

Разбираемся с манифестами в C#

Приветствую всех, сегодня я хотел поговорить о манифестах, и как их можно использовать.

Сборка имеет несколько видом информации, и мы их все расмотроим:
Первый вид это манифест сборки-он позволяет среды .NET предостовлять сведения, это имя,версия, разрешения и ссылки.

Воторой вид- это манифест приложения-который предоставляет сведение для OS, в него входит варианты развертывания сборки, а так же запрос полномочий до администратора.

Третий вид это скомпилированные типы, это метаданные и код, которые определены внутри сборки.

Четвертый вид это ресурсы-это все материалы которые вошли в сборку, это изображения, локальный текст итд.

Читайте также:  Iso mount linux program

В середине 90 при написании приложения, программы могли подменять системные библиотеки, тем самым заменять их старыми версиями, и новые программы отказывались работать. Это привело к тому что в 2000 придумали использовать манифест который шел внутри самого приложения. В нем находилось описание какая версия операционной системы требуется для работы, библиотеки, версия программы. Всю эту информацию мы могли увидеть если бы выбрали исполняемый фаил и нажали на его свойство. Так называемый манифест сборки.

А изменить все это мы могли в Свойствах проекта>Приложение>Сведения о сборке:

Все поля мы можем заполнить с нашими предпочтениями, сохранить и у нас обновиться манифест сборки, который храниться в файле AssemblyInfo.cs:

Однако это не решало не которых проблем и было придуманы манифесты приложения который сейчас просто незаменим при использовании приложений работающий с реестром и системным диском. А все дело в том что этот манифест использует Xml формат и в нем содержится информация о том как можно запустить приложение. И оптимизировать работу приложения под конкретную версию Windows вообще то в нем уже содержатся комментарии которые, достаточно раскомментировать и пересобрать свой проект с новыми возможностями.

Common Control Versions

This topic lists the available versions of the Common Control library (ComCtl32.dll), describes how to identify the version that your application is using, and explains how to target your application for a specific version.

This topic contains the following sections.

Common Control DLL Versions Numbers

Support for common controls is provided by ComCtl32.dll, which all 32-bit and 64-bit versions of Windows include. Each successive version of the DLL supports the features and API of earlier versions and adds new features.

Because various versions of ComCtl32.dll were distributed with Internet Explorer, the version that is active is sometimes different from the version that was shipped with the operating system. Therefore, your application must directly determine which version of ComCtl32.dll is present.

In the common controls reference documentation, many programming elements specify a minimum supported DLL version number. This version number indicates that the programming element is implemented in that version and subsequent versions of the DLL unless otherwise specified. If no version number is specified, the programming element is implemented in all existing versions of the DLL.

The following table outlines the different DLL versions and how they were distributed on supported OSes.

Microsoft Internet ExplorerВ 5.01, Microsoft Internet ExplorerВ 5.5, and Microsoft Internet ExplorerВ 6

Windows ServerВ 2003, WindowsВ Vista, Windows ServerВ 2008, and WindowsВ 7

Windows ServerВ 2003

WindowsВ Vista, Windows ServerВ 2008, and WindowsВ 7

Structure Sizes for Different Common Control Versions

Ongoing enhancements to common controls have resulted in the need to extend many of the structures. For this reason, the size of the structures has changed between different versions of Commctrl.h. Because most of the common control structures take a structure size as one of the parameters, a message or function can fail if the size is not recognized. To remedy this, structure size constants have been defined to aid in targeting different version of ComCtl32.dll. The following list defines the structure size constants.

HDITEM_V1_SIZE The size of the HDITEM structure in version 4.0.
IMAGELISTDRAWPARAMS_V3_SIZE The size of the IMAGELISTDRAWPARAMS structure in version 5.9.
LVCOLUMN_V1_SIZE The size of the LVCOLUMN structure in version 4.0.
LVGROUP_V5_SIZE The size of the LVGROUP structure in version 6.0.
LVHITTESTINFO_V1_SIZE The size of the LVHITTESTINFO structure in version 4.0.
LVITEM_V1_SIZE The size of the LVITEM structure in version 4.0.
LVITEM_V5_SIZE The size of the LVITEM structure in version 6.0.
LVTILEINFO_V5_SIZE The size of the LVTILEINFO structure in version 6.0.
MCHITTESTINFO_V1_SIZE The size of the MCHITTESTINFO structure in version 4.0.
NMLVCUSTOMDRAW_V3_SIZE The size of the NMLVCUSTOMDRAW structure in version 4.7.
NMTTDISPINFO_V1_SIZE The size of the NMTTDISPINFO structure in version 4.0.
NMTVCUSTOMDRAW_V3_SIZE The size of the NMTVCUSTOMDRAW structure in version 4.7.
PROPSHEETHEADER_V1_SIZE The size of the PROPSHEETHEADER structure in version 4.0.
PROPSHEETPAGE_V1_SIZE The size of the PROPSHEETPAGE structure in version 4.0.
REBARBANDINFO_V3_SIZE The size of the REBARBANDINFO structure in version 4.7.
REBARBANDINFO_V6_SIZE The size of the REBARBANDINFO structure in version 6.0.
TTTOOLINFO_V1_SIZE The size of the TOOLINFO structure in version 4.0.
TTTOOLINFO_V2_SIZE The size of the TOOLINFO structure in version 4.7.
TTTOOLINFO_V3_SIZE The size of the TOOLINFO structure in version 6.0.
TVINSERTSTRUCT_V1_SIZE The size of the TVINSERTSTRUCT structure in version 4.0.
Читайте также:  Windows phone nokia lumina

Using DllGetVersion to Determine the Version Number

The DllGetVersion function can be called by an application to determine which DLL version is present on the system.

DllGetVersion returns a DLLVERSIONINFO2 structure. In addition to the information provided through DLLVERSIONINFO, DLLVERSIONINFO2 also provides the hotfix number that identifies the latest installed service pack, which provides a more robust way to compare version numbers. Because the first member of DLLVERSIONINFO2 is a DLLVERSIONINFO structure, the later structure is backward-compatible.

The following sample function GetVersion loads a specified DLL and attempts to call its DllGetVersion function. If successful, it uses a macro to pack the major and minor version numbers from the DLLVERSIONINFO structure into a DWORD that is returned to the calling application. If the DLL does not export DllGetVersion, the function returns zero. You can modify the function to handle the possibility that DllGetVersion returns a DLLVERSIONINFO2 structure. If so, use the information in that DLLVERSIONINFO2 structure’s ullVersion member to compare versions, build numbers, and service pack releases. The MAKEDLLVERULL macro simplifies the task of comparing these values to those in ullVersion.

Using LoadLibrary incorrectly can pose security risks. Refer to the LoadLibrary documentation for information on how to correctly load DLLs with different versions of Windows.

The following code example shows how you can use GetVersion to test whether ComCtl32.dll is version 6.0 or later.

Project Versions

To ensure that your application is compatible with different targeted versions of a .dll file, version macros are present in the header files. These macros are used to define, exclude, or redefine certain definitions for different versions of the DLL. See Using the Windows Headers for an in-depth description of these macros.

For example, the macro name _WIN32_IE is commonly found in older headers. You are responsible for defining the macro as a hexadecimal number. This version number defines the target version of the application that is using the DLL. The following table shows the available version numbers and the effect each has on your application.

Version Description
0x0300 The application is compatible with ComCtl32.dll version 4.70 and later. The application cannot implement features that were added after version 4.70.
0x0400 The application is compatible with ComCtl32.dll version 4.71 and later. The application cannot implement features that were added after version 4.71.
0x0401 The application is compatible with ComCtl32.dll version 4.72 and later. The application cannot implement features that were added after version 4.72.
0x0500 The application is compatible with ComCtl32.dll version 5.80 and later. The application cannot implement features that were added after version 5.80.
0x0501 The application is compatible with ComCtl32.dll version 5.81 and later. The application cannot implement features that were added after version 5.81.
0x0600 The application is compatible with ComCtl32.dll version 6.0 and later. The application cannot implement features that were added after version 6.0.

If you do not define the _WIN32_IE macro in your project, it is automatically defined as 0x0500. To define a different value, you can add the following to the compiler directives in your make file; substitute the desired version number for 0x0400.

Another method is to add a line similar to the following in your source code before you include the Shell header files. Substitute the desired version number for 0x0400.

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:

Читайте также:  Утилиты для мониторинга сети linux
Оцените статью