【发布时间】:2013-11-07 15:37:30
【问题描述】:
我正在尝试使用 PInvoke 和 .Net4.5 访问电池设备信息(在 Enumerating Battery Devices 行)。我有一个 WPF 应用程序运行良好,并且能够获取各种低级电池信息。
现在我正在尝试将同一个应用程序修改为 WinRT 现代应用程序。 Win32 API(例如 SetupDiEnumDeviceInterfaces、SetupDiGetDeviceInterfaceDetail)在 WinRT 中运行良好。但是当涉及到 CreateFile 时,我得到了无效的句柄 (-1) 并且 Marshal.GetLastWin32Error() 给出了 1008 (Error_No_Token)。 Marshal.GetHRForLastWin32Error().ToString() 给出“-2147023888”
知道如何在 WinRT 中通过 PIvoke 使用 CreateFile 吗?
[DllImport ("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
//var hBattery = NativeMethods.CreateFile (devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);
var hBattery = NativeMethods.CreateFile (devicePath, 3, 3, IntPtr.Zero, 3, 128, IntPtr.Zero);
if ( hBattery == new IntPtr (-1) )
{ throw new System.Exception(Marshal.GetHRForLastWin32Error().ToString()); }
【问题讨论】:
-
不能调用 CreateFile,沙盒不允许。对于文件,您必须使用 Windows.Storage 命名空间中的新 Windows 运行时 API。对于其他设备,除非有新的 api 可用,否则您将不走运。试试msdn.microsoft.com/en-us/library/windows/apps/… 命名空间。
-
谢谢克里斯。如果您可以将相同的评论作为答案,我很乐意将其标记为已接受的答案。它实际上引导我朝着正确的方向前进。
标签: c# .net windows-runtime pinvoke .net-4.5