You can do this using CGEventTap but it requires that the application is given accessibility permissions in "System Preferences - Security & Privacy - Privacy - Accessibility".
See this answerthis answer for a complete example.
If you need help converting this to Swift, let me know.