Search code examples
macosxamarinxamarin.formsxamarin.mac

How to capture key down events at application level in Xamarin.Mac


I have a Xamarin.Forms application and successfully capture application level key down events in WPF using the PreviewKeyDown event in the main window.

How do I do the same thing for Xamarin.Mac in AppDelegate or otherwise?


Solution

  • You can add an NSEvent handler in the AppDelegate's DidFinishLaunching at the local level to monitor any combination of the NSEventMask.

    public override void DidFinishLaunching(NSNotification notification)
    {
        NSEvent.AddLocalMonitorForEventsMatchingMask(NSEventMask.KeyDown, (NSEvent theEvent) =>
        {
            Console.WriteLine(theEvent);
            return theEvent;
        }); 
    
        Forms.Init();
        LoadApplication(new App());
        base.DidFinishLaunching(notification);
    }