Windows.UI.Input.Preview.Injection Пространство имен

Обеспечивает поддержку программного создания и автоматизации ввода с различных устройств, таких как клавиатура, мышь, сенсорный ввод, перо и геймпад.

Важно!

Для API в этом пространстве имен требуется ограниченная возможность inputInjectionBrokered.

Классы

InjectedInputGamepadInfo

Представляет создаваемые программными средствами входные данные геймпада.

InjectedInputKeyboardInfo

Представляет программный ввод с клавиатуры, например tab или SHIFT+TAB (обратное табуляция).

InjectedInputMouseInfo

Представляет ввод с помощью мыши, созданный программным способом.

InjectedInputPenInfo

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

InjectedInputTouchInfo

Представляет создаваемый программным способом сенсорный ввод.

InputInjector

Представляет виртуальное устройство ввода для отправки входных данных.

Структуры

InjectedInputPoint

Содержит экранные координаты указателя в аппаратно-независимом пикселе (DIP).

InjectedInputPointerInfo

Содержит основные сведения о указателе, общие для всех типов указателей.

InjectedInputRectangle

Смещения от внедренного указателя для ограничивающего прямоугольника, представляющего контактную область касания.

Перечисления

InjectedInputButtonChangeKind

Указывает изменения в состоянии кнопки, связанной с указателем.

InjectedInputKeyOptions

Задает различные параметры или модификаторы, используемые для имитации ввода с физической или виртуальной клавиатуры с помощью InjectedInputKeyboardInfo.

InjectedInputMouseOptions

Задает различные параметры или модификаторы, используемые для имитации ввода с помощью функции InjectedInputMouseInfo.

InjectedInputPenButtons

Задает параметры пера, используемые для имитации ввода пером с помощью Метода InjectedInputPenInfo.

InjectedInputPenParameters

Указывает состояния пера, используемые для имитации ввода пера с помощью Метода InjectedInputPenInfo.

InjectedInputPointerOptions

Указывает различные параметры или модификаторы, используемые для имитации входных данных указателя через InjectedInputMouseInfo, InjectedInputPenInfo и InjectedInputTouchInfo.

InjectedInputShortcut

Указывает системные ярлыки для InjectShortcut.

InjectedInputTouchParameters

Указывает состояния касания, используемые для имитации сенсорного ввода с помощью Метода InjectedInputTouchInfo.

InjectedInputVisualizationMode

Указывает тип визуальной обратной связи, отображаемой для внедренного типа входных данных.

Примеры

Ниже приведен пример функции внедрения сенсорного ввода.

Сначала мы вызываем функцию TryCreate для создания экземпляра объекта InputInjector.

Затем мы вызываем InitializeTouchInjection, где для InjectedInputVisualizationMode указано значение Default.

После определения точки внедрение мы вызываем функцию InjectedInputTouchInfo, чтобы инициализировать список точек касания для внедрения (в этом примере мы создаем одну точку касания, соответствующую указателю мыши).

Наконец, мы два раза вызываем InjectTouchInput: первый для перемещения указателя вниз и второй для перемещения указателя вверх.

/// <summary>
/// Inject touch input on injection target corresponding 
/// to mouse click on input target.
/// </summary>
/// <param name="pointerPoint">The mouse click pointer.</param>
private void InjectTouchForMouse(PointerPoint pointerPoint)
{
    // Create the touch injection object.
    _inputInjector = InputInjector.TryCreate();

    if (_inputInjector != null)
    {
        _inputInjector.InitializeTouchInjection(
            InjectedInputVisualizationMode.Default);

        // Create a unique pointer ID for the injected touch pointer.
        // Multiple input pointers would require more robust handling.
        uint pointerId = pointerPoint.PointerId + 1;

        // Get the bounding rectangle of the app window.
        Rect appBounds =
            Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().VisibleBounds;

        // Get the top left screen coordinates of the app window rect.
        Point appBoundsTopLeft = new Point(appBounds.Left, appBounds.Top);

        // Get a reference to the input injection area.
        GeneralTransform injectArea =
            ContainerInject.TransformToVisual(Window.Current.Content);

        // Get the top left screen coordinates of the input injection area.
        Point injectAreaTopLeft = injectArea.TransformPoint(new Point(0, 0));

        // Get the screen coordinates (relative to the input area) 
        // of the input pointer.
        int pointerPointX = (int)pointerPoint.Position.X;
        int pointerPointY = (int)pointerPoint.Position.Y;

        // Create the point for input injection and calculate its screen location.
        Point injectionPoint =
            new Point(
                appBoundsTopLeft.X + injectAreaTopLeft.X + pointerPointX,
                appBoundsTopLeft.Y + injectAreaTopLeft.Y + pointerPointY);

        // Create a touch data point for pointer down.
        // Each element in the touch data list represents a single touch contact. 
        // For this example, we're mirroring a single mouse pointer.
        List<InjectedInputTouchInfo> touchData =
            new List<InjectedInputTouchInfo>
            {
                new InjectedInputTouchInfo
                {
                    Contact = new InjectedInputRectangle
                    {
                        Left = 30, Top = 30, Bottom = 30, Right = 30
                    },
                    PointerInfo = new InjectedInputPointerInfo
                    {
                        PointerId = pointerId,
                        PointerOptions =
                        InjectedInputPointerOptions.PointerDown |
                        InjectedInputPointerOptions.InContact |
                        InjectedInputPointerOptions.New,
                        TimeOffsetInMilliseconds = 0,
                        PixelLocation = new InjectedInputPoint
                        {
                            PositionX = (int)injectionPoint.X ,
                            PositionY = (int)injectionPoint.Y
                        }
                },
                Pressure = 1.0,
                TouchParameters =
                    InjectedInputTouchParameters.Pressure |
                    InjectedInputTouchParameters.Contact
            }
        };

        // Inject the touch input. 
        _inputInjector.InjectTouchInput(touchData);

        // Create a touch data point for pointer up.
        touchData = new List<InjectedInputTouchInfo>
        {
            new InjectedInputTouchInfo
            {
                PointerInfo = new InjectedInputPointerInfo
                {
                    PointerId = pointerId,
                    PointerOptions = InjectedInputPointerOptions.PointerUp
                }
            }
        };

        // Inject the touch input. 
        _inputInjector.InjectTouchInput(touchData);
    }
}

Ниже приведены некоторые скачиваемые примеры, демонстрирующие базовые входные данные и внедрение входных данных:

Комментарии

При использовании внедрения входных данных необходимо добавить в Package.appxmanifest следующее:

  • Кому <Package>
    • xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    • IgnorableNamespaces="rescap"
  • Кому <Capabilities>
    • <rescap:Capability Name="inputInjectionBrokered" />

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