代码开源,C#获取mac电脑的开机时间!

代码开源:

在macOS中使用P/Invoke 原理,C#获取mac电脑的开机时间!

无废话,代码如下:

using System;
using System.Runtime.InteropServices;


namespace YuanMacLib
{
    public class MacBootTime
    {

        [DllImport("libc")]
        private static extern int sysctl(int[] name, uint namelen, IntPtr oldp, ref IntPtr oldlenp, IntPtr newp, uint newlen);

        // 对应 sysctl 的 kern.boottime 常量
        private static readonly int[] MIB = { 1, 21 }; // CTL_KERN = 1, KERN_BOOTTIME = 21

        public static DateTime GetBootTime()
        {
            IntPtr size = IntPtr.Zero;
            // 第一次调用获取数据长度
            if (sysctl(MIB, 2, IntPtr.Zero, ref size, IntPtr.Zero, 0) != 0)
                throw new Exception("sysctl failed");

            // 分配内存并获取数据
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                if (sysctl(MIB, 2, buffer, ref size, IntPtr.Zero, 0) != 0)
                    throw new Exception("sysctl failed");

                // 解析 timeval 结构体(tv_sec 和 tv_usec)
                long seconds = Marshal.ReadInt64(buffer, 0);
                int microseconds = Marshal.ReadInt32(buffer, 8);

                // 转换为 DateTime (Unix 时间戳起点为 1970-01-01)
                var bootTime = DateTimeOffset.FromUnixTimeSeconds(seconds)
                                              .AddMilliseconds(microseconds / 1000.0)
                                              .LocalDateTime;
                return bootTime;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }


    }
}

 

计算开机时间已流逝:

TimeSpan tspMacStartTimeGo = DateTime.Now - MacBootTime.GetBootTime();

 

posted @ 2026-10-04 13:36  鑫_源  阅读(9)  评论(0)    收藏  举报