How to track the key press events of keyboard using SwiftUI for MacOS?

I am unable to get the keyboard keys events in the background or Inactive state of the mac application. I am trying to get the global event using

NSEvent.addGlobalMonitorForEvent(matching: [.keyDown], handler: {

    event in print("key pressed : \(event.keyCode)")

    return event
})

This is working for mouse tracking but unable to track the events for keyboard...;(

Please help me to track the event for the keyboard events in active/inactive and background.

The documentation says

Key-related events may only be monitored if accessibility is enabled or if your application is trusted for accessibility access (see AXIsProcessTrusted).

See also AXIsProcessTrustedWithOptions and the newer APIs CGPreflightListenEventAccess and CGRequestListenEventAccess. For instance, when you program is starting up, you might call CGPreflightListenEventAccess, and if that returns false, call CGRequestListenEventAccess.

How to track the key press events of keyboard using SwiftUI for MacOS?
 
 
Q