You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java JNA调用CallNtPowerInformation获取屏幕超时时间

解决JNA调用CallNtPowerInformation获取屏幕超时的问题

你的代码存在几个关键问题,导致返回结果始终为0,以下是修正方案:

  • 调用CallNtPowerInformation后未检查返回值,无法确认调用是否成功
  • 未同步原生内存与Java结构体的字段数据
  • 错误访问了全局字段,笔记本的屏幕超时需区分AC(插电)和DC(电池)模式的独立设置

修正后的代码

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.PowrProf;
import com.sun.jna.platform.win32.WinNT;

public class ScreenTimeoutGetter {
    public static void main(String[] args) {
        WinNT.SYSTEM_POWER_POLICY powerPolicy = new WinNT.SYSTEM_POWER_POLICY();
        // 将Java结构体数据写入原生内存,确保初始化
        powerPolicy.write();
        Pointer policyPtr = powerPolicy.getPointer();

        // 调用系统API并检查返回状态
        int status = PowrProf.INSTANCE.CallNtPowerInformation(
                PowrProf.POWER_INFORMATION_LEVEL.SystemPowerPolicyCurrent,
                Pointer.NULL,
                0,
                policyPtr,
                powerPolicy.size()
        );

        if (status != WinNT.STATUS_SUCCESS) {
            System.err.println("API调用失败,错误码: " + status);
            return;
        }

        // 将原生内存更新的数据同步回Java结构体
        powerPolicy.read();

        // 分别获取插电和电池模式下的屏幕超时时间(单位:秒)
        System.out.println("插电状态屏幕超时: " + powerPolicy.AcPolicy.VideoTimeout + " 秒");
        System.out.println("电池状态屏幕超时: " + powerPolicy.DcPolicy.VideoTimeout + " 秒");
        System.out.println("是否启用屏幕调暗: " + (powerPolicy.VideoDimDisplay != 0));
    }
}

关键说明

  1. 内存同步:调用write()确保结构体的原生内存被正确初始化,调用read()将API修改后的原生数据同步到Java字段,这是JNA操作结构体的必要步骤。
  2. 模式区分:笔记本的电源策略分为AC(外接电源)和DC(电池)两种独立配置,超时时间需从对应模式的VideoTimeout字段获取。
  3. 错误检查:通过返回值判断API调用是否成功,非0值表示调用失败,可结合Windows错误码解析具体原因。

内容的提问来源于stack exchange,提问作者adragomir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:17:33