C# 如何使用CallNtPowerInformation(带Interop)获取Windows SystemExecutionState?
我真的很难在C#中使用这个函数。我需要获取Windows SystemExecutionState。(可能的值) 我找到了合适的C#签名:C# 如何使用CallNtPowerInformation(带Interop)获取Windows SystemExecutionState?,c#,interop,pinvoke,C#,Interop,Pinvoke,我真的很难在C#中使用这个函数。我需要获取Windows SystemExecutionState。(可能的值) 我找到了合适的C#签名: [DllImport("powrprof.dll", SetLastError = true)] private static extern UInt32 CallNtPowerInformation( Int32 InformationLevel, IntPtr lpInputBuffer,
[DllImport("powrprof.dll", SetLastError = true)]
private static extern UInt32 CallNtPowerInformation(
Int32 InformationLevel,
IntPtr lpInputBuffer,
UInt32 nInputBufferSize,
IntPtr lpOutputBuffer,
UInt32 nOutputBufferSize
);
现在我需要使用信息级别16来读取“SystemExecutionState”。以下是我目前掌握的代码:
IntPtr status = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(ulong)));
UInt32 returnValue = CallNtPowerInformation(
16,
(IntPtr)null,
0,
status, (
UInt32)Marshal.SizeOf(typeof(ulong)));
Marshal.FreeCoTaskMem(status);
根据Microsoft文档:
lpOutputBuffer接收包含系统的ULONG值
执行状态缓冲区
如何从IntPtr获取ULONG值?使用
输出uint
而不是IntPtr
[DllImport("powrprof.dll", SetLastError = true)]
private static extern UInt32 CallNtPowerInformation(
Int32 InformationLevel,
IntPtr lpInputBuffer,
UInt32 nInputBufferSize,
out uint lpOutputBuffer,
UInt32 nOutputBufferSize
);
uint result;
CallNtPowerInformation(..., out result);
调用以获取值
uint statusValue = (uint)Marshal.ReadInt32(status);
Marshal
类有一整套ReadXXX
方法,允许您从非托管内存中读取。+1这当然是一个选项,但它确实将CallNtPowerInformation
的使用限制为32位大小的值。如果您只对这一个值使用CallNtPowerInformation
,SystemExecutionState
,那么我会这样做。如果您想重新使用CallNtPowerInformation
的DllImport,那么Marshal.ReadInt32
及其朋友就是一个好办法。还有其他理由不使用Marshal吗?@James您真的可以这样做。两者都能完美地工作。“这就归结到哪个对你来说更方便了。”@DavidHeffernan:你也可以进行多次重载。@Slaks是的。这可以很好地工作。有很多选择!!这很有效,谢谢。我只是想决定是用这个方法还是SLaks的。