I'm writing a program in C for OS X (for the terminal). As mentioned in the title, just need the id and/or name of the application receiving the keystrokes i.e. the focused window.
I've found the you can use frontmostApplication but I can't use it in C or can't figure out how to do it. I'm new to writing stuff in macOS, any help much appreciated.
答案 0 :(得分:-1)
The UI layer on macOS is all written in Objective-C, which you can't easily call from straight C code (well, technically, you could use objc_msgSend()
, but trust me, you don't want to do that). Fortunately, the amount of Objective-C code you'll need to do this is quite small, and you can separate it out into a separate file which you include from your C code:
GetFrontApplication.h:
#ifndef GETFRONTAPPLICATION_H
#define GETFRONTAPPLICATION_H
char *GetFrontmostApplication(void);
#endif /* GETFRONTAPPLICATION_H */
GetFrontApplication.m:
@import Cocoa;
char *GetFrontmostApplication(void) {
@autoreleasepool {
NSRunningApplication *frontApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
return strdup(frontApp.localizedName.UTF8String);
}
}
Now you can just #include "GetFrontApplication.h"
and call GetFrontmostApplication()
from your C code, and you'll get a char *
containing the name of the application. Make sure to free()
the string after you're done with it.