Search code examples
c#.net-coreavaloniauiavalonia

AvaloniaUI: Capture mouse button up/down globally


Is there a possibility in AvaloniaUI, to globally capture mouse press button up/down? To be notified about this events outside of any controls (or possibly outside of any particular view model)?


Solution

  • You can listen for these Events in the Code-Behind of your MainWindow and also handle Events that have already been handled by other Controls with handledEventsToo: true like this:

    public class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
    
            this.AddHandler(PointerPressedEvent, MouseDownHandler, handledEventsToo: true);
            this.AddHandler(PointerReleasedEvent, MouseUpHandler, handledEventsToo: true);
    
            #if DEBUG
            this.AttachDevTools();
            #endif
        }
    
        private void MouseUpHandler(object sender, PointerReleasedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Mouse released.");
        }
    
        private void MouseDownHandler(object sender, PointerPressedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Mouse pressed.");
        }
    
        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
    

    Note that this (probably) won't work globally if you have multiple windows.