如何检测OS X中的屏幕是否关闭?

时间:2016-08-29 13:27:27

标签: java macos

我正在创建一个应该只在显示器打开时运行的应用程序(除其他外),但我找不到通过命令行检查的方法。通过pmset -g检查用户空闲时间和首选空闲时间并不总是有效,因为各种程序可以改变这种状态。

是否有办法(通过命令行或Java)检查OS X中的屏幕当前是否已关闭?

1 个答案:

答案 0 :(得分:1)

C的这一位将检测屏幕是睡着还是醒着:

CGDirectDisplayID ids[20];
uint32_t num_ids;
if (kCGErrorSuccess != CGGetActiveDisplayList(20, ids, &num_ids)) {
    printf("Oops\n");
    return 1;
}
boolean_t asleep = true;
for (int i = 0; i < num_ids; i++) {
    asleep &= CGDisplayIsAsleep(ids[i]);
}
if (asleep) {
    printf("Asleep\n");
    return 1;
} else {
    printf("Awake\n");
    return 0;
}

使用:

可以将其严格转换为某些JNA

CoreGraphics.java

import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;

public interface CoreGraphics extends Library {
    CoreGraphics INSTANCE = (CoreGraphics)Native.loadLibrary("CoreGraphics", CoreGraphics.class);

    class int32_t extends IntegerType {
        public static final int SIZE = 4;
        public int32_t() {
            this(0);
        }
        public int32_t(long value) {
            super(SIZE, value, false);
        }
    };

    public static class CGError extends int32_t {
        public static final CGError Success = new CGError(0);

        public CGError() { this(0); }
        public CGError(int value) { super(value); }
    };

    public static class CGDirectDisplayID extends int32_t {
    };

    CGError CGGetActiveDisplayList(int maxDisplays, CGDirectDisplayID[] activeDisplays, IntByReference displayCount);
    boolean CGDisplayIsAsleep(CGDirectDisplayID disp);
}

使用界面的示例程序 - jna_monitors_run.java

import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;

public class jna_monitors_run {

    static final int MAX_DISPLAYS = 20;
    public static void main(String[] args) {
        IntByReference ib = new IntByReference();
        CoreGraphics.CGDirectDisplayID ids[] = new CoreGraphics.CGDirectDisplayID[MAX_DISPLAYS];
        if (! CoreGraphics.CGError.Success.equals(CoreGraphics.INSTANCE.CGGetActiveDisplayList(
                MAX_DISPLAYS, ids, ib))) {
            System.exit(2);
        }
        boolean is_asleep = true;
        int i = ib.getValue();
        while (--i >= 0) {
            is_asleep &= CoreGraphics.INSTANCE.CGDisplayIsAsleep(ids[i]);
        }
        System.out.println(is_asleep);
        System.exit(is_asleep ? 1 : 0);
    }
}