I am trying to access a process to send a key with CGEventPostToPSN later. But my problem is that I can not get the running process. I am using the following code:
pid_t pid = GetPIDForProcessName("myprocess");
NSLog(@"PID: %d", pid);
ProcessSerialNumber psn = { 0, pid };
OSStatus status = GetProcessForPID(pid, &psn);
if (status != noErr) {
NSLog(@"OSStatus KO PID: %d %d %d", status, noErr, pid);
}else{
NSLog(@"OSStatus OK PID: %d %d %d", status, noErr, pid);
CGEventRef keyDown;
keyDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)0, TRUE);
CGEventRef keyUp;
keyUp = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)0, FALSE);
CGEventPostToPSN(&psn, keyDown);
CFRelease(keyDown);
CGEventPostToPSN(&psn, keyUp);
CFRelease(keyUp);
}
I am using the class "GetPID.h" to get the PID as an integer, and this seems to work correctly. But I get an error 600 "No eligible process with specified process serial number" in GetPIDForProcessName status.
I have tested some processes and this code works, but does not work with others. I have no very clear difference between processes can be
Thank you very much for any suggestions.
Not every process has a process serial number, just the apps. The docs for GetProcessForPID
fail to say that, but see Technical Q&A QA1123.
Edit to add: Here's a quote from that document...
Q: How do I get a list of all processes on Mac OS X?
A: Well, that depends on how you define "process". If you want to list all of the running applications you should use the Carbon Process Manager routine GetNextProcess. This will return a list of all application processes, including those running in the Carbon, Cocoa, and Classic environments. However, this doesn't return a list of non-application (daemon) processes.