Skip to content

Instantly share code, notes, and snippets.

@killgxlin
Created January 16, 2020 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killgxlin/0a28ca18cca9303ebd6c8187ad23de95 to your computer and use it in GitHub Desktop.
Save killgxlin/0a28ca18cca9303ebd6c8187ad23de95 to your computer and use it in GitHub Desktop.
osx1015 设置 ScreenCapture 权限
#import <Foundation/Foundation.h>
#import <CoreVideo/CoreVideo.h>
#import <AppKit/AppKit.h>
BOOL canRecordScreen()
{
if (@available(macOS 10.15, *)) {
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
NSUInteger numberOfWindows = CFArrayGetCount(windowList);
NSUInteger numberOfWindowsWithName = 0;
for (int idx = 0; idx < numberOfWindows; idx++) {
NSDictionary *windowInfo = (NSDictionary *)CFArrayGetValueAtIndex(windowList, idx);
NSString *windowName = windowInfo[(id)kCGWindowName];
if (windowName) {
numberOfWindowsWithName++;
} else {
//no kCGWindowName detected -> not enabled
break; //breaking early, numberOfWindowsWithName not increased
}
}
CFRelease(windowList);
return numberOfWindows == numberOfWindowsWithName;
}
return YES;
}
void openSetting(){
NSString *urlString = @"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture";
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:urlString]];
}
void capture() {
CGRect mainRect = CGDisplayBounds(CGMainDisplayID());
CGImageRef desktopImage = CGWindowListCreateImage(mainRect, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageBestResolution | kCGWindowImageShouldBeOpaque);
NSImage* image = [[NSImage alloc]initWithCGImage:desktopImage size:NSMakeSize(100,100)];
CGImageRelease(desktopImage);
}
NSString * runCommand(NSString *commandToRun)
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
NSLog(@"run command:%@", commandToRun);
[task setArguments:arguments];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
NSData *data = [file readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return output;
}
void openDialog(void) {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"好的"];
[alert addButtonWithTitle:@"取消"];
[alert setMessageText:@"设置权限"];
[alert setInformativeText:@"请设置屏幕捕捉权限,重启小米人"];
[alert setAlertStyle:NSWarningAlertStyle];
if ([alert runModal] == NSAlertFirstButtonReturn) {
capture();
}
}
void gainPrivacy() {
if (!canRecordScreen()) {
runCommand(@"tccutil reset ScreenCapture com.xiaomi.mier");
openDialog();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment