OC代码
NSArray *windows = (__bridge_transfer NSArray*) CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
for(NSDictionary* winDict in windows)
{
NSString *appName = [winDict valueForKey:(__bridge NSString*)kCGWindowOwnerName];
pid_t pid = (pid_t)[[winDict valueForKey:(__bridge NSString*)kCGWindowOwnerPID] intValue];
if ([appName isEqualTo:@"QYHotReload"]) {
NSRunningApplication* app = [NSRunningApplication runningApplicationWithProcessIdentifier:pid];
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
}
}
swift 代码
let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }
if let window = infoList.first(where: { ($0["kCGWindowOwnerName"] as? String) == windowOwnerName}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
let app = NSRunningApplication(processIdentifier: pid)
app?.activate(options: .activateIgnoringOtherApps)
}