继续扩展Input类 (https://www.cnblogs.com/dalgleish/p/18992754),增加IPointer私有变量,用作Capture功能的实现。

        private static IPointer? pointer;

        private static void OnRawEvent(RawInputEventArgs e)
        {
            switch (e)
            {
                case RawKeyEventArgs keyEvent:
                    HandleKeyEvent(keyEvent);
                    break;
                    
                case RawTextInputEventArgs textInputEvent:
                    HandleTextInputEvent(textInputEvent);
                    break;

                case RawPointerEventArgs rawPointerEvent:
                    HandlePointerEvent(rawPointerEvent);
                    break;
            }
        }

        private static void HandlePointerEvent(RawPointerEventArgs e)
        {
            if (pointer == null)
                pointer = e.GetPropertyValue<IInputDevice>("Device")?.GetFieldValue<IPointer>("_pointer");
        }
        public static void Capture(IInputElement inputElement)
        {
            pointer?.Capture(inputElement);
        }

MousePosition.axaml代码

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Height="300" Width="300"
        x:Class="AvaloniaUI.MousePosition"
        Title="MousePosition">
    <Grid Margin="5" RowDefinitions="*,auto,auto">
        <Rectangle Name="rect" PointerMoved="MouseMoved" Fill="LightBlue" ></Rectangle>
        <Button Grid.Row="1" Name="cmdCapture" Click="cmdCapture_Click">Capture the Mouse</Button>
        <TextBlock Name="lblInfo" Grid.Row="2"></TextBlock>
    </Grid>
</Window>

MousePosition.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Shares.Avalonia;
using System;
using System.Threading.Tasks;

namespace AvaloniaUI;

public partial class MousePosition : Window
{
    public MousePosition()
    {
        InitializeComponent();
        this.AddHandler(PointerCaptureLostEvent, LostCapture);
        this.LostFocus += LostCapture;
        Input.Route = RoutingStrategies.Tunnel;
    }
    private async void cmdCapture_Click(object? sender, RoutedEventArgs e)
    {
        await Task.Delay(20);
        Input.Capture(rect);
        cmdCapture.Content = "[ Mouse is now captured ... ]";
    }
    private void MouseMoved(object? sender, PointerEventArgs e)
    {
        Point pt = e.GetPosition(this);
        lblInfo.Text = $"You are at ({pt.X},{pt.Y}) in window coordinates";
    }
    private void LostCapture(object? sender, RoutedEventArgs e)
    {
        cmdCapture.Content = "[ Mouse lost capture ... ]";
    }
}

运行效果 (此时是屏蔽所有其他输入的,比如窗口的放大,缩小,和关闭)

 

posted on 2025-07-20 13:04  dalgleish  阅读(20)  评论(0)    收藏  举报