stand on the shoulders of giants

[转] Tips - C#获取LastError

如下代码示例如何在C#中取得Win32的GetLastError.

 

        // this function is just for fun
        [DllImport("winusb.dll", SetLastError = true)]
        public static extern bool WinUsb_SetPowerPolicy(IntPtr InterfaceHandle, UInt32 PolicyType, UInt32 ValueLength, ref Byte Value);

        // this function is just for fun
        [DllImport("winusb.dll", SetLastError = true)]
        public static extern bool WinUsb_Initialize(Microsoft.Win32.SafeHandles.SafeFileHandle DeviceHandle, ref IntPtr InterfaceHandle);

 

 public bool SetPowerPolicy()
        {
            // this function never work
            IntPtr interfaceHandle = IntPtr.Zero;
            Microsoft.Win32.SafeHandles.SafeFileHandle sfh = new Microsoft.Win32.SafeHandles.SafeFileHandle(new IntPtr(this.deviceHandle), true);
            bool temp = USBXpressAPI.WinUsb_Initialize(sfh, ref interfaceHandle);
            System.ComponentModel.Win32Exception we = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
            System.Console.WriteLine(we.Message);
            byte value = 1;
            bool result = USBXpressAPI.WinUsb_SetPowerPolicy(interfaceHandle, (uint)0x01, (uint)1, ref value);
            return result;
        }

posted @ 2010-08-04 18:40  DylanWind  阅读(860)  评论(0编辑  收藏  举报