I am reading keys from a Logitech G13 keyboard and need to send them to a known application. It seems I should use the CGEventPostToPSN method to send the keystrokes. My problem is that I need the PSN for it, but all the solutions I could find in Stackoverflow use an iteration over the processes using GetNextProcess and it seems to be deprecated.
Is there a way of getting the PSN from a process if a know the name of the application or the path?
Or is there any other way of sending keystrokes to an external app? I could imagine that in any case I will need a PSN or a pid to the process.
It would be great to get Objective C code for it.
To get the PSN, you can use OSStatus GetProcessForPID(pid_t pid, ProcessSerialNumber *psn)
from the HIServices Framework. It's been deprecateded for many years but it still works fine.
In newer APIs there is the LSASN
(LS stands for LaunchServices which is a framework, and ASN might stand for ApplicationSerialNumber). Despite the different name it seems to be exactly the same as the ProcessSerialNumber and it seems it can be used interchangeably.
NSRunningApplication
has a private _asn
field which contains the LSASN. But it's wrapped inside an opaque CFType. You can extract the content by parsing the result of CFCopyDescription()
or by using private methods from the LaunchServices framework such as _LSASNToUInt64(LSASNRef asn)
. Another way to get the ASN is the lsappinfo
command line tool.
But personally, I would just stick to using GetProcessForPID()
until it's removed from the sytem. It's been deprecated since macOS 10.10 which was released in late 2014 - so over 9 years ago! But it still works fine.