CoreIndependentInputSource Класс

Определение

Surfaces core input API для сценариев взаимодействия.

public ref class CoreIndependentInputSource sealed : ICoreInputSourceBase, ICorePointerInputSource
public ref class CoreIndependentInputSource sealed : ICoreInputSourceBase, ICorePointerInputSource2
public ref class CoreIndependentInputSource sealed : ICoreInputSourceBase, ICorePointerInputSource2, ICorePointerRedirector
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
class CoreIndependentInputSource final : ICoreInputSourceBase, ICorePointerInputSource
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
class CoreIndependentInputSource final : ICoreInputSourceBase, ICorePointerInputSource2
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
class CoreIndependentInputSource final : ICoreInputSourceBase, ICorePointerInputSource2, ICorePointerRedirector
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
public sealed class CoreIndependentInputSource : ICoreInputSourceBase, ICorePointerInputSource
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
public sealed class CoreIndependentInputSource : ICoreInputSourceBase, ICorePointerInputSource2
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
public sealed class CoreIndependentInputSource : ICoreInputSourceBase, ICorePointerInputSource2, ICorePointerRedirector
Public NotInheritable Class CoreIndependentInputSource
Implements ICoreInputSourceBase, ICorePointerInputSource
Public NotInheritable Class CoreIndependentInputSource
Implements ICoreInputSourceBase, ICorePointerInputSource2
Public NotInheritable Class CoreIndependentInputSource
Implements ICoreInputSourceBase, ICorePointerInputSource2, ICorePointerRedirector
Наследование
Object Platform::Object IInspectable CoreIndependentInputSource
Атрибуты
Реализации

Требования к Windows

Семейство устройств
Windows 10 (появилось в 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (появилось в v1.0)

Примеры

Инициализация независимых входных данных.

// MainPage.cpp
#include "pch.h"
#include "MainPage.h"
#include <winrt/Windows.System.Threading.h>
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.UI.Xaml.Controls.h>

using namespace winrt;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;

Windows::Foundation::IAsyncAction m_inputLoopWorker;
...
    // Create a task to register for independent input and begin processing input messages.
    Windows::System::Threading::WorkItemHandler workItemHandler([this](Windows::Foundation::IAsyncAction const& /* action */)
    {
        // The CoreIndependentInputSource will raise pointer events for the specified device types on whichever thread it's created on.
        Windows::UI::Core::CoreIndependentInputSource coreInput{
            MySwapChainPanel().CreateCoreIndependentInputSource(
                Windows::UI::Core::CoreInputDeviceTypes::Mouse |
                Windows::UI::Core::CoreInputDeviceTypes::Touch |
                Windows::UI::Core::CoreInputDeviceTypes::Pen)
        };

        // Register for pointer events, which will be raised on the background thread.
        coreInput.PointerPressed({ this, &MainPage::SCP_OnPointerPressed });
        coreInput.PointerMoved({ this, &MainPage::SCP_OnPointerMoved });
        coreInput.PointerReleased({ this, &MainPage::SCP_OnPointerReleased });

        // Begin processing input messages as they're delivered.
        coreInput.Dispatcher().ProcessEvents(Windows::UI::Core::CoreProcessEventsOption::ProcessUntilQuit);
    });

    // Run task on a dedicated high priority background thread.
    m_inputLoopWorker = Windows::System::Threading::ThreadPool::RunAsync(
        workItemHandler, Windows::System::Threading::WorkItemPriority::High,
        Windows::System::Threading::WorkItemOptions::TimeSliced);
...
void MainPage::SCP_OnPointerPressed(Windows::Foundation::IInspectable const& /* sender */,
    Windows::UI::Core::PointerEventArgs const& /* args */) {}
void MainPage::SCP_OnPointerMoved(Windows::Foundation::IInspectable const& /* sender */,
    Windows::UI::Core::PointerEventArgs const& /* args */) {}
void MainPage::SCP_OnPointerReleased(Windows::Foundation::IInspectable const& /* sender */,
    Windows::UI::Core::PointerEventArgs const& /* args */) {}
// Create a task to register for independent input and begin processing input messages.
auto workItemHandler = ref new WorkItemHandler([this] (IAsyncAction ^)
{
   // The CoreIndependentInputSource will raise pointer events for the specified device types on whichever thread it's created on.
   CoreIndependentInputSource^ coreInput = CreateCoreIndependentInputSource(
      Windows::UI::Core::CoreInputDeviceTypes::Mouse |
      Windows::UI::Core::CoreInputDeviceTypes::Touch |
      Windows::UI::Core::CoreInputDeviceTypes::Pen
   );

   // Register for pointer events, which will be raised on the background thread.
   coreInput->PointerPressed += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &MyClass::OnPointerPressed);
   coreInput->PointerMoved += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &MyClass::OnPointerMoved);
   coreInput->PointerReleased += ref new TypedEventHandler<Object^, PointerEventArgs^>(this, &MyClass::OnPointerReleased);

   // Begin processing input messages as they're delivered.
   coreInput->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
});

// Run task on a dedicated high priority background thread.
m_inputLoopWorker = ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced);

Дополнительные примеры кода использования CreateCoreIndependentInputSource и CoreIndependentInputSource см DrawingPanel . в определении класса, которое является частью примера взаимодействия DirectX в XAML SwapChainPanel.

Комментарии

Создайте экземпляр этого класса, вызвав SwapChainBackgroundPanel.CreateCoreIndependentInputSource или SwapChainPanel.CreateCoreIndependentInputSource.

Класс CoreIndependentInputSource позволяет приложению обрабатывать входные данные и отрисовку независимо от потока пользовательского интерфейса XAML, так как вы намеренно предоставляете логику обработки входных данных в фоновом потоке. Необходимо вызвать CreateCoreIndependentInputSource из потока, отличного от пользовательского интерфейса, в противном случае вызов метода CreateCoreIndependentInputSource завершится ошибкой.

Журнал версий

Версия Windows Версия пакета SDK Добавленная стоимость
1803 17134 DispatcherQueue

Свойства

Dispatcher

Возвращает диспетчер событий для окна.

DispatcherQueue

Возвращает DispatcherQueue, связанный с этим CoreIndependentInputSource.

HasCapture

Возвращает значение, указывающее, есть ли в окне запись указателя.

IsInputEnabled

Возвращает или задает значение, указывающее, включен ли вход для приложения UWP.

PointerCursor

Возвращает или задает курсор указателя, используемый приложением.

PointerPosition

Возвращает клиентские координаты указателя.

Методы

ReleasePointerCapture()

Отключает запись указателя для приложения UWP.

SetPointerCapture()

Включает запись указателя для приложения UWP.

События

InputEnabled

Происходит при включении или отключении входных данных для приложения UWP.

PointerCaptureLost

Происходит при перемещении указателя в другое приложение UWP. Это событие возникает после PointerExited и является последним событием, полученным приложением для этого указателя.

PointerEntered

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

PointerExited

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

PointerMoved

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

PointerPressed

Происходит при нажатии кнопки мыши или обнаружен контакт сенсорного ввода или пера в ограничивающем прямоугольнике приложения UWP.

PointerReleased

Происходит при отпускании кнопки мыши или нажатия контакта или нажатия пера в ограничивающем прямоугольнике приложения UWP.

PointerRoutedAway

Происходит на входном объекте, получающем входные данные указателя, когда указатель перенаправляется на другой входной объект (возможно, в отдельном процессе).

PointerRoutedReleased

Происходит на всех входных объектах, когда-либо связанных с, но не получающих входные данные из указателя, который вызывает событие CoreIndependentInputSource.PointerReleased для входного объекта.

PointerRoutedTo

Происходит, когда захваченные входные данные указателя ранее доставляются другому объекту и переходят к доставке этому объекту.

PointerWheelChanged

Происходит при повороте кнопки колесика.

Применяется к

См. также раздел