H теми для windows win32

SetWindowTheme function (uxtheme.h)

Causes a window to use a different set of visual style information than its class normally uses.

Syntax

Parameters

Handle to the window whose visual style information is to be changed.

Pointer to a string that contains the application name to use in place of the calling application’s name. If this parameter is NULL, the calling application’s name is used.

Pointer to a string that contains a semicolon-separated list of CLSID names to use in place of the actual list passed by the window’s class. If this parameter is NULL, the ID list from the calling class is used.

Return value

If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Remarks

The theme manager retains the pszSubAppName and the pszSubIdList associations through the lifetime of the window, even if visual styles subsequently change. The window is sent a WM_THEMECHANGED message at the end of a SetWindowTheme call, so that the new visual style can be found and applied.

When pszSubAppName and pszSubIdList are NULL, the theme manager removes the previously applied associations. You can prevent visual styles from being applied to a specified window by specifying an empty string, (L» «), which does not match any section entries.

Examples

The following example code gives a list-view control the appearance of a Windows Explorer list:

Использование визуального уровня на платформе Win32 Using the Visual Layer with Win32

Вы можете использовать интерфейсы API Composition среды выполнения Windows (также называемые визуальным уровнем) в приложениях Win32, чтобы создавать современные интерфейсы для пользователей Windows 10. You can use Windows Runtime Composition APIs (also called the Visual layer) in your Win32 apps to create modern experiences that light up for Windows 10 users.

Полный код для этого руководства доступен на сайте GitHub: Пример приложения Win32 HelloComposition. The complete code for this tutorial is available on GitHub: Win32 HelloComposition sample.

Приложения универсальной платформы Windows, которым необходим точный контроль над композицией пользовательского интерфейса, имеют доступ к пространству имен Windows.UI.Composition, которое позволяет точно контролировать композицию и отрисовку пользовательского интерфейса. Universal Windows Applications that need precise control over their UI composition have access to the Windows.UI.Composition namespace to exert fine grained control over how their UI is composed and rendered. Однако этот API Composition не ограничивается только приложениями UWP. This composition API is not limited to UWP apps, however. Классические приложения Win32 могут использовать современные системы композиции в UWP и Windows 10. Win32 desktop applications can take advantage of the modern composition systems in UWP and Windows 10.

Предварительные условия Prerequisites

Для использования API размещения для UWP накладываются приведенные ниже предварительные требования. The UWP hosting API has these prerequisites.

  • Предполагается, что у вас есть опыт разработки приложений с помощью Win32 и UWP. We assume that you have some familiarity with app development using Win32 and UWP. См. также: For more info, see:
    • Get Started with Win32 and C++ (Приступая к работе с Win32 и C++) Get Started with Win32 and C++
    • Приступая к работе с приложениями для Windows 10 Get started with Windows 10 apps
    • Улучшение классического приложения для Windows 10 Enhance your desktop application for Windows 10
  • Windows 10 версии 1803 или более поздней версии. Windows 10 version 1803 or later
  • Пакет SDK для Windows 10 версии 17134 или более поздней версии. Windows 10 SDK 17134 or later
Читайте также:  Run windows update with powershell

Как использовать интерфейсы API Composition из классического приложения Win32 How to use Composition APIs from a Win32 desktop application

При работе с этим руководством вы создадите простое приложение Win32 на C++ и добавите в него элементы композиции UWP. In this tutorial, you create a simple Win32 C++ app and add UWP Composition elements to it. Основное внимание уделяется правильной настройке проекта, созданию кода взаимодействия и отрисовке простых элементов с помощью интерфейсов API Windows Composition. The focus is on correctly configuring the project, creating the interop code, and drawing something simple using Windows Composition APIs. Завершенное приложение выглядит следующим образом. The finished app looks like this.

Создание проекта C++ для Win32 в Visual Studio Create a C++ Win32 project in Visual Studio

Первым шагом является создание проекта приложения Win32 в Visual Studio. The first step is to create the Win32 app project in Visual Studio.

Чтобы создать проект приложения Win32 на C++ с именем HelloComposition, сделайте следующее. To create a new Win32 Application project in C++ named HelloComposition:

Откройте Visual Studio и выберите Файл > Создать > Проект. Open Visual Studio and select File > New > Project.

Появится диалоговое окно Создать проект. The New Project dialog opens.

В категории Установлены разверните узел Visual C++ , а затем выберите Windows Desktop. Under the Installed category, expand the Visual C++ node, and then select Windows Desktop.

Выберите шаблон Классическое приложение Windows. Select the Windows Desktop Application template.

Введите имя HelloComposition, а затем нажмите кнопку ОК. Enter the name HelloComposition, then click OK.

Visual Studio создаст проект и откроет редактор для основного файла приложения. Visual Studio creates the project and opens the editor for the main app file.

Настройка проекта для использования интерфейсов API среды выполнения Windows Configure the project to use Windows Runtime APIs

Чтобы применить интерфейсы API среды выполнения Windows (WinRT) в приложении Win32, мы используем C++/WinRT. To use Windows Runtime (WinRT) APIs in your Win32 app, we use C++/WinRT. Чтобы добавить поддержку C++/WinRT, необходимо настроить проект Visual Studio. You need to configure your Visual Studio project to add C++/WinRT support.

В меню Проект откройте свойства проекта (Свойства HelloComposition) и убедитесь, что для следующих параметров заданы указанные значения. From the Project menu, open the project properties (HelloComposition Properties) and ensure the following settings are set to the specified values:

  • Для параметра Конфигурации выберите Все конфигурации. For Configuration, select All Configurations. Для параметра Платформа выберите Все платформы. For Platform, select All Platforms.
  • Свойства конфигурации >Общие >Версия Windows SDK = 10.0.17763.0 или более поздняя версия. Configuration Properties >General >Windows SDK Version = 10.0.17763.0 or greater

  • C/C++ >Язык >Стандарт языка C++ = Стандарт ISO C++ 17 (/stf:c++17)C/C++ >Language >C++ Language Standard = ISO C++ 17 Standard (/stf:c++17)

  • Компоновщик >Ввод >Дополнительные зависимости — этот раздел должен содержать windowsapp.lib. Linker >Input >Additional Dependencies must include «windowsapp.lib«. Если эта зависимость отсутствует в списке, добавьте ее. If it’s not included in the list, add it.

Изменение предварительно скомпилированного заголовка Update the precompiled header

Переименуйте stdafx.h и stdafx.cpp в pch.h и pch.cpp соответственно. Rename stdafx.h and stdafx.cpp to pch.h and pch.cpp , respectively.

Установите для свойства проекта C/C++ > Предварительно скомпилированные заголовки > Предварительно скомпилированный заголовочный файл значение pch.h. Set project property C/C++ > Precompiled Headers > Precompiled Header File to pch.h.

Найдите #include «stdafx.h» и замените его #include «pch.h» во всех файлах. Find and replace #include «stdafx.h» with #include «pch.h» in all files.

(Изменить > Найти и заменить > Найти в файлах.) (Edit > Find and Replace > Find in Files)

В pch.h добавьте winrt/base.h и unknwn.h . In pch.h , include winrt/base.h and unknwn.h .

На этом этапе рекомендуется выполнить сборку проекта, чтобы убедиться в отсутствии ошибок, прежде чем продолжить. It’s a good idea to build the project at this point to make sure there are no errors before going on.

Создание класса для размещения элементов композиции Create a class to host composition elements

Чтобы разместить содержимое, созданное с помощью визуального уровня, создайте класс (CompositionHost) для управления взаимодействием и создания элементов композиции. To host content you create with the visual layer, create a class (CompositionHost) to manage interop and create composition elements. Это потребует выполнить большую часть настройки для размещения интерфейсов API Composition. Потребуется: This is where you do most of the configuration for hosting Composition APIs, including:

  • получить Compositor, который создает объекты и управляет ими в пространстве имен Windows.UI.Composition; getting a Compositor, which creates and manages objects in the Windows.UI.Composition namespace.
  • создать DispatcherQueueController/DispatcherQueue для управления задачами интерфейсов API WinRT; creating a DispatcherQueueController/DispatcherQueue to manage tasks for the WinRT APIs.
  • создать DesktopWindowTarget и контейнера Composition для отображения объектов композиции. creating a DesktopWindowTarget and Composition container to display the composition objects.
Читайте также:  При обновлении windows 10 код ошибки 0x8007025d

Мы сделаем этот класс singleton, чтобы избежать проблем с потоками. We make this class a singleton to avoid threading issues. Например, можно создать только одну очередь диспетчера для каждого потока, поэтому создание второго экземпляра CompositionHost в том же потоке вызовет ошибку. For example, you can only create one dispatcher queue per thread, so instantiating a second instance of CompositionHost on the same thread would cause an error.

При необходимости сверьтесь с полным кодом в конце руководства, чтобы убедиться в том, что весь код добавлен в соответствующе места при работе с этим руководством. If you need to, check the complete code at the end of the tutorial to make sure all the code is in the right places as you work through the tutorial.

Добавьте новый файл класса в проект. Add a new class file to your project.

  • В обозревателе решений щелкните проект HelloComposition правой кнопкой мыши. In Solution Explorer, right click the HelloComposition project.
  • В контекстном меню выберите Добавить >Класс. In the context menu, select Add >Class. .
  • В диалоговом окне Добавление класса укажите имя класса, CompositionHost.cs, а затем щелкните Добавить. In the Add Class dialog, name the class CompositionHost.cs, then click Add.

Добавьте заголовки и операторы using, необходимые для взаимодействия композиции. Include headers and usings required for composition interop.

  • В начало файла CompositionHost.h добавьте приведенные ниже операторы include. In CompositionHost.h, add these includes at the top of the file.
  • В начале файла CompositionHost.cpp после каждого оператора include добавьте оператор using. In CompositionHost.cpp, add these usings at the top of the file, after any includes.

Измените класс, чтобы использовать шаблон singleton. Edit the class to use the singleton pattern.

  • В CompositionHost.h сделайте конструктор частным. In CompositionHost.h, make the constructor private.
  • Объявите общедоступный статический метод GetInstance. Declare a public static GetInstance method.
  • В CompositionHost.cpp добавьте определение метода GetInstance. In CompositionHost.cpp, add the definition of the GetInstance method.

В CompositionHost.h объявите частные переменные-члены DispatcherQueueController и DesktopWindowTarget для Compositor. In CompositionHost.h, declare private member variables for the Compositor, DispatcherQueueController, and DesktopWindowTarget.

Добавьте общедоступный метод для инициализации объектов взаимодействия композиции. Add a public method to initialize the composition interop objects.

В методе Initialize вызываются методы EnsureDispatcherQueue, CreateDesktopWindowTarget и CreateCompositionRoot. In Initialize, you call the EnsureDispatcherQueue, CreateDesktopWindowTarget, and CreateCompositionRoot methods. Эти методы создаются на следующих шагах. You create these methods in the next steps.

  • В CompositionHost.h объявите общедоступный метод Initialize, который принимает HWND в качестве аргумента. In CompositionHost.h, declare a public method named Initialize that takes an HWND as an argument.
  • В CompositionHost.cpp добавьте определение метода Initialize. In CompositionHost.cpp, add the definition of the Initialize method.
  • Создайте очередь диспетчера в потоке, который будет использовать Windows Composition. Create a dispatcher queue on the thread that will be using Windows Composition.

    Необходимо создать Compositor в потоке с очередью диспетчера, поэтому этот метод вызывается первым во время инициализации. A Compositor must be created on a thread that has a dispatcher queue, so this method is called first during initialization.

    • В CompositionHost.h объявите частный метод EnsureDispatcherQueue. In CompositionHost.h, declare a private method named EnsureDispatcherQueue.
    • В CompositionHost.cpp добавьте определение метода EnsureDispatcherQueue. In CompositionHost.cpp, add the definition of the EnsureDispatcherQueue method.

    Зарегистрируйте окно приложения в качестве цели композиции. Register your app’s window as a composition target.

    • В CompositionHost.h объявите частный метод CreateDesktopWindowTarget, который принимает HWND в качестве аргумента. In CompositionHost.h, declare a private method named CreateDesktopWindowTarget that takes an HWND as an argument.
    • В CompositionHost.cpp добавьте определение метода CreateDesktopWindowTarget. In CompositionHost.cpp, add the definition of the CreateDesktopWindowTarget method.
    Читайте также:  Предварительный просмотр накопительного обновления для windows 10 version 20h2 kb4598291

    Создайте корневой контейнер для размещения визуальных объектов. Create a root visual container to hold visual objects.

    • В CompositionHost.h объявите частный метод CreateCompositionRoot. In CompositionHost.h, declare a private method named CreateCompositionRoot.
    • В CompositionHost.cpp добавьте определение метода CreateCompositionRoot. In CompositionHost.cpp, add the definition of the CreateCompositionRoot method.
  • Выполните сборку проекта, чтобы убедиться в отсутствии ошибок. Build the project now to make sure there are no errors.

    Эти методы настраивают компоненты, необходимые для взаимодействия между визуальным уровнем UWP и интерфейсами API Win32. These methods set up the components needed for interop between the UWP visual layer and Win32 APIs. Теперь вы можете добавить содержимое в приложение. Now you can add content to your app.

    Добавление элементов композиции Add composition elements

    Теперь, когда инфраструктура настроена, можно создать содержимое Composition, которое необходимо отобразить. With the infrastructure in place, you can now generate the Composition content you want to show.

    В этом примере вы добавите код, создающий квадрат SpriteVisual произвольного цвета с анимацией, которая удаляет его после небольшой задержки. For this example, you add code that creates a randomly-colored square SpriteVisual with an animation that causes it to drop after a short delay.

    Добавьте элемент композиции. Add a composition element.

    • В CompositionHost.h объявите общедоступный метод AddElement, который принимает 3 значения с плавающей запятой в качестве аргументов. In CompositionHost.h, declare a public method named AddElement that takes 3 float values as arguments.
    • В CompositionHost.cpp добавьте определение метода AddElement. In CompositionHost.cpp, add the definition of the AddElement method.

    Создание и отображение окна Create and show the window

    Теперь можно добавить кнопку и содержимое композиции UWP в пользовательский интерфейс Win32. Now, you can add a button and the UWP composition content to your Win32 UI.

    В начало файла HelloComposition.cpp добавьте CompositionHost.h, определите BTN_ADD и получите экземпляр CompositionHost. In HelloComposition.cpp, at the top of the file, include CompositionHost.h, define BTN_ADD, and get an instance of CompositionHost.

    В методе InitInstance измените размер создаваемого окна. In the InitInstance method, change the size of the window that’s created. (В этой строке измените CW_USEDEFAULT, 0 на 900, 672 .) (In this line, change CW_USEDEFAULT, 0 to 900, 672 .)

    В функции WndProc добавьте case WM_CREATE в блок параметров message. In the WndProc function, add case WM_CREATE to the message switch block. В этом случае инициализируется CompositionHost и создается кнопка. In this case, you initialize the CompositionHost and create the button.

    Кроме того, в функции WndProc обработайте нажатие кнопки, чтобы добавить элемент композиции в пользовательский интерфейс. Also in the WndProc function, handle the button click to add a composition element to the UI.

    Добавьте case BTN_ADD в блок параметров wmId в блоке WM_COMMAND. Add case BTN_ADD to the wmId switch block inside the WM_COMMAND block.

    Теперь можно выполнить сборку приложения и запустить его. You can now build and run your app. При необходимости сверьтесь с полным кодом в конце руководства, чтобы убедиться в том, что весь код добавлен в соответствующе места. If you need to, check the complete code at the end of the tutorial to make sure all the code is in the right places.

    Если запустить приложение и нажать кнопку, в пользовательском интерфейсе должны отобразиться анимированные квадраты. When you run the app and click the button, you should see animated squares added to the UI.

    Дополнительные ресурсы Additional resources

    • Пример приложения Win32 HelloComposition (GitHub) Win32 HelloComposition sample (GitHub)
    • Get Started with Win32 and C++ (Приступая к работе с Win32 и C++) Get Started with Win32 and C++
    • Приступая к работе с приложениями для Windows 10 (UWP) Get started with Windows 10 apps (UWP)
    • Улучшение классического приложения для Windows 10 (UWP) Enhance your desktop application for Windows 10 (UWP)
    • Пространство имен Windows.UI.Composition (UWP) Windows.UI.Composition namespace (UWP)

    Полный код Complete code

    Ниже приведен полный код класса CompositionHost и метода InitInstance. Here’s the complete code for the CompositionHost class and the InitInstance method.

    Оцените статью