美文网首页C++/Qt
Mac 枚举所有进程窗口并截图

Mac 枚举所有进程窗口并截图

作者: 哦呵呵y | 来源:发表于2020-06-08 11:12 被阅读0次

    清除app的所有权限
    tccutil reset All com.xxx.xxx
    mac 10.15 调试程序每次启动都需要重新授权。

    // 1. 先获取window列表 CGWindowListOption 可以换成自己需要的  windowid传空可以获取所有窗口
        CFArrayRef windowsRef = CGWindowListCreate(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
        CFArrayRef windowInfoRef = CGWindowListCreateDescriptionFromArray(windowsRef);
    // 2. 遍历窗口,对窗口截图
        int index = 0;
        int count = CFArrayGetCount(windowsRef);
        for (int i = 0; i < count; i ++) {
            // 3. 获取窗口ID
            CGWindowID wid = (CGWindowID)CFArrayGetValueAtIndex(windowsRef, i);
            // 4. 获取窗口信息
            NSDictionary *dict = CFArrayGetValueAtIndex(windowInfoRef, i);
            NSDictionary *value = dict[(NSString *)kCGWindowBounds];
            NSLog(@"%@", dict);
            NSLog(@"%@---%@---%@---%@", value[@"X"], value[@"Y"], value[@"Width"], value[@"Height"]);
            NSString *x = value[@"X"];
            NSString *y = value[@"Y"];
            NSString *width = value[@"Width"];
            NSString *height = value[@"Height"];
            NSNumber *number = dict[(NSString *)kCGWindowLayer];
            // 5. 过滤窗口,好像 kCGWindowLayer == 0的是应用程序窗口,其他类型的是menubar还有其他一些东西,暂时搞不清楚
            if (number.intValue == 0) {
                // 6. 通过windowID 和rect获取窗口截图
                NSRect rect = NSMakeRect(x.intValue, y.intValue, width.intValue, height.intValue);
                CGImageRef imgRef = CGWindowListCreateImage(rect, kCGWindowListOptionIncludingWindow, wid, kCGWindowImageDefault);
                NSImage *img = [[NSImage alloc] initWithCGImage:imgRef size:CGSizeZero];
                NSImageView *imageView = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 100 * index, 100, 100)];
                [self.view addSubview:imageView];
                imageView.image = img;
                index += 1;
            }
            
        }
    
    

    // 官方截图demo
    https://developer.apple.com/library/archive/samplecode/SonOfGrab/Introduction/Intro.html

    相关文章

      网友评论

        本文标题:Mac 枚举所有进程窗口并截图

        本文链接:https://www.haomeiwen.com/subject/eblltktx.html