首页 / 资讯中心 / 文章详情

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

代码开源,C#获取mac电脑的开机时间! ★ FEATURED ARTICLE
代码开源在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();
阅读完成 · 觉得有帮助?
咨询建站