コード例 #1
0
        /// <summary>
        /// Opens the device handles and registers for device removal notification.
        /// </summary>
        private void OpenDevice()
        {
            DebugWriteLine("OpenDevice()");

            if (_readHandle != null)
            {
                DebugWriteLine("Device already open");
                return;
            }

            int lastError;

            _readHandle = CreateFile(_devicePath + "\\Pipe01", CreateFileAccessTypes.GenericRead, CreateFileShares.None,
                                     IntPtr.Zero, CreateFileDisposition.OpenExisting, CreateFileAttributes.Overlapped,
                                     IntPtr.Zero);
            lastError = Marshal.GetLastWin32Error();
            if (_readHandle.IsInvalid)
            {
                _readHandle = null;
                throw new Win32Exception(lastError);
            }

            _writeHandle = CreateFile(_devicePath + "\\Pipe00", CreateFileAccessTypes.GenericWrite, CreateFileShares.None,
                                      IntPtr.Zero, CreateFileDisposition.OpenExisting, CreateFileAttributes.Overlapped,
                                      IntPtr.Zero);
            lastError = Marshal.GetLastWin32Error();
            if (_writeHandle.IsInvalid)
            {
                _writeHandle = null;
                _readHandle.Dispose();
                throw new Win32Exception(lastError);
            }

            bool success = false;

            _readHandle.DangerousAddRef(ref success);
            if (success)
            {
                _notifyWindow.RegisterDeviceRemoval(_readHandle.DangerousGetHandle());
            }
            else
            {
                DebugWriteLine("Warning: Failed to initialize device removal notification");
            }

            _deviceAvailable = true;
        }