diff --git a/TownSuite.TwainScanner/DibToImage.cs b/TownSuite.TwainScanner/DibToImage.cs index 16a1043..5db4173 100644 --- a/TownSuite.TwainScanner/DibToImage.cs +++ b/TownSuite.TwainScanner/DibToImage.cs @@ -1,20 +1,20 @@ -/* Saraff.Twain.NET - * SARAFF SOFTWARE ( ), 2011. - * Saraff.Twain.NET - : / - * GNU , - * ; - * 3 , ( ) - * . - * Saraff.Twain.NET , , - * ; - * . . - * GNU. - * GNU - * . , . +/* ���� ���� �������� ������ ���������� Saraff.Twain.NET + * � SARAFF SOFTWARE (����������� ������), 2011. + * Saraff.Twain.NET - ��������� ���������: �� ������ ������������������ �� �/��� + * �������� �� �� �������� ������� ����������� ������������ �������� GNU � ��� ����, + * � ����� ��� ���� ������������ ������ ���������� ������������ �����������; + * ���� ������ 3 ��������, ���� (�� ������ ������) ����� ����� ������� + * ������. + * Saraff.Twain.NET ���������������� � �������, ��� ��� ����� ��������, + * �� ���� ������ ��������; ���� ��� ������� �������� ��������� ���� + * ��� ����������� ��� ������������ �����. ��������� ��. � ������� ����������� + * ������������ �������� GNU. + * �� ������ ���� �������� ����� ������� ����������� ������������ �������� GNU + * ������ � ���� ����������. ���� ��� �� ���, ��. * .) * * This file is part of Saraff.Twain.NET. - * SARAFF SOFTWARE (Kirnazhytski Andrei), 2011. + * � SARAFF SOFTWARE (Kirnazhytski Andrei), 2011. * Saraff.Twain.NET is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or @@ -35,57 +35,90 @@ using System.IO; using System.Reflection; using System.Collections.Generic; +using TownSuite.TwainScanner; namespace TownSuite.TwainScanner { - internal sealed class DibToImage { - private const int BufferSize=256*1024; //256K + internal sealed class DibToImage : _ImageHandler + { - public static Stream WithStream(IntPtr dibPtr,IStreamProvider provider) { - Stream _stream=provider!=null?provider.GetStream():new MemoryStream(); - BinaryWriter _writer=new BinaryWriter(_stream); - - BITMAPINFOHEADER _bmi=(BITMAPINFOHEADER)Marshal.PtrToStructure(dibPtr,typeof(BITMAPINFOHEADER)); - - int _extra=0; - if(_bmi.biCompression==0) { - int _bytesPerRow=((_bmi.biWidth*_bmi.biBitCount)>>3); - _extra=Math.Max(_bmi.biHeight*(_bytesPerRow+((_bytesPerRow&0x3)!=0?4-_bytesPerRow&0x3:0))-_bmi.biSizeImage,0); - } - - int _dibSize=_bmi.biSize+_bmi.biSizeImage+_extra+(_bmi.ClrUsed<<2); + /// + /// Convert a block of unmanaged memory to stream. + /// + /// The pointer to block of unmanaged memory. + /// + protected override void PtrToStreamCore(IntPtr ptr, Stream stream) + { + BinaryWriter _writer = new BinaryWriter(stream); #region BITMAPFILEHEADER + BITMAPINFOHEADER _header = this.Header; + _writer.Write((ushort)0x4d42); - _writer.Write(14+_dibSize); + _writer.Write(14 + this.GetSize()); _writer.Write(0); - _writer.Write(14+_bmi.biSize+(_bmi.ClrUsed<<2)); + _writer.Write(14 + _header.biSize + (_header.ClrUsed << 2)); #endregion #region BITMAPINFO and pixel data - byte[] _buffer = new byte[DibToImage.BufferSize]; - for(int _offset = 0, _len = 0; _offset<_dibSize; _offset+=_len) { - _len=Math.Min(DibToImage.BufferSize,_dibSize-_offset); - Marshal.Copy((IntPtr)(dibPtr.ToInt64()+_offset),_buffer,0,_len); - _writer.Write(_buffer,0,_len); - } + base.PtrToStreamCore(ptr, stream); #endregion - return _stream; } - public static Stream WithStream(IntPtr dibPtr) { - return DibToImage.WithStream(dibPtr,null); + /// + /// Gets the size of a image data. + /// + /// + /// Size of a image data. + /// + protected override int GetSize() + { + if (!this.HandlerState.ContainsKey("DIBSIZE")) + { + BITMAPINFOHEADER _header = this.Header; + + int _extra = 0; + if (_header.biCompression == 0) + { + int _bytesPerRow = ((_header.biWidth * _header.biBitCount) >> 3); + _extra = Math.Max(_header.biHeight * (_bytesPerRow + ((_bytesPerRow & 0x3) != 0 ? 4 - _bytesPerRow & 0x3 : 0)) - _header.biSizeImage, 0); + } + + this.HandlerState.Add("DIBSIZE", _header.biSize + _header.biSizeImage + _extra + (_header.ClrUsed << 2)); + } + return (int)this.HandlerState["DIBSIZE"]; + } + + /// + /// Gets the size of the buffer. + /// + /// + /// The size of the buffer. + /// + protected override int BufferSize => 256 * 1024; //256K + + private BITMAPINFOHEADER Header + { + get + { + if (!this.HandlerState.ContainsKey("BITMAPINFOHEADER")) + { + this.HandlerState.Add("BITMAPINFOHEADER", Marshal.PtrToStructure(this.ImagePointer, typeof(BITMAPINFOHEADER))); + } + return this.HandlerState["BITMAPINFOHEADER"] as BITMAPINFOHEADER; + } } - [StructLayout(LayoutKind.Sequential,Pack=2)] - private class BITMAPINFOHEADER { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + private class BITMAPINFOHEADER + { public int biSize; public int biWidth; public int biHeight; @@ -98,29 +131,9 @@ private class BITMAPINFOHEADER { public int biClrUsed; public int biClrImportant; - public int ClrUsed { - get { - return this.IsRequiredCreateColorTable ? 1< this.IsRequiredCreateColorTable ? 1 << this.biBitCount : this.biClrUsed; - public bool IsRequiredCreateColorTable { - get { - return this.biClrUsed==0&&this.biBitCount<=8; - } - } + public bool IsRequiredCreateColorTable => this.biClrUsed == 0 && this.biBitCount <= 8; } } - - /// - /// Provides instances of the for data writing. - /// - public interface IStreamProvider { - - /// - /// Gets the stream. - /// - /// The stream. - Stream GetStream(); - } -} +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/MainFrame.cs b/TownSuite.TwainScanner/MainFrame.cs index bcbfa75..6a54ad2 100644 --- a/TownSuite.TwainScanner/MainFrame.cs +++ b/TownSuite.TwainScanner/MainFrame.cs @@ -1064,7 +1064,10 @@ private void SourceListBox_SelectedValueChanged(object sender, EventArgs e) private void SourceTwianListBox_SelectedValueChanged(object sender, EventArgs e) { //this._twain.SetDefaultSource(sourceTwianListBox.SelectedIndex); - this._twain.SourceIndex = sourceTwianListBox.SelectedIndex; + if (sourceTwianListBox.SelectedIndex >= 0) + { + this._twain.SourceIndex = sourceTwianListBox.SelectedIndex; + } } private void MainFrame_FormClosing(object sender, FormClosingEventArgs e) diff --git a/TownSuite.TwainScanner/Pict.cs b/TownSuite.TwainScanner/Pict.cs new file mode 100644 index 0000000..5770388 --- /dev/null +++ b/TownSuite.TwainScanner/Pict.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using TownSuite.TwainScanner; + +namespace TownSuite.TwainScanner +{ + + internal sealed class Pict : _ImageHandler + { + + /// + /// Gets the size of a image data. + /// + /// + /// Size of a image data. + /// + protected override int GetSize() => throw new NotImplementedException(); + + /// + /// Gets the size of the buffer. + /// + /// + /// The size of the buffer. + /// + protected override int BufferSize => 256 * 1024; //256K + } +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/Tiff.cs b/TownSuite.TwainScanner/Tiff.cs index a993e21..e014421 100644 --- a/TownSuite.TwainScanner/Tiff.cs +++ b/TownSuite.TwainScanner/Tiff.cs @@ -36,95 +36,139 @@ using System.Diagnostics; using System.IO; using System.Collections.ObjectModel; +using TownSuite.TwainScanner; namespace TownSuite.TwainScanner { - internal sealed class Tiff { - private TiffHeader _header; - private Tiff.Ifd _ifd; + internal sealed class Tiff : _ImageHandler + { - private static Tiff FromPtr(IntPtr ptr) { - Tiff _tiff=new Tiff { - _header=(TiffHeader)Marshal.PtrToStructure(ptr,typeof(TiffHeader)) - }; - if(_tiff._header.magic==MagicValues.BigEndian) { + /// + /// Convert a block of unmanaged memory to stream. + /// + /// The pointer to block of unmanaged memory. + /// + /// + protected override void PtrToStreamCore(IntPtr ptr, Stream stream) + { + if (this.Header.magic == MagicValues.BigEndian) + { throw new NotSupportedException(); } - _tiff._ifd=Ifd.FromPtr((IntPtr)(ptr.ToInt64()+_tiff._header.dirOffset),ptr); - return _tiff; + base.PtrToStreamCore(ptr, stream); } - public static Stream FromPtrToImage(IntPtr ptr) { - Tiff _tiff=Tiff.FromPtr(ptr); - byte[] _tiffData=new byte[_tiff._GetSize()]; - Marshal.Copy(ptr,_tiffData,0,_tiffData.Length); - return new MemoryStream(_tiffData); - } - - private int _GetSize() { - int _size=0; - for(Tiff.Ifd _idf=this.ImageFileDirectory; _idf!=null; _idf=_idf.NextIfd) { - if(_idf.Offset+_idf.Size>_size) { - _size=_idf.Offset+_idf.Size; - } - - Tiff.IfdEntry _stripOffsetsTag=null,_stripByteCountsTag=null; - Tiff.IfdEntry _freeOffsets=null,_freeByteCounts=null; - Tiff.IfdEntry _tileOffsets=null,_tileByteCounts=null; - foreach(IfdEntry _entry in _idf) { - if(_entry.DataOffset+_entry.DataSize>_size) { - _size=_entry.DataOffset+_entry.DataSize; + /// + /// Gets the size of a image data. + /// + /// + /// Size of a image data. + /// + protected override int GetSize() + { + if (!this.HandlerState.ContainsKey("TIFFSIZE")) + { + int _size = 0; + for (Tiff.Ifd _idf = this.ImageFileDirectory; _idf != null; _idf = _idf.NextIfd) + { + if (_idf.Offset + _idf.Size > _size) + { + _size = _idf.Offset + _idf.Size; } - switch(_entry.Tag) { - case TiffTags.STRIPOFFSETS: - _stripOffsetsTag=_entry; - break; - case TiffTags.STRIPBYTECOUNTS: - _stripByteCountsTag=_entry; - break; - case TiffTags.FREEOFFSETS: - _freeOffsets=_entry; - break; - case TiffTags.FREEBYTECOUNTS: - _freeByteCounts=_entry; - break; - case TiffTags.TILEOFFSETS: - _tileOffsets=_entry; - break; - case TiffTags.TILEBYTECOUNTS: - _tileByteCounts=_entry; - break; + + Tiff.IfdEntry _stripOffsetsTag = null, _stripByteCountsTag = null; + Tiff.IfdEntry _freeOffsets = null, _freeByteCounts = null; + Tiff.IfdEntry _tileOffsets = null, _tileByteCounts = null; + foreach (IfdEntry _entry in _idf) + { + if (_entry.DataOffset + _entry.DataSize > _size) + { + _size = _entry.DataOffset + _entry.DataSize; + } + switch (_entry.Tag) + { + case TiffTags.STRIPOFFSETS: + _stripOffsetsTag = _entry; + break; + case TiffTags.STRIPBYTECOUNTS: + _stripByteCountsTag = _entry; + break; + case TiffTags.FREEOFFSETS: + _freeOffsets = _entry; + break; + case TiffTags.FREEBYTECOUNTS: + _freeByteCounts = _entry; + break; + case TiffTags.TILEOFFSETS: + _tileOffsets = _entry; + break; + case TiffTags.TILEBYTECOUNTS: + _tileByteCounts = _entry; + break; + } } - } - foreach(IfdEntry[] _item in new Tiff.IfdEntry[][] { new[] { _stripOffsetsTag,_stripByteCountsTag },new[] { _freeOffsets,_freeByteCounts },new[] { _tileOffsets,_tileByteCounts } }) { - if(_item[0]!=null&&_item[1]!=null&&_item[0].Length==_item[1].Length) { - for(int i=0; i<_item[0].Length; i++) { - int _dataOffset=Convert.ToInt32(_item[0][i]); - int _dataSize=Convert.ToInt32(_item[1][i]); - if(_dataOffset+_dataSize>_size) { - _size=_dataOffset+_dataSize; + foreach (IfdEntry[] _item in new Tiff.IfdEntry[][] { new[] { _stripOffsetsTag, _stripByteCountsTag }, new[] { _freeOffsets, _freeByteCounts }, new[] { _tileOffsets, _tileByteCounts } }) + { + if (_item[0] != null && _item[1] != null && _item[0].Length == _item[1].Length) + { + for (int i = 0; i < _item[0].Length; i++) + { + int _dataOffset = Convert.ToInt32(_item[0][i]); + int _dataSize = Convert.ToInt32(_item[1][i]); + if (_dataOffset + _dataSize > _size) + { + _size = _dataOffset + _dataSize; + } } } } } + this.HandlerState.Add("TIFFSIZE", _size); } - return _size; + return (int)this.HandlerState["TIFFSIZE"]; } - private Tiff.Ifd ImageFileDirectory { - get { - return this._ifd; + /// + /// Gets the size of the buffer. + /// + /// + /// The size of the buffer. + /// + protected override int BufferSize => 256 * 1024; //256K + + private TiffHeader Header + { + get + { + if (!this.HandlerState.ContainsKey("TiffHeader")) + { + this.HandlerState.Add("TiffHeader", Marshal.PtrToStructure(this.ImagePointer, typeof(TiffHeader))); + } + return this.HandlerState["TiffHeader"] as TiffHeader; + } + } + + private Tiff.Ifd ImageFileDirectory + { + get + { + if (!this.HandlerState.ContainsKey("ImageFileDirectory")) + { + this.HandlerState.Add("ImageFileDirectory", Ifd.FromPtr((IntPtr)(this.ImagePointer.ToInt64() + this.Header.dirOffset), this.ImagePointer)); + } + return this.HandlerState["ImageFileDirectory"] as Tiff.Ifd; } } - #region Вложенные типы + #region Nested Types / Вложенные типы /// /// TIFF header. /// - [StructLayout(LayoutKind.Sequential,Pack=1)] - private sealed class TiffHeader { + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private sealed class TiffHeader + { /// /// Magic number (defines byte order). @@ -143,9 +187,10 @@ private sealed class TiffHeader { public uint dirOffset; } - private enum MagicValues:ushort { - BigEndian=0x4d4d, - LittleEndian=0x4949 + private enum MagicValues : ushort + { + BigEndian = 0x4d4d, + LittleEndian = 0x4949 } /// @@ -158,8 +203,9 @@ private enum MagicValues:ushort { /// field to save space. If the value is less than 4 bytes, it is /// left-justified in the offset field. /// - [StructLayout(LayoutKind.Sequential,Pack=1)] - private sealed class TiffDirEntry { + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private sealed class TiffDirEntry + { /// /// Tag id. @@ -188,101 +234,85 @@ private sealed class TiffDirEntry { /// Image File Directory. /// [DebuggerDisplay("{Tag}; DataType = {DataType}; Length = {Length}")] - private sealed class IfdEntry { + private sealed class IfdEntry + { private Array _data; - public static Tiff.IfdEntry FromPtr(IntPtr ptr,IntPtr baseAddr) { - TiffDirEntry _entry=(TiffDirEntry)Marshal.PtrToStructure(ptr,typeof(TiffDirEntry)); + public static Tiff.IfdEntry FromPtr(IntPtr ptr, IntPtr baseAddr) + { + TiffDirEntry _entry = (TiffDirEntry)Marshal.PtrToStructure(ptr, typeof(TiffDirEntry)); - Tiff.IfdEntry _ifdEntry=new Tiff.IfdEntry { - Tag=_entry.tag, - DataType=_entry.type, - _data=Array.CreateInstance(TiffDataTypeHelper.Typeof(_entry.type),_entry.count<=int.MaxValue?_entry.count:0) + Tiff.IfdEntry _ifdEntry = new Tiff.IfdEntry + { + Tag = _entry.tag, + DataType = _entry.type, + _data = Array.CreateInstance(TiffDataTypeHelper.Typeof(_entry.type), _entry.count <= int.MaxValue ? _entry.count : 0) }; - IntPtr _dataPtr=(IntPtr)(((_ifdEntry.DataSize=(int)(TiffDataTypeHelper.Sizeof(_entry.type)*_ifdEntry._data.Length))>4)?baseAddr.ToInt64()+_entry.offset:ptr.ToInt64()+8); - _ifdEntry.DataOffset=(int)(_dataPtr.ToInt64()-baseAddr.ToInt64()); - for(int i=0,_size=TiffDataTypeHelper.Sizeof(_entry.type); i<_ifdEntry._data.Length; i++) { - _ifdEntry._data.SetValue(Marshal.PtrToStructure((IntPtr)(_dataPtr.ToInt64()+_size*i),TiffDataTypeHelper.Typeof(_entry.type)),i); + IntPtr _dataPtr = (IntPtr)(((_ifdEntry.DataSize = (int)(TiffDataTypeHelper.Sizeof(_entry.type) * _ifdEntry._data.Length)) > 4) ? baseAddr.ToInt64() + _entry.offset : ptr.ToInt64() + 8); + _ifdEntry.DataOffset = (int)(_dataPtr.ToInt64() - baseAddr.ToInt64()); + for (int i = 0, _size = TiffDataTypeHelper.Sizeof(_entry.type); i < _ifdEntry._data.Length; i++) + { + _ifdEntry._data.SetValue(Marshal.PtrToStructure((IntPtr)(_dataPtr.ToInt64() + _size * i), TiffDataTypeHelper.Typeof(_entry.type)), i); } return _ifdEntry; } - public TiffTags Tag { - get; - private set; - } + public TiffTags Tag { get; private set; } - public TiffDataType DataType { - get; - private set; - } + public TiffDataType DataType { get; private set; } - public int DataOffset { - get; - private set; - } + public int DataOffset { get; private set; } - public int DataSize { - get; - private set; - } + public int DataSize { get; private set; } - public int Length { - get { - return this._data.Length; - } - } + public int Length => this._data.Length; - public object this[int index] { - get { - return this._data.GetValue(index); - } - } + public object this[int index] => this._data.GetValue(index); } - private sealed class Ifd:Collection { + private sealed class Ifd : Collection + { - public static Tiff.Ifd FromPtr(IntPtr ptr,IntPtr baseAddr) { - Tiff.Ifd _idf=new Tiff.Ifd(); - _idf.Load(ptr,baseAddr); + public static Tiff.Ifd FromPtr(IntPtr ptr, IntPtr baseAddr) + { + Tiff.Ifd _idf = new Tiff.Ifd(); + _idf.Load(ptr, baseAddr); return _idf; } - private void Load(IntPtr ptr,IntPtr baseAddr) { - ushort _count=(ushort)Marshal.PtrToStructure(ptr,typeof(ushort)); - IntPtr _ptr=(IntPtr)(ptr.ToInt64()+sizeof(ushort)); - for(int i=0,_size=Marshal.SizeOf(typeof(TiffDirEntry)); i<_count; i++,_ptr=(IntPtr)(_ptr.ToInt64()+_size)) { - this.Add(Tiff.IfdEntry.FromPtr(_ptr,baseAddr)); + private void Load(IntPtr ptr, IntPtr baseAddr) + { + ushort _count = (ushort)Marshal.PtrToStructure(ptr, typeof(ushort)); + IntPtr _ptr = (IntPtr)(ptr.ToInt64() + sizeof(ushort)); + for (int i = 0, _size = Marshal.SizeOf(typeof(TiffDirEntry)); i < _count; i++, _ptr = (IntPtr)(_ptr.ToInt64() + _size)) + { + this.Add(Tiff.IfdEntry.FromPtr(_ptr, baseAddr)); } - int _nextIdfOffset=(int)Marshal.PtrToStructure(_ptr,typeof(int)); - if(_nextIdfOffset!=0) { - this.NextIfd=Ifd.FromPtr((IntPtr)(baseAddr.ToInt64()+_nextIdfOffset),baseAddr); + int _nextIdfOffset = (int)Marshal.PtrToStructure(_ptr, typeof(int)); + if (_nextIdfOffset != 0) + { + this.NextIfd = Ifd.FromPtr((IntPtr)(baseAddr.ToInt64() + _nextIdfOffset), baseAddr); } - this.Offset=(int)(ptr.ToInt64()-baseAddr.ToInt64()); - this.Size=6+Marshal.SizeOf(typeof(Tiff.TiffDirEntry))*_count; + this.Offset = (int)(ptr.ToInt64() - baseAddr.ToInt64()); + this.Size = 6 + Marshal.SizeOf(typeof(Tiff.TiffDirEntry)) * _count; } - public int Offset { - get; - private set; - } + public int Offset { get; private set; } - public int Size { - get; - private set; - } + public int Size { get; private set; } - public Tiff.Ifd NextIfd { - get; - private set; - } + public Tiff.Ifd NextIfd { get; private set; } - public Tiff.IfdEntry this[TiffTags tag] { - get { - for(int i=0; i /// RATIONALs are the ratio of two 32-bit integer values. - private enum TiffDataType:ushort { + private enum TiffDataType : ushort + { /// /// Placeholder. /// - TIFF_NOTYPE=0, + TIFF_NOTYPE = 0, /// /// 8-bit unsigned integer. /// - TIFF_BYTE=1, + TIFF_BYTE = 1, /// /// 8-bit bytes w/ last byte null. /// - TIFF_ASCII=2, + TIFF_ASCII = 2, /// /// 16-bit unsigned integer. /// - TIFF_SHORT=3, + TIFF_SHORT = 3, /// /// 32-bit unsigned integer. /// - TIFF_LONG=4, + TIFF_LONG = 4, /// /// 64-bit unsigned fraction. /// - TIFF_RATIONAL=5, + TIFF_RATIONAL = 5, /// /// !8-bit signed integer. /// - TIFF_SBYTE=6, + TIFF_SBYTE = 6, /// /// !8-bit untyped data. /// - TIFF_UNDEFINED=7, + TIFF_UNDEFINED = 7, /// /// !16-bit signed integer. /// - TIFF_SSHORT=8, + TIFF_SSHORT = 8, /// /// !32-bit signed integer. /// - TIFF_SLONG=9, + TIFF_SLONG = 9, /// /// !64-bit signed fraction. /// - TIFF_SRATIONAL=10, + TIFF_SRATIONAL = 10, /// /// !32-bit IEEE floating point. /// - TIFF_FLOAT=11, + TIFF_FLOAT = 11, /// /// !64-bit IEEE floating point. /// - TIFF_DOUBLE=12, + TIFF_DOUBLE = 12, /// /// %32-bit unsigned integer (offset). /// - TIFF_IFD=13 + TIFF_IFD = 13 } - private sealed class TiffDataTypeHelper { - private static Dictionary _sizeDictionary; - private static Dictionary _typeDictionary; + private sealed class TiffDataTypeHelper + { + private static Dictionary _sizeDictionary; + private static Dictionary _typeDictionary; - public static int Sizeof(TiffDataType type) { - try { + public static int Sizeof(TiffDataType type) + { + try + { return TiffDataTypeHelper.SizeDictionary[type]; - } catch(KeyNotFoundException) { + } + catch (KeyNotFoundException) + { return 0; } } - public static Type Typeof(TiffDataType type) { - try { + public static Type Typeof(TiffDataType type) + { + try + { return TiffDataTypeHelper.TypeDictionary[type]; - } catch(KeyNotFoundException) { + } + catch (KeyNotFoundException) + { return typeof(object); } } - private static Dictionary SizeDictionary { - get { - if(TiffDataTypeHelper._sizeDictionary==null) { - TiffDataTypeHelper._sizeDictionary=new Dictionary { + private static Dictionary SizeDictionary + { + get + { + if (TiffDataTypeHelper._sizeDictionary == null) + { + TiffDataTypeHelper._sizeDictionary = new Dictionary { {TiffDataType.TIFF_NOTYPE,0}, {TiffDataType.TIFF_BYTE,1}, {TiffDataType.TIFF_ASCII,1}, @@ -412,10 +455,13 @@ private static Dictionary SizeDictionary { } } - private static Dictionary TypeDictionary { - get { - if(TiffDataTypeHelper._typeDictionary==null) { - TiffDataTypeHelper._typeDictionary=new Dictionary { + private static Dictionary TypeDictionary + { + get + { + if (TiffDataTypeHelper._typeDictionary == null) + { + TiffDataTypeHelper._typeDictionary = new Dictionary { {TiffDataType.TIFF_NOTYPE,typeof(object)}, {TiffDataType.TIFF_BYTE,typeof(byte)}, {TiffDataType.TIFF_ASCII,typeof(byte)}, @@ -440,111 +486,112 @@ private static Dictionary TypeDictionary { /// /// TIFF Tag Definitions. /// - private enum TiffTags:ushort { - SUBFILETYPE=254, /* subfile data descriptor */ - OSUBFILETYPE=255, /* +kind of data in subfile */ - IMAGEWIDTH=256, /* image width in pixels */ - IMAGELENGTH=257, /* image height in pixels */ - BITSPERSAMPLE=258, /* bits per channel (sample) */ - COMPRESSION=259, /* data compression technique */ - PHOTOMETRIC=262, /* photometric interpretation */ - THRESHHOLDING=263, /* +thresholding used on data */ - CELLWIDTH=264, /* +dithering matrix width */ - CELLLENGTH=265, /* +dithering matrix height */ - FILLORDER=266, /* data order within a byte */ - DOCUMENTNAME=269, /* name of doc. image is from */ - IMAGEDESCRIPTION=270, /* info about image */ - MAKE=271, /* scanner manufacturer name */ - MODEL=272, /* scanner model name/number */ - STRIPOFFSETS=273, /* offsets to data strips */ - ORIENTATION=274, /* +image orientation */ - SAMPLESPERPIXEL=277, /* samples per pixel */ - ROWSPERSTRIP=278, /* rows per strip of data */ - STRIPBYTECOUNTS=279, /* bytes counts for strips */ - MINSAMPLEVALUE=280, /* +minimum sample value */ - MAXSAMPLEVALUE=281, /* +maximum sample value */ - XRESOLUTION=282, /* pixels/resolution in x */ - YRESOLUTION=283, /* pixels/resolution in y */ - PLANARCONFIG=284, /* storage organization */ - PAGENAME=285, /* page name image is from */ - XPOSITION=286, /* x page offset of image lhs */ - YPOSITION=287, /* y page offset of image lhs */ - FREEOFFSETS=288, /* +byte offset to free block */ - FREEBYTECOUNTS=289, /* +sizes of free blocks */ - GRAYRESPONSEUNIT=290, /* $gray scale curve accuracy */ - GRAYRESPONSECURVE=291, /* $gray scale response curve */ - GROUP3OPTIONS=292, /* 32 flag bits */ - T4OPTIONS=292, /* TIFF 6.0 proper name alias */ - GROUP4OPTIONS=293, /* 32 flag bits */ - T6OPTIONS=293, /* TIFF 6.0 proper name */ - RESOLUTIONUNIT=296, /* units of resolutions */ - PAGENUMBER=297, /* page numbers of multi-page */ - COLORRESPONSEUNIT=300, /* $color curve accuracy */ - TRANSFERFUNCTION=301, /* !colorimetry info */ - SOFTWARE=305, /* name & release */ - DATETIME=306, /* creation date and time */ - ARTIST=315, /* creator of image */ - HOSTCOMPUTER=316, /* machine where created */ - PREDICTOR=317, /* prediction scheme w/ LZW */ - WHITEPOINT=318, /* image white point */ - PRIMARYCHROMATICITIES=319, /* !primary chromaticities */ - COLORMAP=320, /* RGB map for pallette image */ - HALFTONEHINTS=321, /* !highlight+shadow info */ - TILEWIDTH=322, /* !tile width in pixels */ - TILELENGTH=323, /* !tile height in pixels */ - TILEOFFSETS=324, /* !offsets to data tiles */ - TILEBYTECOUNTS=325, /* !byte counts for tiles */ - BADFAXLINES=326, /* lines w/ wrong pixel count */ - CLEANFAXDATA=327, /* regenerated line info */ - CONSECUTIVEBADFAXLINES=328, /* max consecutive bad lines */ - SUBIFD=330, /* subimage descriptors */ - INKSET=332, /* !inks in separated image */ - INKNAMES=333, /* !ascii names of inks */ - NUMBEROFINKS=334, /* !number of inks */ - DOTRANGE=336, /* !0% and 100% dot codes */ - TARGETPRINTER=337, /* !separation target */ - EXTRASAMPLES=338, /* !info about extra samples */ - SAMPLEFORMAT=339, /* !data sample format */ - SMINSAMPLEVALUE=340, /* !variable MinSampleValue */ - SMAXSAMPLEVALUE=341, /* !variable MaxSampleValue */ - CLIPPATH=343, /* %ClipPath [Adobe TIFF technote 2] */ - XCLIPPATHUNITS=344, /* %XClipPathUnits [Adobe TIFF technote 2] */ - YCLIPPATHUNITS=345, /* %YClipPathUnits [Adobe TIFF technote 2] */ - INDEXED=346, /* %Indexed [Adobe TIFF Technote 3] */ - JPEGTABLES=347, /* %JPEG table stream */ - OPIPROXY=351, /* %OPI Proxy [Adobe TIFF technote] */ + private enum TiffTags : ushort + { + SUBFILETYPE = 254, /* subfile data descriptor */ + OSUBFILETYPE = 255, /* +kind of data in subfile */ + IMAGEWIDTH = 256, /* image width in pixels */ + IMAGELENGTH = 257, /* image height in pixels */ + BITSPERSAMPLE = 258, /* bits per channel (sample) */ + COMPRESSION = 259, /* data compression technique */ + PHOTOMETRIC = 262, /* photometric interpretation */ + THRESHHOLDING = 263, /* +thresholding used on data */ + CELLWIDTH = 264, /* +dithering matrix width */ + CELLLENGTH = 265, /* +dithering matrix height */ + FILLORDER = 266, /* data order within a byte */ + DOCUMENTNAME = 269, /* name of doc. image is from */ + IMAGEDESCRIPTION = 270, /* info about image */ + MAKE = 271, /* scanner manufacturer name */ + MODEL = 272, /* scanner model name/number */ + STRIPOFFSETS = 273, /* offsets to data strips */ + ORIENTATION = 274, /* +image orientation */ + SAMPLESPERPIXEL = 277, /* samples per pixel */ + ROWSPERSTRIP = 278, /* rows per strip of data */ + STRIPBYTECOUNTS = 279, /* bytes counts for strips */ + MINSAMPLEVALUE = 280, /* +minimum sample value */ + MAXSAMPLEVALUE = 281, /* +maximum sample value */ + XRESOLUTION = 282, /* pixels/resolution in x */ + YRESOLUTION = 283, /* pixels/resolution in y */ + PLANARCONFIG = 284, /* storage organization */ + PAGENAME = 285, /* page name image is from */ + XPOSITION = 286, /* x page offset of image lhs */ + YPOSITION = 287, /* y page offset of image lhs */ + FREEOFFSETS = 288, /* +byte offset to free block */ + FREEBYTECOUNTS = 289, /* +sizes of free blocks */ + GRAYRESPONSEUNIT = 290, /* $gray scale curve accuracy */ + GRAYRESPONSECURVE = 291, /* $gray scale response curve */ + GROUP3OPTIONS = 292, /* 32 flag bits */ + T4OPTIONS = 292, /* TIFF 6.0 proper name alias */ + GROUP4OPTIONS = 293, /* 32 flag bits */ + T6OPTIONS = 293, /* TIFF 6.0 proper name */ + RESOLUTIONUNIT = 296, /* units of resolutions */ + PAGENUMBER = 297, /* page numbers of multi-page */ + COLORRESPONSEUNIT = 300, /* $color curve accuracy */ + TRANSFERFUNCTION = 301, /* !colorimetry info */ + SOFTWARE = 305, /* name & release */ + DATETIME = 306, /* creation date and time */ + ARTIST = 315, /* creator of image */ + HOSTCOMPUTER = 316, /* machine where created */ + PREDICTOR = 317, /* prediction scheme w/ LZW */ + WHITEPOINT = 318, /* image white point */ + PRIMARYCHROMATICITIES = 319, /* !primary chromaticities */ + COLORMAP = 320, /* RGB map for pallette image */ + HALFTONEHINTS = 321, /* !highlight+shadow info */ + TILEWIDTH = 322, /* !tile width in pixels */ + TILELENGTH = 323, /* !tile height in pixels */ + TILEOFFSETS = 324, /* !offsets to data tiles */ + TILEBYTECOUNTS = 325, /* !byte counts for tiles */ + BADFAXLINES = 326, /* lines w/ wrong pixel count */ + CLEANFAXDATA = 327, /* regenerated line info */ + CONSECUTIVEBADFAXLINES = 328, /* max consecutive bad lines */ + SUBIFD = 330, /* subimage descriptors */ + INKSET = 332, /* !inks in separated image */ + INKNAMES = 333, /* !ascii names of inks */ + NUMBEROFINKS = 334, /* !number of inks */ + DOTRANGE = 336, /* !0% and 100% dot codes */ + TARGETPRINTER = 337, /* !separation target */ + EXTRASAMPLES = 338, /* !info about extra samples */ + SAMPLEFORMAT = 339, /* !data sample format */ + SMINSAMPLEVALUE = 340, /* !variable MinSampleValue */ + SMAXSAMPLEVALUE = 341, /* !variable MaxSampleValue */ + CLIPPATH = 343, /* %ClipPath [Adobe TIFF technote 2] */ + XCLIPPATHUNITS = 344, /* %XClipPathUnits [Adobe TIFF technote 2] */ + YCLIPPATHUNITS = 345, /* %YClipPathUnits [Adobe TIFF technote 2] */ + INDEXED = 346, /* %Indexed [Adobe TIFF Technote 3] */ + JPEGTABLES = 347, /* %JPEG table stream */ + OPIPROXY = 351, /* %OPI Proxy [Adobe TIFF technote] */ /* * Tags 512-521 are obsoleted by Technical Note #2 which specifies a * revised JPEG-in-TIFF scheme. */ - JPEGPROC=512, /* !JPEG processing algorithm */ - JPEGIFOFFSET=513, /* !pointer to SOI marker */ - JPEGIFBYTECOUNT=514, /* !JFIF stream length */ - JPEGRESTARTINTERVAL=515, /* !restart interval length */ - JPEGLOSSLESSPREDICTORS=517, /* !lossless proc predictor */ - JPEGPOINTTRANSFORM=518, /* !lossless point transform */ - JPEGQTABLES=519, /* !Q matrice offsets */ - JPEGDCTABLES=520, /* !DCT table offsets */ - JPEGACTABLES=521, /* !AC coefficient offsets */ - YCBCRCOEFFICIENTS=529, /* !RGB -> YCbCr transform */ - YCBCRSUBSAMPLING=530, /* !YCbCr subsampling factors */ - YCBCRPOSITIONING=531, /* !subsample positioning */ - REFERENCEBLACKWHITE=532, /* !colorimetry info */ - XMLPACKET=700, /* %XML packet [Adobe XMP Specification, January 2004 */ - OPIIMAGEID=32781, /* %OPI ImageID [Adobe TIFF technote] */ + JPEGPROC = 512, /* !JPEG processing algorithm */ + JPEGIFOFFSET = 513, /* !pointer to SOI marker */ + JPEGIFBYTECOUNT = 514, /* !JFIF stream length */ + JPEGRESTARTINTERVAL = 515, /* !restart interval length */ + JPEGLOSSLESSPREDICTORS = 517, /* !lossless proc predictor */ + JPEGPOINTTRANSFORM = 518, /* !lossless point transform */ + JPEGQTABLES = 519, /* !Q matrice offsets */ + JPEGDCTABLES = 520, /* !DCT table offsets */ + JPEGACTABLES = 521, /* !AC coefficient offsets */ + YCBCRCOEFFICIENTS = 529, /* !RGB -> YCbCr transform */ + YCBCRSUBSAMPLING = 530, /* !YCbCr subsampling factors */ + YCBCRPOSITIONING = 531, /* !subsample positioning */ + REFERENCEBLACKWHITE = 532, /* !colorimetry info */ + XMLPACKET = 700, /* %XML packet [Adobe XMP Specification, January 2004 */ + OPIIMAGEID = 32781, /* %OPI ImageID [Adobe TIFF technote] */ /* tags 32952-32956 are private tags registered to Island Graphics */ - REFPTS=32953, /* image reference points */ - REGIONTACKPOINT=32954, /* region-xform tack point */ - REGIONWARPCORNERS=32955, /* warp quadrilateral */ - REGIONAFFINE=32956, /* affine transformation mat */ + REFPTS = 32953, /* image reference points */ + REGIONTACKPOINT = 32954, /* region-xform tack point */ + REGIONWARPCORNERS = 32955, /* warp quadrilateral */ + REGIONAFFINE = 32956, /* affine transformation mat */ /* tags 32995-32999 are private tags registered to SGI */ - MATTEING=32995, /* $use ExtraSamples */ - DATATYPE=32996, /* $use SampleFormat */ - IMAGEDEPTH=32997, /* z depth of image */ - TILEDEPTH=32998, /* z depth/data tile */ + MATTEING = 32995, /* $use ExtraSamples */ + DATATYPE = 32996, /* $use SampleFormat */ + IMAGEDEPTH = 32997, /* z depth of image */ + TILEDEPTH = 32998, /* z depth/data tile */ /* tags 33300-33309 are private tags registered to Pixar */ /* @@ -554,297 +601,317 @@ private enum TiffTags:ushort { * The TIFFTAG_XPOSITION and TIFFTAG_YPOSITION can be used * to determine the position of the smaller image in the larger one. */ - PIXAR_IMAGEFULLWIDTH=33300, /* full image size in x */ - PIXAR_IMAGEFULLLENGTH=33301, /* full image size in y */ + PIXAR_IMAGEFULLWIDTH = 33300, /* full image size in x */ + PIXAR_IMAGEFULLLENGTH = 33301, /* full image size in y */ /* Tags 33302-33306 are used to identify special image modes and data * used by Pixar's texture formats. */ - PIXAR_TEXTUREFORMAT=33302, /* texture map format */ - PIXAR_WRAPMODES=33303, /* s & t wrap modes */ - PIXAR_FOVCOT=33304, /* cotan(fov) for env. maps */ - PIXAR_MATRIX_WORLDTOSCREEN=33305, - PIXAR_MATRIX_WORLDTOCAMERA=33306, + PIXAR_TEXTUREFORMAT = 33302, /* texture map format */ + PIXAR_WRAPMODES = 33303, /* s & t wrap modes */ + PIXAR_FOVCOT = 33304, /* cotan(fov) for env. maps */ + PIXAR_MATRIX_WORLDTOSCREEN = 33305, + PIXAR_MATRIX_WORLDTOCAMERA = 33306, /* tag 33405 is a private tag registered to Eastman Kodak */ - WRITERSERIALNUMBER=33405, /* device serial number */ + WRITERSERIALNUMBER = 33405, /* device serial number */ /* tag 33432 is listed in the 6.0 spec w/ unknown ownership */ - COPYRIGHT=33432, /* copyright string */ + COPYRIGHT = 33432, /* copyright string */ /* IPTC TAG from RichTIFF specifications */ - RICHTIFFIPTC=33723, + RICHTIFFIPTC = 33723, /* 34016-34029 are reserved for ANSI IT8 TIFF/IT */ - STONITS=37439, /* Sample value to Nits */ + STONITS = 37439, /* Sample value to Nits */ /* tag 34929 is a private tag registered to FedEx */ - FEDEX_EDR=34929, /* unknown use */ - INTEROPERABILITYIFD=40965, /* Pointer to Interoperability private directory */ + FEDEX_EDR = 34929, /* unknown use */ + INTEROPERABILITYIFD = 40965, /* Pointer to Interoperability private directory */ /* Adobe Digital Negative (DNG) format tags */ - DNGVERSION=50706, /* &DNG version number */ - DNGBACKWARDVERSION=50707, /* &DNG compatibility version */ - UNIQUECAMERAMODEL=50708, /* &name for the camera model */ - LOCALIZEDCAMERAMODEL=50709, /* &localized camera model name */ - CFAPLANECOLOR=50710, /* &CFAPattern->LinearRaw space mapping */ - CFALAYOUT=50711, /* &spatial layout of the CFA */ - LINEARIZATIONTABLE=50712, /* &lookup table description */ - BLACKLEVELREPEATDIM=50713, /* &repeat pattern size for the BlackLevel tag */ - BLACKLEVEL=50714, /* &zero light encoding level */ - BLACKLEVELDELTAH=50715, /* &zero light encoding level differences (columns) */ - BLACKLEVELDELTAV=50716, /* &zero light encoding level differences (rows) */ - WHITELEVEL=50717, /* &fully saturated encoding level */ - DEFAULTSCALE=50718, /* &default scale factors */ - DEFAULTCROPORIGIN=50719, /* &origin of the final image area */ - DEFAULTCROPSIZE=50720, /* &size of the final image area */ - COLORMATRIX1=50721, /* &XYZ->reference color space transformation matrix 1 */ - COLORMATRIX2=50722, /* &XYZ->reference color space transformation matrix 2 */ - CAMERACALIBRATION1=50723, /* &calibration matrix 1 */ - CAMERACALIBRATION2=50724, /* &calibration matrix 2 */ - REDUCTIONMATRIX1=50725, /* &dimensionality reduction matrix 1 */ - REDUCTIONMATRIX2=50726, /* &dimensionality reduction matrix 2 */ - ANALOGBALANCE=50727, /* &gain applied the stored raw values*/ - ASSHOTNEUTRAL=50728, /* &selected white balance in linear reference space */ - ASSHOTWHITEXY=50729, /* &selected white balance in x-y chromaticity coordinates */ - BASELINEEXPOSURE=50730, /* &how much to move the zero point */ - BASELINENOISE=50731, /* &relative noise level */ - BASELINESHARPNESS=50732, /* &relative amount of sharpening */ - BAYERGREENSPLIT=50733, /* &how closely the values of the green pixels in the blue/green rows track the values of the green pixels in the red/green rows */ - LINEARRESPONSELIMIT=50734, /* &non-linear encoding range */ - CAMERASERIALNUMBER=50735, /* &camera's serial number */ - LENSINFO=50736, /* info about the lens */ - CHROMABLURRADIUS=50737, /* &chroma blur radius */ - ANTIALIASSTRENGTH=50738, /* &relative strength of the camera's anti-alias filter */ - SHADOWSCALE=50739, /* &used by Adobe Camera Raw */ - DNGPRIVATEDATA=50740, /* &manufacturer's private data */ - MAKERNOTESAFETY=50741, /* &whether the EXIF MakerNote tag is safe to preserve along with the rest of the EXIF data */ - CALIBRATIONILLUMINANT1=50778, /* &illuminant 1 */ - CALIBRATIONILLUMINANT2=50779, /* &illuminant 2 */ - BESTQUALITYSCALE=50780, /* &best quality multiplier */ - RAWDATAUNIQUEID=50781, /* &unique identifier for the raw image data */ - ORIGINALRAWFILENAME=50827, /* &file name of the original raw file */ - ORIGINALRAWFILEDATA=50828, /* &contents of the original raw file */ - ACTIVEAREA=50829, /* &active (non-masked) pixels of the sensor */ - MASKEDAREAS=50830, /* &list of coordinates of fully masked pixels */ - ASSHOTICCPROFILE=50831, /* &these two tags used to */ - ASSHOTPREPROFILEMATRIX=50832, /* map cameras's color space into ICC profile space */ - CURRENTICCPROFILE=50833, /* & */ - CURRENTPREPROFILEMATRIX=50834, /* & */ + DNGVERSION = 50706, /* &DNG version number */ + DNGBACKWARDVERSION = 50707, /* &DNG compatibility version */ + UNIQUECAMERAMODEL = 50708, /* &name for the camera model */ + LOCALIZEDCAMERAMODEL = 50709, /* &localized camera model name */ + CFAPLANECOLOR = 50710, /* &CFAPattern->LinearRaw space mapping */ + CFALAYOUT = 50711, /* &spatial layout of the CFA */ + LINEARIZATIONTABLE = 50712, /* &lookup table description */ + BLACKLEVELREPEATDIM = 50713, /* &repeat pattern size for the BlackLevel tag */ + BLACKLEVEL = 50714, /* &zero light encoding level */ + BLACKLEVELDELTAH = 50715, /* &zero light encoding level differences (columns) */ + BLACKLEVELDELTAV = 50716, /* &zero light encoding level differences (rows) */ + WHITELEVEL = 50717, /* &fully saturated encoding level */ + DEFAULTSCALE = 50718, /* &default scale factors */ + DEFAULTCROPORIGIN = 50719, /* &origin of the final image area */ + DEFAULTCROPSIZE = 50720, /* &size of the final image area */ + COLORMATRIX1 = 50721, /* &XYZ->reference color space transformation matrix 1 */ + COLORMATRIX2 = 50722, /* &XYZ->reference color space transformation matrix 2 */ + CAMERACALIBRATION1 = 50723, /* &calibration matrix 1 */ + CAMERACALIBRATION2 = 50724, /* &calibration matrix 2 */ + REDUCTIONMATRIX1 = 50725, /* &dimensionality reduction matrix 1 */ + REDUCTIONMATRIX2 = 50726, /* &dimensionality reduction matrix 2 */ + ANALOGBALANCE = 50727, /* &gain applied the stored raw values*/ + ASSHOTNEUTRAL = 50728, /* &selected white balance in linear reference space */ + ASSHOTWHITEXY = 50729, /* &selected white balance in x-y chromaticity coordinates */ + BASELINEEXPOSURE = 50730, /* &how much to move the zero point */ + BASELINENOISE = 50731, /* &relative noise level */ + BASELINESHARPNESS = 50732, /* &relative amount of sharpening */ + BAYERGREENSPLIT = 50733, /* &how closely the values of the green pixels in the blue/green rows track the values of the green pixels in the red/green rows */ + LINEARRESPONSELIMIT = 50734, /* &non-linear encoding range */ + CAMERASERIALNUMBER = 50735, /* &camera's serial number */ + LENSINFO = 50736, /* info about the lens */ + CHROMABLURRADIUS = 50737, /* &chroma blur radius */ + ANTIALIASSTRENGTH = 50738, /* &relative strength of the camera's anti-alias filter */ + SHADOWSCALE = 50739, /* &used by Adobe Camera Raw */ + DNGPRIVATEDATA = 50740, /* &manufacturer's private data */ + MAKERNOTESAFETY = 50741, /* &whether the EXIF MakerNote tag is safe to preserve along with the rest of the EXIF data */ + CALIBRATIONILLUMINANT1 = 50778, /* &illuminant 1 */ + CALIBRATIONILLUMINANT2 = 50779, /* &illuminant 2 */ + BESTQUALITYSCALE = 50780, /* &best quality multiplier */ + RAWDATAUNIQUEID = 50781, /* &unique identifier for the raw image data */ + ORIGINALRAWFILENAME = 50827, /* &file name of the original raw file */ + ORIGINALRAWFILEDATA = 50828, /* &contents of the original raw file */ + ACTIVEAREA = 50829, /* &active (non-masked) pixels of the sensor */ + MASKEDAREAS = 50830, /* &list of coordinates of fully masked pixels */ + ASSHOTICCPROFILE = 50831, /* &these two tags used to */ + ASSHOTPREPROFILEMATRIX = 50832, /* map cameras's color space into ICC profile space */ + CURRENTICCPROFILE = 50833, /* & */ + CURRENTPREPROFILEMATRIX = 50834, /* & */ /* tag 65535 is an undefined tag used by Eastman Kodak */ - DCSHUESHIFTVALUES=65535 /* hue shift correction data */ + DCSHUESHIFTVALUES = 65535 /* hue shift correction data */ } #endregion - #region Не используется - - private enum SubFileTypeValues { - REDUCEDIMAGE=0x1, /* reduced resolution version */ - PAGE=0x2, /* one page of many */ - MASK=0x4, /* transparency mask */ - } - - private enum OSubFileTypeValues { - IMAGE=1, /* full resolution image data */ - REDUCEDIMAGE=2, /* reduced size image data */ - PAGE=3, /* one page of many */ - } - - private enum CompressionValues { - NONE=1, /* dump mode */ - CCITTRLE=2, /* CCITT modified Huffman RLE */ - CCITTFAX3=3, /* CCITT Group 3 fax encoding */ - CCITT_T4=3, /* CCITT T.4 (TIFF 6 name) */ - CCITTFAX4=4, /* CCITT Group 4 fax encoding */ - CCITT_T6=4, /* CCITT T.6 (TIFF 6 name) */ - LZW=5, /* Lempel-Ziv & Welch */ - OJPEG=6, /* !6.0 JPEG */ - JPEG=7, /* %JPEG DCT compression */ - NEXT=32766, /* NeXT 2-bit RLE */ - CCITTRLEW=32771, /* #1 w/ word alignment */ - PACKBITS=32773, /* Macintosh RLE */ - THUNDERSCAN=32809, /* ThunderScan RLE */ + #region Not used / Не используется + + private enum SubFileTypeValues + { + REDUCEDIMAGE = 0x1, /* reduced resolution version */ + PAGE = 0x2, /* one page of many */ + MASK = 0x4, /* transparency mask */ + } + + private enum OSubFileTypeValues + { + IMAGE = 1, /* full resolution image data */ + REDUCEDIMAGE = 2, /* reduced size image data */ + PAGE = 3, /* one page of many */ + } + + private enum CompressionValues + { + NONE = 1, /* dump mode */ + CCITTRLE = 2, /* CCITT modified Huffman RLE */ + CCITTFAX3 = 3, /* CCITT Group 3 fax encoding */ + CCITT_T4 = 3, /* CCITT T.4 (TIFF 6 name) */ + CCITTFAX4 = 4, /* CCITT Group 4 fax encoding */ + CCITT_T6 = 4, /* CCITT T.6 (TIFF 6 name) */ + LZW = 5, /* Lempel-Ziv & Welch */ + OJPEG = 6, /* !6.0 JPEG */ + JPEG = 7, /* %JPEG DCT compression */ + NEXT = 32766, /* NeXT 2-bit RLE */ + CCITTRLEW = 32771, /* #1 w/ word alignment */ + PACKBITS = 32773, /* Macintosh RLE */ + THUNDERSCAN = 32809, /* ThunderScan RLE */ /* codes 32895-32898 are reserved for ANSI IT8 TIFF/IT */ - DCS=32947, /* Kodak DCS encoding */ - JBIG=34661, /* ISO JBIG */ - SGILOG=34676, /* SGI Log Luminance RLE */ - SGILOG24=34677, /* SGI Log 24-bit packed */ - JP2000=34712, /* Leadtools JPEG2000 */ + DCS = 32947, /* Kodak DCS encoding */ + JBIG = 34661, /* ISO JBIG */ + SGILOG = 34676, /* SGI Log Luminance RLE */ + SGILOG24 = 34677, /* SGI Log 24-bit packed */ + JP2000 = 34712, /* Leadtools JPEG2000 */ } - private enum PhotoMetricValues { - MINISWHITE=0, /* min value is white */ - MINISBLACK=1, /* min value is black */ - RGB=2, /* RGB color model */ - PALETTE=3, /* color map indexed */ - MASK=4, /* $holdout mask */ - SEPARATED=5, /* !color separations */ - YCBCR=6, /* !CCIR 601 */ - CIELAB=8, /* !1976 CIE L*a*b* */ - ICCLAB=9, /* ICC L*a*b* [Adobe TIFF Technote 4] */ - ITULAB=10, /* ITU L*a*b* */ - LOGL=32844, /* CIE Log2(L) */ - LOGLUV=32845, /* CIE Log2(L) (u',v') */ + private enum PhotoMetricValues + { + MINISWHITE = 0, /* min value is white */ + MINISBLACK = 1, /* min value is black */ + RGB = 2, /* RGB color model */ + PALETTE = 3, /* color map indexed */ + MASK = 4, /* $holdout mask */ + SEPARATED = 5, /* !color separations */ + YCBCR = 6, /* !CCIR 601 */ + CIELAB = 8, /* !1976 CIE L*a*b* */ + ICCLAB = 9, /* ICC L*a*b* [Adobe TIFF Technote 4] */ + ITULAB = 10, /* ITU L*a*b* */ + LOGL = 32844, /* CIE Log2(L) */ + LOGLUV = 32845, /* CIE Log2(L) (u',v') */ } - private enum ThreshHoldingValues { - BILEVEL=1, /* b&w art scan */ - HALFTONE=2, /* or dithered scan */ - ERRORDIFFUSE=3, /* usually floyd-steinberg */ + private enum ThreshHoldingValues + { + BILEVEL = 1, /* b&w art scan */ + HALFTONE = 2, /* or dithered scan */ + ERRORDIFFUSE = 3, /* usually floyd-steinberg */ } - private enum FillOrderValues { - MSB2LSB=1, /* most significant -> least */ - LSB2MSB=2, /* least significant -> most */ + private enum FillOrderValues + { + MSB2LSB = 1, /* most significant -> least */ + LSB2MSB = 2, /* least significant -> most */ } - private enum OrientationValues { - TOPLEFT=1, /* row 0 top, col 0 lhs */ - TOPRIGHT=2, /* row 0 top, col 0 rhs */ - BOTRIGHT=3, /* row 0 bottom, col 0 rhs */ - BOTLEFT=4, /* row 0 bottom, col 0 lhs */ - LEFTTOP=5, /* row 0 lhs, col 0 top */ - RIGHTTOP=6, /* row 0 rhs, col 0 top */ - RIGHTBOT=7, /* row 0 rhs, col 0 bottom */ - LEFTBOT=8, /* row 0 lhs, col 0 bottom */ + private enum OrientationValues + { + TOPLEFT = 1, /* row 0 top, col 0 lhs */ + TOPRIGHT = 2, /* row 0 top, col 0 rhs */ + BOTRIGHT = 3, /* row 0 bottom, col 0 rhs */ + BOTLEFT = 4, /* row 0 bottom, col 0 lhs */ + LEFTTOP = 5, /* row 0 lhs, col 0 top */ + RIGHTTOP = 6, /* row 0 rhs, col 0 top */ + RIGHTBOT = 7, /* row 0 rhs, col 0 bottom */ + LEFTBOT = 8, /* row 0 lhs, col 0 bottom */ } - private enum PlanarConfigValues { - CONTIG=1, /* single image plane */ - SEPARATE=2, /* separate planes of data */ + private enum PlanarConfigValues + { + CONTIG = 1, /* single image plane */ + SEPARATE = 2, /* separate planes of data */ } - private enum GrayResponseUnitValues { - _10S=1, /* tenths of a unit */ - _100S=2, /* hundredths of a unit */ - _1000S=3, /* thousandths of a unit */ - _10000S=4, /* ten-thousandths of a unit */ - _100000S=5, /* hundred-thousandths */ + private enum GrayResponseUnitValues + { + _10S = 1, /* tenths of a unit */ + _100S = 2, /* hundredths of a unit */ + _1000S = 3, /* thousandths of a unit */ + _10000S = 4, /* ten-thousandths of a unit */ + _100000S = 5, /* hundred-thousandths */ } - private enum Group3OptionsValues { - _2DENCODING=0x1, /* 2-dimensional coding */ - UNCOMPRESSED=0x2, /* data not compressed */ - FILLBITS=0x4, /* fill to byte boundary */ + private enum Group3OptionsValues + { + _2DENCODING = 0x1, /* 2-dimensional coding */ + UNCOMPRESSED = 0x2, /* data not compressed */ + FILLBITS = 0x4, /* fill to byte boundary */ } - private enum Group4OptionsValues { - UNCOMPRESSED=0x2, /* data not compressed */ + private enum Group4OptionsValues + { + UNCOMPRESSED = 0x2, /* data not compressed */ } - private enum ResolutionUnitValues { - NONE=1, /* no meaningful units */ - INCH=2, /* english */ - CENTIMETER=3, /* metric */ + private enum ResolutionUnitValues + { + NONE = 1, /* no meaningful units */ + INCH = 2, /* english */ + CENTIMETER = 3, /* metric */ } - private enum ColorResponseUnitValues { - _10S=1, /* tenths of a unit */ - _100S=2, /* hundredths of a unit */ - _1000S=3, /* thousandths of a unit */ - _10000S=4, /* ten-thousandths of a unit */ - _100000S=5, /* hundred-thousandths */ + private enum ColorResponseUnitValues + { + _10S = 1, /* tenths of a unit */ + _100S = 2, /* hundredths of a unit */ + _1000S = 3, /* thousandths of a unit */ + _10000S = 4, /* ten-thousandths of a unit */ + _100000S = 5, /* hundred-thousandths */ } - private enum PredictorValues { - NONE=1, /* no prediction scheme used */ - HORIZONTAL=2, /* horizontal differencing */ - FLOATINGPOINT=3, /* floating point predictor */ + private enum PredictorValues + { + NONE = 1, /* no prediction scheme used */ + HORIZONTAL = 2, /* horizontal differencing */ + FLOATINGPOINT = 3, /* floating point predictor */ } - private enum CleanFaxDataValues { - CLEAN=0, /* no errors detected */ - REGENERATED=1, /* receiver regenerated lines */ - UNCLEAN=2, /* uncorrected errors exist */ + private enum CleanFaxDataValues + { + CLEAN = 0, /* no errors detected */ + REGENERATED = 1, /* receiver regenerated lines */ + UNCLEAN = 2, /* uncorrected errors exist */ } - private enum InkSetValues { - CMYK=1, /* !cyan-magenta-yellow-black color */ - MULTIINK=2, /* !multi-ink or hi-fi color */ + private enum InkSetValues + { + CMYK = 1, /* !cyan-magenta-yellow-black color */ + MULTIINK = 2, /* !multi-ink or hi-fi color */ } - private enum ExtraSamplesValues { - UNSPECIFIED=0, /* !unspecified data */ - ASSOCALPHA=1, /* !associated alpha data */ - UNASSALPHA=2, /* !unassociated alpha data */ + private enum ExtraSamplesValues + { + UNSPECIFIED = 0, /* !unspecified data */ + ASSOCALPHA = 1, /* !associated alpha data */ + UNASSALPHA = 2, /* !unassociated alpha data */ } - private enum SampleFormatValues { - UINT=1, /* !unsigned integer data */ - INT=2, /* !signed integer data */ - IEEEFP=3, /* !IEEE floating point data */ - VOID=4, /* !untyped data */ - COMPLEXINT=5, /* !complex signed int */ - COMPLEXIEEEFP=6, /* !complex ieee floating */ + private enum SampleFormatValues + { + UINT = 1, /* !unsigned integer data */ + INT = 2, /* !signed integer data */ + IEEEFP = 3, /* !IEEE floating point data */ + VOID = 4, /* !untyped data */ + COMPLEXINT = 5, /* !complex signed int */ + COMPLEXIEEEFP = 6, /* !complex ieee floating */ } - private enum JpegProcValues { - BASELINE=1, /* !baseline sequential */ - LOSSLESS=14, /* !Huffman coded lossless */ + private enum JpegProcValues + { + BASELINE = 1, /* !baseline sequential */ + LOSSLESS = 14, /* !Huffman coded lossless */ } - private enum YcbcrPositionINValues { - CENTERED=1, /* !as in PostScript Level 2 */ - COSITED=2, /* !as in CCIR 601-1 */ + private enum YcbcrPositionINValues + { + CENTERED = 1, /* !as in PostScript Level 2 */ + COSITED = 2, /* !as in CCIR 601-1 */ } #endregion } -} +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/Twain32.cs b/TownSuite.TwainScanner/Twain32.cs index 89c2885..896aadc 100644 --- a/TownSuite.TwainScanner/Twain32.cs +++ b/TownSuite.TwainScanner/Twain32.cs @@ -45,48 +45,51 @@ namespace TownSuite.TwainScanner { /// - /// Обеспечивает возможность работы с TWAIN-источниками. + /// Provides the ability to work with TWAIN sources. + /// Обеспечивает возможность работы с TWAIN-источниками. /// - [ToolboxBitmap(typeof(Twain32),"Resources.scanner.bmp")] + [ToolboxBitmap(typeof(Twain32), "Resources.scanner.bmp")] [DebuggerDisplay("ProductName = {_appid.ProductName.Value}, Version = {_appid.Version.Info}, DS = {_srcds.ProductName}")] [DefaultEvent("AcquireCompleted")] [DefaultProperty("AppProductName")] - public sealed class Twain32:Component { + public sealed class Twain32 : Component + { private _DsmEntry _dsmEntry; - private IntPtr _hTwainDll; //дескриптор модуля twain_32.dll - private IContainer _components=new Container(); - private IntPtr _hwnd; //дескриптор родительского окна. - private TwIdentity _appid; //идентификатор приложения. - private TwIdentity _srcds; //идентификатор текущего источника данных. - private _MessageFilter _filter; //фильтр событий WIN32 - private TwIdentity[] _sources=new TwIdentity[0]; //массив доступных источников данных. - private ApplicationContext _context=null; //контекст приложения. используется в случае отсутствия основного цикла обработки сообщений. - private Collection<_Image> _images=new Collection<_Image>(); + private IntPtr _hTwainDll; //module descriptor twain_32.dll / дескриптор модуля twain_32.dll + private IContainer _components = new Container(); + private IntPtr _hwnd; //handle to the parent window / дескриптор родительского окна. + private TwIdentity _appid; //application identifier / идентификатор приложения. + private TwIdentity _srcds; //identifier of the current data source / идентификатор текущего источника данных. + private _MessageFilter _filter; //WIN32 event filter / фильтр событий WIN32 + private TwIdentity[] _sources = new TwIdentity[0]; //an array of available data sources / массив доступных источников данных. + private ApplicationContext _context = null; //application context. used if there is no main message processing cycle / контекст приложения. используется в случае отсутствия основного цикла обработки сообщений. + private Collection<_Image> _images = new Collection<_Image>(); private TwainStateFlag _twainState; - private bool _isTwain2Enable=IntPtr.Size!=4||Environment.OSVersion.Platform==PlatformID.Unix; + private bool _isTwain2Enable = IntPtr.Size != 4 || Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX; private CallBackProc _callbackProc; private TwainCapabilities _capabilities; /// /// Initializes a new instance of the class. /// - public Twain32() { - this._srcds=new TwIdentity(); - this._srcds.Id=0; - this._filter=new _MessageFilter(this); - this.ShowUI=true; - this.DisableAfterAcquire=true; - this.Palette=new TwainPalette(this); - this._callbackProc=this._TwCallbackProc; - switch(Environment.OSVersion.Platform) { + public Twain32() + { + this._srcds = new TwIdentity(); + this._srcds.Id = 0; + this._filter = new _MessageFilter(this); + this.ShowUI = true; + this.DisableAfterAcquire = true; + this.Palette = new TwainPalette(this); + this._callbackProc = this._TwCallbackProc; + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - break; case PlatformID.MacOSX: - throw new NotImplementedException(); + break; default: - var _window=new System.Windows.Forms.Form(); + Form _window = new Form(); this._components.Add(_window); - this._hwnd=_window.Handle; + this._hwnd = _window.Handle; break; } } @@ -95,7 +98,8 @@ public Twain32() { /// Initializes a new instance of the class. /// /// The container. - public Twain32(IContainer container):this() { + public Twain32(IContainer container) : this() + { container.Add(this); } @@ -103,20 +107,23 @@ public Twain32(IContainer container):this() { /// Releases the unmanaged resources used by the and optionally releases the managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected override void Dispose(bool disposing) { - if(disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { this.CloseDSM(); - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - break; case PlatformID.MacOSX: - throw new NotImplementedException(); + break; default: this._filter.Dispose(); break; } this._UnloadDSM(); - if(this._components!=null) { + if (this._components != null) + { this._components.Dispose(); } } @@ -124,171 +131,227 @@ protected override void Dispose(bool disposing) { } /// - /// Открывает менеджер источников данных. + /// Opens the data source manager + /// Открывает менеджер источников данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - public bool OpenDSM() { - if((this._TwainState&TwainStateFlag.DSMOpen)==0) { + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + public bool OpenDSM() + { + if ((this._TwainState & TwainStateFlag.DSMOpen) == 0) + { - #region Загружаем DSM, получаем адрес точки входа DSM_Entry и приводим ее к соответствующим делегатам + #region We load DSM, we receive the address of the entry point DSM_Entry and we bring it to the appropriate delegates / Загружаем DSM, получаем адрес точки входа DSM_Entry и приводим ее к соответствующим делегатам - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - this._hTwainDll=_Platform.Load("/usr/local/lib/libtwaindsm.so"); - break; case PlatformID.MacOSX: - throw new NotImplementedException(); + this._dsmEntry = _DsmEntry.Create(IntPtr.Zero); + try + { + if (this._dsmEntry.DsmRaw == null) + { + throw new InvalidOperationException("Can't load DSM."); + } + } + catch (Exception ex) + { + throw new TwainException("Can't load DSM.", ex); + } + break; default: - string _twainDsm=Path.ChangeExtension(Path.Combine(Environment.SystemDirectory,"TWAINDSM"),".dll"); - this._hTwainDll=_Platform.Load(File.Exists(_twainDsm)&&this.IsTwain2Enable?_twainDsm:Path.ChangeExtension(Path.Combine(Environment.SystemDirectory,"..\\twain_32"),".dll")); - if(this.Parent!=null) { - this._hwnd=this.Parent.Handle; + string _twainDsm = Path.ChangeExtension(Path.Combine(Environment.SystemDirectory, "TWAINDSM"), ".dll"); + this._hTwainDll = _Platform.Load(File.Exists(_twainDsm) && this.IsTwain2Enable ? _twainDsm : Path.ChangeExtension(Path.Combine(Environment.SystemDirectory, "..\\twain_32"), ".dll")); + if (this.Parent != null) + { + this._hwnd = this.Parent.Handle; + } + if (this._hTwainDll != IntPtr.Zero) + { + IntPtr _pDsmEntry = _Platform.GetProcAddr(this._hTwainDll, "DSM_Entry"); + if (_pDsmEntry != IntPtr.Zero) + { + this._dsmEntry = _DsmEntry.Create(_pDsmEntry); + _Memory._SetEntryPoints(null); + } + else + { + throw new TwainException("Can't find DSM_Entry entry point."); + } + } + else + { + throw new TwainException("Can't load DSM."); } break; } - if(this._hTwainDll!=IntPtr.Zero) { - IntPtr _pDsmEntry=_Platform.GetProcAddr(this._hTwainDll,"DSM_Entry"); - if(_pDsmEntry!=IntPtr.Zero) { - this._dsmEntry=_DsmEntry.Create(_pDsmEntry); - _Memory._SetEntryPoints(null); - } else { - throw new TwainException("Cann't find DSM_Entry entry point."); - } - } else { - throw new TwainException("Cann't load DSM."); - } #endregion - for(TwRC _rc=this._dsmEntry.DsmParent(this._AppId,IntPtr.Zero,TwDG.Control,TwDAT.Parent,TwMSG.OpenDSM,ref this._hwnd); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsmParent(this._AppId, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.OpenDSM, ref this._hwnd); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - this._TwainState|=TwainStateFlag.DSMOpen; + this._TwainState |= TwainStateFlag.DSMOpen; - if(this.IsTwain2Supported) { - TwEntryPoint _entry=new TwEntryPoint(); - for(TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.EntryPoint,TwMSG.Get,ref _entry); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + if (this.IsTwain2Supported) + { + TwEntryPoint _entry = new TwEntryPoint(); + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.EntryPoint, TwMSG.Get, ref _entry); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } _Memory._SetEntryPoints(_entry); } this._GetAllSorces(); } - return (this._TwainState&TwainStateFlag.DSMOpen)!=0; + return (this._TwainState & TwainStateFlag.DSMOpen) != 0; } /// - /// Отображает диалоговое окно для выбора источника данных. + /// Displays a dialog box for selecting a data source. + /// Отображает диалоговое окно для выбора источника данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - public bool SelectSource() { - if(Environment.OSVersion.Platform==PlatformID.Unix) { + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + public bool SelectSource() + { + if (Environment.OSVersion.Platform == PlatformID.Unix) + { throw new NotSupportedException("DG_CONTROL / DAT_IDENTITY / MSG_USERSELECT is not available on Linux."); } - if((this._TwainState&TwainStateFlag.DSOpen)==0) { - if((this._TwainState&TwainStateFlag.DSMOpen)==0) { + if ((this._TwainState & TwainStateFlag.DSOpen) == 0) + { + if ((this._TwainState & TwainStateFlag.DSMOpen) == 0) + { this.OpenDSM(); - if((this._TwainState&TwainStateFlag.DSMOpen)==0) { + if ((this._TwainState & TwainStateFlag.DSMOpen) == 0) + { return false; } } - TwIdentity _src=new TwIdentity(); - for(TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.UserSelect,ref _src); _rc!=TwRC.Success; ) { - if(_rc==TwRC.Cancel) { + TwIdentity _src = new TwIdentity(); + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.UserSelect, ref _src); _rc != TwRC.Success;) + { + if (_rc == TwRC.Cancel) + { return false; } - throw new TwainException(this._GetTwainStatus(),_rc); + throw new TwainException(this._GetTwainStatus(), _rc); } - this._srcds=_src; + this._srcds = _src; return true; } return false; } /// - /// Открывает источник данных. + /// Opens a data source. + /// Открывает источник данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - public bool OpenDataSource() { - if((this._TwainState&TwainStateFlag.DSMOpen)!=0 && (this._TwainState&TwainStateFlag.DSOpen)==0) { - for(TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.OpenDS,ref this._srcds); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + public bool OpenDataSource() + { + if ((this._TwainState & TwainStateFlag.DSMOpen) != 0 && (this._TwainState & TwainStateFlag.DSOpen) == 0) + { + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.OpenDS, ref this._srcds); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - this._TwainState|=TwainStateFlag.DSOpen; + this._TwainState |= TwainStateFlag.DSOpen; - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: + case PlatformID.MacOSX: this._RegisterCallback(); break; - case PlatformID.MacOSX: - throw new NotImplementedException(); default: - if(this.IsTwain2Supported&&(this._srcds.SupportedGroups&TwDG.DS2)!=0) { + if (this.IsTwain2Supported && (this._srcds.SupportedGroups & TwDG.DS2) != 0) + { this._RegisterCallback(); } break; } } - return (this._TwainState&TwainStateFlag.DSOpen)!=0; + return (this._TwainState & TwainStateFlag.DSOpen) != 0; } /// - /// Регестрирует обработчик событий источника данных. + /// Registers a data source event handler. + /// Регестрирует обработчик событий источника данных. /// - private void _RegisterCallback() { - TwCallback2 _callback=new TwCallback2 { - CallBackProc=this._callbackProc + private void _RegisterCallback() + { + TwCallback2 _callback = new TwCallback2 + { + CallBackProc = this._callbackProc }; - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Callback2,TwMSG.RegisterCallback,ref _callback); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Callback2, TwMSG.RegisterCallback, ref _callback); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } } /// - /// Активирует источник данных. + /// Activates a data source. + /// Активирует источник данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - private bool _EnableDataSource() { - if((this._TwainState&TwainStateFlag.DSOpen)!=0 && (this._TwainState&TwainStateFlag.DSEnabled)==0) { - TwUserInterface _guif=new TwUserInterface() { - ShowUI=this.ShowUI, - ModalUI=this.ModalUI, - ParentHand=this._hwnd + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + private bool _EnableDataSource() + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0 && (this._TwainState & TwainStateFlag.DSEnabled) == 0) + { + TwUserInterface _guif = new TwUserInterface() + { + ShowUI = this.ShowUI, + ModalUI = this.ModalUI, + ParentHand = this._hwnd }; - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.UserInterface,TwMSG.EnableDS,ref _guif); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.EnableDS, ref _guif); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); + } + if ((this._TwainState & TwainStateFlag.DSReady) != 0) + { + this._TwainState &= ~TwainStateFlag.DSReady; } - if((this._TwainState&TwainStateFlag.DSReady)!=0) { - this._TwainState&=~TwainStateFlag.DSReady; - } else { - this._TwainState|=TwainStateFlag.DSEnabled; + else + { + this._TwainState |= TwainStateFlag.DSEnabled; } } - return (this._TwainState&TwainStateFlag.DSEnabled)!=0; + return (this._TwainState & TwainStateFlag.DSEnabled) != 0; } /// - /// Получает изображение с источника данных. + /// Gets an image from a data source. + /// Получает изображение с источника данных. /// - public void Acquire() { - if(this.OpenDSM()) { - if(this.OpenDataSource()) { - if(this._EnableDataSource()) { - switch(Environment.OSVersion.Platform) { + public void Acquire() + { + if (this.OpenDSM()) + { + if (this.OpenDataSource()) + { + if (this._EnableDataSource()) + { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - break; case PlatformID.MacOSX: - throw new NotImplementedException(); + break; default: - if(!this.IsTwain2Supported||(this._srcds.SupportedGroups&TwDG.DS2)==0) { + if (!this.IsTwain2Supported || (this._srcds.SupportedGroups & TwDG.DS2) == 0) + { this._filter.SetFilter(); } - if(!Application.MessageLoop) { - Application.Run(this._context=new ApplicationContext()); + if (!Application.MessageLoop) + { + Application.Run(this._context = new ApplicationContext()); } break; } @@ -298,247 +361,326 @@ public void Acquire() { } /// - /// Деактивирует источник данных. + /// Deactivates the data source. + /// Деактивирует источник данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - private bool _DisableDataSource() { - if((this._TwainState&TwainStateFlag.DSEnabled)!=0) { - try { - TwUserInterface _guif=new TwUserInterface() { - ParentHand=this._hwnd, - ShowUI=false + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + private bool _DisableDataSource() + { + if ((this._TwainState & TwainStateFlag.DSEnabled) != 0) + { + try + { + TwUserInterface _guif = new TwUserInterface() + { + ParentHand = this._hwnd, + ShowUI = false }; - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.UserInterface,TwMSG.DisableDS,ref _guif); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.DisableDS, ref _guif); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } finally { - this._TwainState&=~TwainStateFlag.DSEnabled; - if(this._context!=null) { + } + finally + { + this._TwainState &= ~TwainStateFlag.DSEnabled; + if (this._context != null) + { this._context.ExitThread(); this._context.Dispose(); - this._context=null; + this._context = null; } } - return (this._TwainState&TwainStateFlag.DSEnabled)==0; + return (this._TwainState & TwainStateFlag.DSEnabled) == 0; } return false; } /// - /// Закрывает источник данных. + /// Closes the data source. + /// Закрывает источник данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - public bool CloseDataSource() { - if((this._TwainState&TwainStateFlag.DSOpen)!=0 && (this._TwainState&TwainStateFlag.DSEnabled)==0) { + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + public bool CloseDataSource() + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0 && (this._TwainState & TwainStateFlag.DSEnabled) == 0) + { this._images.Clear(); - for(TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.CloseDS,ref this._srcds); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.CloseDS, ref this._srcds); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - this._TwainState&=~TwainStateFlag.DSOpen; - return (this._TwainState&TwainStateFlag.DSOpen)==0; + this._TwainState &= ~TwainStateFlag.DSOpen; + return (this._TwainState & TwainStateFlag.DSOpen) == 0; } return false; } /// - /// Закрывает менежер источников данных. + /// Closes the data source manager. + /// Закрывает менежер источников данных. /// - /// Истина, если операция прошла удачно; иначе, лож. - public bool CloseDSM() { - if((this._TwainState&TwainStateFlag.DSEnabled)!=0) { + /// True if the operation was successful; otherwise, false.Истина, если операция прошла удачно; иначе, лож. + public bool CloseDSM() + { + if ((this._TwainState & TwainStateFlag.DSEnabled) != 0) + { this._DisableDataSource(); } - if((this._TwainState&TwainStateFlag.DSOpen)!=0) { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { this.CloseDataSource(); } - if((this._TwainState&TwainStateFlag.DSMOpen)!=0&&(this._TwainState&TwainStateFlag.DSOpen)==0) { - for(TwRC _rc=this._dsmEntry.DsmParent(this._AppId,IntPtr.Zero,TwDG.Control,TwDAT.Parent,TwMSG.CloseDSM,ref this._hwnd); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + if ((this._TwainState & TwainStateFlag.DSMOpen) != 0 && (this._TwainState & TwainStateFlag.DSOpen) == 0) + { + for (TwRC _rc = this._dsmEntry.DsmParent(this._AppId, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.CloseDSM, ref this._hwnd); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - this._TwainState&=~TwainStateFlag.DSMOpen; + this._TwainState &= ~TwainStateFlag.DSMOpen; this._UnloadDSM(); - return (this._TwainState&TwainStateFlag.DSMOpen)==0; + return (this._TwainState & TwainStateFlag.DSMOpen) == 0; } return false; } - private void _UnloadDSM() { - this._AppId=null; - if(this._hTwainDll!=IntPtr.Zero) { + private void _UnloadDSM() + { + this._AppId = null; + if (this._hTwainDll != IntPtr.Zero) + { _Platform.Unload(this._hTwainDll); - this._hTwainDll=IntPtr.Zero; + this._hTwainDll = IntPtr.Zero; } } /// - /// Возвращает отсканированое изображение. + /// Returns the scanned image. + /// Возвращает отсканированое изображение. /// - /// Индекс изображения. - /// Экземпляр изображения. - public Image GetImage(int index) { - return this._images[index]; - } + /// Image index.Индекс изображения. + /// Instance of the image.Экземпляр изображения. + public Image GetImage(int index) => this._images[index]; /// - /// Возвращает количество отсканированных изображений. + /// Returns the number of scanned images. + /// Возвращает количество отсканированных изображений. /// [Browsable(false)] - public int ImageCount { - get { - return this._images.Count; - } - } + public int ImageCount => this._images.Count; /// - /// Возвращает или устанавливает значение, указывающее на необходимость деактивации источника данных после получения изображения. + /// Gets or sets a value indicating the need to deactivate the data source after receiving the image. + /// Возвращает или устанавливает значение, указывающее на необходимость деактивации источника данных после получения изображения. /// [DefaultValue(true)] [Category("Behavior")] - [Description("Возвращает или устанавливает значение, указывающее на необходимость деактивации источника данных после получения изображения.")] - public bool DisableAfterAcquire { - get; - set; - } + [Description("Gets or sets a value indicating the need to deactivate the data source after receiving the image. Возвращает или устанавливает значение, указывающее на необходимость деактивации источника данных после получения изображения.")] + public bool DisableAfterAcquire { get; set; } /// - /// Возвращает или устанавливает значение, указывающее на необходимость использования TWAIN 2.0. + /// Gets or sets a value indicating whether to use TWAIN 2.0. + /// Возвращает или устанавливает значение, указывающее на необходимость использования TWAIN 2.0. /// [DefaultValue(false)] [Category("Behavior")] - [Description("Возвращает или устанавливает значение, указывающее на необходимость использования TWAIN 2.0.")] - public bool IsTwain2Enable { - get { + [Description("Gets or sets a value indicating whether to use TWAIN 2.0. Возвращает или устанавливает значение, указывающее на необходимость использования TWAIN 2.0.")] + public bool IsTwain2Enable + { + get + { return this._isTwain2Enable; } - set { - if((this._TwainState&TwainStateFlag.DSMOpen)!=0) { + set + { + if ((this._TwainState & TwainStateFlag.DSMOpen) != 0) + { throw new InvalidOperationException("DSM already opened."); } - if(IntPtr.Size!=4&&!value) { + if (IntPtr.Size != 4 && !value) + { throw new InvalidOperationException("In x64 mode only TWAIN 2.x enabled."); } - if(Environment.OSVersion.Platform==PlatformID.Unix&&!value) { + if (Environment.OSVersion.Platform == PlatformID.Unix && !value) + { throw new InvalidOperationException("On UNIX platform only TWAIN 2.x enabled."); } - if(Environment.OSVersion.Platform==PlatformID.MacOSX) { - throw new NotImplementedException(); + if (Environment.OSVersion.Platform == PlatformID.MacOSX && !value) + { + throw new InvalidOperationException("On MacOSX platform only TWAIN 2.x enabled."); } - if(this._isTwain2Enable=value) { - this._AppId.SupportedGroups|=TwDG.APP2; - } else { - this._AppId.SupportedGroups&=~TwDG.APP2; + if (this._isTwain2Enable = value) + { + this._AppId.SupportedGroups |= TwDG.APP2; } - this._AppId.ProtocolMajor=(ushort)(this._isTwain2Enable?2:1); - this._AppId.ProtocolMinor=(ushort)(this._isTwain2Enable?3:9); + else + { + this._AppId.SupportedGroups &= ~TwDG.APP2; + } + this._AppId.ProtocolMajor = (ushort)(this._isTwain2Enable ? 2 : 1); + this._AppId.ProtocolMinor = (ushort)(this._isTwain2Enable ? 3 : 9); } } /// - /// Возвращает истину, если DSM поддерживает TWAIN 2.0; иначе лож. + /// Returns true if DSM supports TWAIN 2.0; otherwise false. + /// Возвращает истину, если DSM поддерживает TWAIN 2.0; иначе лож. /// [Browsable(false)] - public bool IsTwain2Supported { - get { - if((this._TwainState&TwainStateFlag.DSMOpen)==0) { + public bool IsTwain2Supported + { + get + { + if ((this._TwainState & TwainStateFlag.DSMOpen) == 0) + { throw new InvalidOperationException("DSM is not open."); } - return (this._AppId.SupportedGroups&TwDG.DSM2)!=0; + return (this._AppId.SupportedGroups & TwDG.DSM2) != 0; } } #region Information of sorces /// - /// Возвращает или устанавливает индекс текущего источника данных. + /// Gets or sets the index of the current data source. + /// Возвращает или устанавливает индекс текущего источника данных. /// [Browsable(false)] [ReadOnly(true)] - public int SourceIndex { - get { - if((this._TwainState&TwainStateFlag.DSMOpen)!=0) { + public int SourceIndex + { + get + { + if ((this._TwainState & TwainStateFlag.DSMOpen) != 0) + { int i; - for(i=0;i - /// Возвращает количество источников данных. + /// Returns the number of data sources. + /// Возвращает количество источников данных. /// [Browsable(false)] - public int SourcesCount { - get { - return this._sources.Length; - } - } + public int SourcesCount => this._sources.Length; /// - /// Возвращает имя источника данных по указанному индексу. + /// Returns the name of the data source at the specified index. + /// Возвращает имя источника данных по указанному индексу. /// - /// Индекс. - /// Имя источника данных. - public string GetSourceProductName(int index) { - return this._sources[index].ProductName; - - } + /// Index.Индекс. + /// The name of the data source.Имя источника данных. + public string GetSourceProductName(int index) => this._sources[index].ProductName; /// - /// Возвращает описание указанного источника. Gets the source identity. + /// Gets a description of the specified source. + /// Возвращает описание указанного источника. Gets the source identity. /// - /// Индекс. The index. - /// Описание источника данных. - public Identity GetSourceIdentity(int index) { - return new Identity(this._sources[index]); - } + /// Index.Индекс. The index. + /// Description of the data source.Описание источника данных. + public Identity GetSourceIdentity(int index) => new Identity(this._sources[index]); + + /// + /// Returns true if the specified source supports TWAIN 2.0; otherwise false. + /// Возвращает истину, если указанный источник поддерживает TWAIN 2.0; иначе лож. + /// + /// IndexИндекс. + /// True if the specified source supports TWAIN 2.0; otherwise false.Истина, если указанный источник поддерживает TWAIN 2.0; иначе лож. + public bool GetIsSourceTwain2Compatible(int index) => (this._sources[index].SupportedGroups & TwDG.DS2) != 0; /// - /// Возвращает истину, если указанный источник поддерживает TWAIN 2.0; иначе лож. + /// Sets the specified data source as the default data source. + /// Устанавливает указанный источник данных в качестве источника данных по умолчанию. /// - /// Индекс. - /// Истина, если указанный источник поддерживает TWAIN 2.0; иначе лож. - public bool GetIsSourceTwain2Compatible(int index) { - return (this._sources[index].SupportedGroups&TwDG.DS2)!=0; - + /// Index.Индекс. + public void SetDefaultSource(int index) + { + if ((this._TwainState & TwainStateFlag.DSMOpen) != 0) + { + if ((this._TwainState & TwainStateFlag.DSOpen) == 0) + { + TwIdentity _src = this._sources[index]; + TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.Set, ref _src); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); + } + } + else + { + throw new TwainException("The data source is already open. You must first close the data source."); + } + } + else + { + throw new TwainException("DSM is not open."); + } } /// - /// Устанавливает указанный источник данных в качестве источника данных по умолчанию. + /// Gets the default Data Source. /// - /// Индекс. - public void SetDefaultSource(int index) { - if((this._TwainState&TwainStateFlag.DSMOpen)!=0) { - if((this._TwainState&TwainStateFlag.DSOpen)==0) { - TwIdentity _src=this._sources[index]; - TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.Set,ref _src); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + /// Index of default Data Source. + /// + /// Не удалось найти источник данных по умолчанию. + /// or + /// DSM не открыт. + /// + public int GetDefaultSource() + { + if ((this._TwainState & TwainStateFlag.DSMOpen) != 0) + { + TwIdentity _identity = new TwIdentity(); + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.GetDefault, ref _identity); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); + } + for (var i = 0; i < this._sources.Length; i++) + { + if (_identity.Id == this._sources[i].Id) + { + return i; } - } else { - throw new TwainException("Источник данных уже открыт. Необходимо сперва закрыть источник данных."); } - } else { - throw new TwainException("DSM не открыт."); + throw new TwainException("Could not find default data source."); + } + else + { + throw new TwainException("DSM is not open."); } } @@ -547,283 +689,253 @@ public void SetDefaultSource(int index) { #region Properties of source /// - /// Возвращает идентификатор приложения. + /// Gets the application identifier. + /// Возвращает идентификатор приложения. /// [Browsable(false)] [ReadOnly(true)] - private TwIdentity _AppId { - get{ - if(this._appid==null) { - Assembly _asm=typeof(Twain32).Assembly; - AssemblyName _asm_name=new AssemblyName(_asm.FullName); - Version _version=new Version(((AssemblyFileVersionAttribute)_asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute),false)[0]).Version); - - this._appid=new TwIdentity() { - Id=0, - Version=new TwVersion() { - MajorNum=(ushort)_version.Major, - MinorNum=(ushort)_version.Minor, - Language=TwLanguage.RUSSIAN, - Country=TwCountry.BELARUS, - Info=_asm_name.Version.ToString() + private TwIdentity _AppId + { + get + { + if (this._appid == null) + { + Assembly _asm = typeof(Twain32).Assembly; + AssemblyName _asm_name = new AssemblyName(_asm.FullName); + Version _version = new Version(((AssemblyFileVersionAttribute)_asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)[0]).Version); + + this._appid = new TwIdentity() + { + Id = 0, + Version = new TwVersion() + { + MajorNum = (ushort)_version.Major, + MinorNum = (ushort)_version.Minor, + Language = TwLanguage.RUSSIAN, + Country = TwCountry.BELARUS, + Info = _asm_name.Version.ToString() }, - ProtocolMajor=(ushort)(this._isTwain2Enable?2:1), - ProtocolMinor=(ushort)(this._isTwain2Enable?3:9), - SupportedGroups=TwDG.Image|TwDG.Control|(this._isTwain2Enable?TwDG.APP2:0), - Manufacturer=((AssemblyCompanyAttribute)_asm.GetCustomAttributes(typeof(AssemblyCompanyAttribute),false)[0]).Company, - ProductFamily="TWAIN Class Library", - ProductName=((AssemblyProductAttribute)_asm.GetCustomAttributes(typeof(AssemblyProductAttribute),false)[0]).Product + ProtocolMajor = (ushort)(this._isTwain2Enable ? 2 : 1), + ProtocolMinor = (ushort)(this._isTwain2Enable ? 3 : 9), + SupportedGroups = TwDG.Image | TwDG.Control | (this._isTwain2Enable ? TwDG.APP2 : 0), + Manufacturer = ((AssemblyCompanyAttribute)_asm.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false)[0]).Company, + ProductFamily = "TWAIN Class Library", + ProductName = ((AssemblyProductAttribute)_asm.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0]).Product }; } return this._appid; } - set { - if(value!=null) { + set + { + if (value != null) + { throw new ArgumentException("Is read only property."); } - this._appid=null; + this._appid = null; } } /// - /// Возвращает или устанавливает имя приложения. + /// Gets or sets the name of the application. + /// Возвращает или устанавливает имя приложения. /// [Category("Behavior")] - [Description("Возвращает или устанавливает имя приложения.")] - public string AppProductName { - get { + [Description("Gets or sets the name of the application. Возвращает или устанавливает имя приложения.")] + public string AppProductName + { + get + { return this._AppId.ProductName; } - set { - this._AppId.ProductName=value; + set + { + this._AppId.ProductName = value; } } /// - /// Возвращает или устанавливает значение указывающие на необходимость отображения UI TWAIN-источника. + /// Gets or sets a value indicating whether to display the UI of the TWAIN source. + /// Возвращает или устанавливает значение указывающие на необходимость отображения UI TWAIN-источника. /// [Category("Behavior")] [DefaultValue(true)] - [Description("Возвращает или устанавливает значение указывающие на необходимость отображения UI TWAIN-источника.")] - public bool ShowUI { - get; - set; - } + [Description("Gets or sets a value indicating whether to display the UI of the TWAIN source. Возвращает или устанавливает значение указывающие на необходимость отображения UI TWAIN-источника.")] + public bool ShowUI { get; set; } [Category("Behavior")] [DefaultValue(false)] - private bool ModalUI { - get; - set; - } + private bool ModalUI { get; set; } /// - /// Возвращает или устанавливает родительское окно для TWAIN-источника. + /// Gets or sets the parent window for the TWAIN source. + /// Возвращает или устанавливает родительское окно для TWAIN-источника. /// /// /// Окно. /// [Category("Behavior")] [DefaultValue(false)] - [Description("Возвращает или устанавливает родительское окно для TWAIN-источника.")] - public IWin32Window Parent { - get; - set; - } + [Description("Gets or sets the parent window for the TWAIN source. Возвращает или устанавливает родительское окно для TWAIN-источника.")] + public IWin32Window Parent { get; set; } /// - /// Возвращает или устанавливает используемый приложением язык. Get or set the primary language for your application. + /// Get or set the primary language for your application. + /// Возвращает или устанавливает используемый приложением язык. /// [Category("Culture")] [DefaultValue(TwLanguage.RUSSIAN)] - [Description("Возвращает или устанавливает используемый приложением язык. Get or set the primary language for your application.")] - public TwLanguage Language { - get { + [Description("Get or set the primary language for your application. Возвращает или устанавливает используемый приложением язык.")] + public TwLanguage Language + { + get + { return this._AppId.Version.Language; } - set { - this._AppId.Version.Language=value; + set + { + this._AppId.Version.Language = value; } } /// - /// Возвращает или устанавливает страну происхождения приложения. Get or set the primary country where your application is intended to be distributed. + /// Get or set the primary country where your application is intended to be distributed. + /// Возвращает или устанавливает страну происхождения приложения. /// [Category("Culture")] [DefaultValue(TwCountry.BELARUS)] - [Description("Возвращает или устанавливает страну происхождения приложения. Get or set the primary country where your application is intended to be distributed.")] - public TwCountry Country { - get { + [Description("Get or set the primary country where your application is intended to be distributed. Возвращает или устанавливает страну происхождения приложения.")] + public TwCountry Country + { + get + { return this._AppId.Version.Country; } - set { - this._AppId.Version.Country=value; + set + { + this._AppId.Version.Country = value; } } /// - /// Возвращает или устанавливает кадр физического расположения изображения. + /// Gets or sets the frame of the physical location of the image. + /// Возвращает или устанавливает кадр физического расположения изображения. /// [Browsable(false)] [ReadOnly(true)] - public RectangleF ImageLayout { - get { - TwImageLayout _imageLayout=new TwImageLayout(); - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Image,TwDAT.ImageLayout,TwMSG.Get,ref _imageLayout); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + public RectangleF ImageLayout + { + get + { + TwImageLayout _imageLayout = new TwImageLayout(); + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Image, TwDAT.ImageLayout, TwMSG.Get, ref _imageLayout); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } return _imageLayout.Frame; } - set { - TwImageLayout _imageLayout=new TwImageLayout{Frame=value}; - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Image,TwDAT.ImageLayout,TwMSG.Set,ref _imageLayout); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + set + { + TwImageLayout _imageLayout = new TwImageLayout { Frame = value }; + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Image, TwDAT.ImageLayout, TwMSG.Set, ref _imageLayout); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } } } /// - /// Возвращает набор возможностей (Capabilities). + /// Returns a set of capabilities (Capabilities). + /// Возвращает набор возможностей (Capabilities). /// [Browsable(false)] [ReadOnly(true)] - public TwainCapabilities Capabilities { - get { - if(this._capabilities==null) { - this._capabilities=new TwainCapabilities(this); + public TwainCapabilities Capabilities + { + get + { + if (this._capabilities == null) + { + this._capabilities = new TwainCapabilities(this); } return this._capabilities; } } /// - /// Возвращает набор операций для работы с цветовой палитрой. + /// Returns a set of operations for working with a color palette. + /// Возвращает набор операций для работы с цветовой палитрой. /// [Browsable(false)] [ReadOnly(true)] - public TwainPalette Palette { - get; - private set; - } - - /// - /// Возвращает разрешения, поддерживаемые источником данных. - /// - /// Коллекция значений. - /// Возбуждается в случае возникновения ошибки во время операции. - [Obsolete("Use Twain32.Capabilities.XResolution.Get() instead.",true)] - public Enumeration GetResolutions() { - return Enumeration.FromObject(this.GetCap(TwCap.XResolution)); - } - - /// - /// Устанавливает текущее разрешение. - /// - /// Разрешение. - /// Возбуждается в случае возникновения ошибки во время операции. - [Obsolete("Use Twain32.Capabilities.XResolution.Set(value) and Twain32.Capabilities.YResolution.Set(value) instead.",true)] - public void SetResolutions(float value) { - this.SetCap(TwCap.XResolution,value); - this.SetCap(TwCap.YResolution,value); - } - - /// - /// Возвращает типы пикселей, поддерживаемые источником данных. - /// - /// Коллекция значений. - /// Возбуждается в случае возникновения ошибки во время операции. - [Obsolete("Use Twain32.Capabilities.PixelType.Get() instead.",true)] - public Enumeration GetPixelTypes() { - Enumeration _val=Enumeration.FromObject(this.GetCap(TwCap.IPixelType)); - for(int i=0;i<_val.Count;i++) { - _val[i]=(TwPixelType)_val[i]; - } - return _val; - } - - /// - /// Устанавливает текущий тип пикселей. - /// - /// Тип пикселей. - /// Возбуждается в случае возникновения ошибки во время операции. - [Obsolete("Use Twain32.Capabilities.PixelType.Set(value) instead.",true)] - public void SetPixelType(TwPixelType value) { - this.SetCap(TwCap.IPixelType,value); - } - - /// - /// Возвращает единицы измерения, используемые источником данных. - /// - /// Единицы измерения. - /// Возбуждается в случае возникновения ошибки во время операции. - [Obsolete("Use Twain32.Capabilities.Units.Get() instead.",true)] - public Enumeration GetUnitOfMeasure() { - Enumeration _val=Enumeration.FromObject(this.GetCap(TwCap.IUnits)); - for (int i=0; i<_val.Count; i++) { - _val[i]=(TwUnits)_val[i]; - } - return _val; - } - - /// - /// Устанавливает текущую единицу измерения, используемую источником данных. - /// - /// Единица измерения. - /// Возбуждается в случае возникновения ошибки во время операции. - [Obsolete("Use Twain32.Capabilities.Units.Set(value) instead.",true)] - public void SetUnitOfMeasure(TwUnits value) { - this.SetCap(TwCap.IUnits,value); - } + public TwainPalette Palette { get; private set; } #endregion #region All capabilities /// - /// Возвращает флаги, указывающие на поддерживаемые источником данных операции, для указанного значения capability. + /// Returns flags indicating operations supported by the data source for the specified capability value. + /// Возвращает флаги, указывающие на поддерживаемые источником данных операции, для указанного значения capability. /// - /// Значение перечисдения TwCap. - /// Набор флагов. + /// The value of the TwCap enumeration.Значение перечисдения TwCap. + /// Set of flags.Набор флагов. /// Возбуждается в случае возникновения ошибки во время операции. - public TwQC IsCapSupported(TwCap capability) { - if((this._TwainState&TwainStateFlag.DSOpen)!=0) { - TwCapability _cap=new TwCapability(capability); - try { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Capability,TwMSG.QuerySupport,ref _cap); - if(_rc==TwRC.Success) { + public TwQC IsCapSupported(TwCap capability) + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + TwCapability _cap = new TwCapability(capability); + try + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Capability, TwMSG.QuerySupport, ref _cap); + if (_rc == TwRC.Success) + { return (TwQC)((TwOneValue)_cap.GetValue()).Item; } return 0; - } finally { + } + finally + { _cap.Dispose(); } - } else { - throw new TwainException("Источник данных не открыт."); + } + else + { + throw new TwainException("The data source is not open."); } } /// - /// Возвращает значение для указанного capability (возможность). + /// Returns the value for the specified capability. + /// Возвращает значение для указанного capability (возможность). /// - /// Значение перечисления TwCap. - /// Значение перечисления TwMSG. - /// В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. + /// The value of the TwCap enumeration.Значение перечисления TwCap. + /// The value of the TwMSG enumeration.Значение перечисления TwMSG. + /// Depending on the value of capability, the following can be returned: type-value, array, range, transfer.В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. /// Возбуждается в случае возникновения ошибки во время операции. - private object _GetCapCore(TwCap capability,TwMSG msg) { - if((this._TwainState&TwainStateFlag.DSOpen)!=0) { - TwCapability _cap=new TwCapability(capability); - try { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Capability,msg,ref _cap); - if(_rc==TwRC.Success) { - switch(_cap.ConType) { + private object _GetCapCore(TwCap capability, TwMSG msg) + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + TwCapability _cap = new TwCapability(capability); + try + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Capability, msg, ref _cap); + if (_rc == TwRC.Success) + { + switch (_cap.ConType) + { case TwOn.One: - object _valueRaw=_cap.GetValue(); - TwOneValue _value=_valueRaw as TwOneValue; - if(_value!=null) { - return TwTypeHelper.CastToCommon(_value.ItemType,TwTypeHelper.ValueToTw(_value.ItemType,_value.Item)); - } else { + object _valueRaw = _cap.GetValue(); + TwOneValue _value = _valueRaw as TwOneValue; + if (_value != null) + { + return TwTypeHelper.CastToCommon(_value.ItemType, TwTypeHelper.ValueToTw(_value.ItemType, _value.Item)); + } + else + { return _valueRaw; } case TwOn.Range: @@ -831,477 +943,633 @@ private object _GetCapCore(TwCap capability,TwMSG msg) { case TwOn.Array: return ((__ITwArray)_cap.GetValue()).Items; case TwOn.Enum: - __ITwEnumeration _enum=_cap.GetValue() as __ITwEnumeration; - return Enumeration.CreateEnumeration(_enum.Items,_enum.CurrentIndex,_enum.DefaultIndex); + __ITwEnumeration _enum = _cap.GetValue() as __ITwEnumeration; + return Enumeration.CreateEnumeration(_enum.Items, _enum.CurrentIndex, _enum.DefaultIndex); } return _cap.GetValue(); - } else { - throw new TwainException(this._GetTwainStatus(),_rc); } - } finally { + else + { + throw new TwainException(this._GetTwainStatus(), _rc); + } + } + finally + { _cap.Dispose(); } - } else { - throw new TwainException("Источник данных не открыт."); + } + else + { + throw new TwainException("The data source is not open."); } } /// - /// Возвращает значения указанной возможности (capability). + /// Gets the values of the specified feature (capability). + /// Возвращает значения указанной возможности (capability). /// - /// Значение перечисления TwCap. - /// В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. + /// The value of the TwCap enumeration.Значение перечисления TwCap. + /// Depending on the value of capability, the following can be returned: type-value, array, range, transfer.В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. /// Возбуждается в случае возникновения ошибки во время операции. - public object GetCap(TwCap capability) { - return this._GetCapCore(capability,TwMSG.Get); - } + public object GetCap(TwCap capability) => this._GetCapCore(capability, TwMSG.Get); /// - /// Возвращает текущее значение для указанной возможности (capability). + /// Returns the current value for the specified feature. (capability). + /// Возвращает текущее значение для указанной возможности (capability). /// - /// Значение перечисления TwCap. - /// В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. + /// The value of the TwCap enumeration.Значение перечисления TwCap. + /// Depending on the value of capability, the following can be returned: type-value, array, range, transfer.В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. /// Возбуждается в случае возникновения ошибки во время операции. - public object GetCurrentCap(TwCap capability) { - return this._GetCapCore(capability,TwMSG.GetCurrent); - } + public object GetCurrentCap(TwCap capability) => this._GetCapCore(capability, TwMSG.GetCurrent); /// - /// Возвращает значение по умолчанию для указанной возможности (capability). + /// Returns the default value for the specified feature. (capability). + /// Возвращает значение по умолчанию для указанной возможности (capability). /// - /// Значение перечисления TwCap. - /// В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. + /// The value of the TwCap enumeration.Значение перечисления TwCap. + /// Depending on the value of capability, the following can be returned: type-value, array, range, transfer.В зависимости от значение capability, могут быть возвращены: тип-значение, массив, диапазон, перечисление. /// Возбуждается в случае возникновения ошибки во время операции. - public object GetDefaultCap(TwCap capability) { - return this._GetCapCore(capability,TwMSG.GetDefault); - } + public object GetDefaultCap(TwCap capability) => this._GetCapCore(capability, TwMSG.GetDefault); /// - /// Сбрасывает текущее значение для указанного capability в значение по умолчанию. + /// Resets the current value for the specified capability to default value. + /// Сбрасывает текущее значение для указанного capability в значение по умолчанию. /// - /// Значение перечисления . + /// Listing Value .Значение перечисления . /// Возбуждается в случае возникновения ошибки во время операции. - public void ResetCap(TwCap capability) { - if((this._TwainState&TwainStateFlag.DSOpen)!=0) { - TwCapability _cap=new TwCapability(capability); - try { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Capability,TwMSG.Reset,ref _cap); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + public void ResetCap(TwCap capability) + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + TwCapability _cap = new TwCapability(capability); + try + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Capability, TwMSG.Reset, ref _cap); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } finally { + } + finally + { _cap.Dispose(); } - } else { - throw new TwainException("Источник данных не открыт."); + } + else + { + throw new TwainException("The data source is not open."); } } /// - /// Сбрасывает текущее значение всех текущих значений в значения по умолчанию. + /// Resets the current value of all current values to the default values. + /// Сбрасывает текущее значение всех текущих значений в значения по умолчанию. /// /// Возбуждается в случае возникновения ошибки во время операции. - public void ResetAllCap() { - if((this._TwainState&TwainStateFlag.DSOpen)!=0) { - TwCapability _cap=new TwCapability(TwCap.SupportedCaps); - try { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Capability,TwMSG.ResetAll,ref _cap); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + public void ResetAllCap() + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + TwCapability _cap = new TwCapability(TwCap.SupportedCaps); + try + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Capability, TwMSG.ResetAll, ref _cap); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } finally { + } + finally + { _cap.Dispose(); } - } else { - throw new TwainException("Источник данных не открыт."); + } + else + { + throw new TwainException("The data source is not open."); } } - private void _SetCapCore(TwCapability cap,TwMSG msg) { - if((this._TwainState&TwainStateFlag.DSOpen)!=0) { - try { - TwRC _rc = this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Capability,msg,ref cap); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + private void _SetCapCore(TwCapability cap, TwMSG msg) + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + try + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Capability, msg, ref cap); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } finally { + } + finally + { cap.Dispose(); } - } else { - throw new TwainException("Источник данных не открыт."); + } + else + { + throw new TwainException("The data source is not open."); } } - private void _SetCapCore(TwCap capability,TwMSG msg,object value) { + private void _SetCapCore(TwCap capability, TwMSG msg, object value) + { TwCapability _cap = null; - if(value is string) { - object[] _attrs = typeof(TwCap).GetField(capability.ToString()).GetCustomAttributes(typeof(TwTypeAttribute),false); - if(_attrs.Length>0) { - _cap=new TwCapability(capability,(string)value,((TwTypeAttribute)_attrs[0]).TwType); - } else { - _cap=new TwCapability(capability,(string)value,TwTypeHelper.TypeOf(value)); - } - } else { + if (value is string) + { + object[] _attrs = typeof(TwCap).GetField(capability.ToString())?.GetCustomAttributes(typeof(TwTypeAttribute), false); + if (_attrs?.Length > 0) + { + _cap = new TwCapability(capability, (string)value, ((TwTypeAttribute)_attrs[0]).TwType); + } + else + { + _cap = new TwCapability(capability, (string)value, TwTypeHelper.TypeOf(value)); + } + } + else + { TwType _type = TwTypeHelper.TypeOf(value.GetType()); - _cap=new TwCapability(capability,TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type,value)),_type); + _cap = new TwCapability(capability, TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type, value)), _type); } - this._SetCapCore(_cap,msg); + this._SetCapCore(_cap, msg); } - private void _SetCapCore(TwCap capability,TwMSG msg,object[] value) { - var _attrs = typeof(TwCap).GetField(capability.ToString()).GetCustomAttributes(typeof(TwTypeAttribute),false); + private void _SetCapCore(TwCap capability, TwMSG msg, object[] value) + { + var _attrs = typeof(TwCap).GetField(capability.ToString())?.GetCustomAttributes(typeof(TwTypeAttribute), false); this._SetCapCore( new TwCapability( capability, - new TwArray() { - ItemType=_attrs.Length>0 ? ((TwTypeAttribute)(_attrs[0])).TwType : TwTypeHelper.TypeOf(value[0]), - NumItems=(uint)value.Length + new TwArray() + { + ItemType = _attrs?.Length > 0 ? ((TwTypeAttribute)(_attrs[0])).TwType : TwTypeHelper.TypeOf(value[0]), + NumItems = (uint)value.Length }, value), msg); } - private void _SetCapCore(TwCap capability,TwMSG msg,Range value) { - this._SetCapCore(new TwCapability(capability,value.ToTwRange()),msg); - } + private void _SetCapCore(TwCap capability, TwMSG msg, Range value) => this._SetCapCore(new TwCapability(capability, value.ToTwRange()), msg); - private void _SetCapCore(TwCap capability,TwMSG msg,Enumeration value) { - var _attrs = typeof(TwCap).GetField(capability.ToString()).GetCustomAttributes(typeof(TwTypeAttribute),false); + private void _SetCapCore(TwCap capability, TwMSG msg, Enumeration value) + { + var _attrs = typeof(TwCap).GetField(capability.ToString())?.GetCustomAttributes(typeof(TwTypeAttribute), false); this._SetCapCore( new TwCapability( capability, - new TwEnumeration { - ItemType=_attrs.Length>0 ? ((TwTypeAttribute)(_attrs[0])).TwType : TwTypeHelper.TypeOf(value[0]), - NumItems=(uint)value.Count, - CurrentIndex=(uint)value.CurrentIndex, - DefaultIndex=(uint)value.DefaultIndex + new TwEnumeration + { + ItemType = _attrs?.Length > 0 ? ((TwTypeAttribute)(_attrs[0])).TwType : TwTypeHelper.TypeOf(value[0]), + NumItems = (uint)value.Count, + CurrentIndex = (uint)value.CurrentIndex, + DefaultIndex = (uint)value.DefaultIndex }, value.Items), msg); } /// - /// Устанавливает значение для указанного capability + /// Sets the value for the specified capability + /// Устанавливает значение для указанного capability /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetCap(TwCap capability,object value) { - this._SetCapCore(capability,TwMSG.Set,value); - } + public void SetCap(TwCap capability, object value) => this._SetCapCore(capability, TwMSG.Set, value); /// - /// Устанавливает значение для указанного capability + /// Sets the value for the specified capability + /// Устанавливает значение для указанного capability /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetCap(TwCap capability,object[] value) { - this._SetCapCore(capability,TwMSG.Set,value); - } + public void SetCap(TwCap capability, object[] value) => this._SetCapCore(capability, TwMSG.Set, value); /// - /// Устанавливает значение для указанного capability + /// Sets the value for the specified capability + /// Устанавливает значение для указанного capability /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetCap(TwCap capability,Range value) { - this._SetCapCore(capability,TwMSG.Set,value); - } + public void SetCap(TwCap capability, Range value) => this._SetCapCore(capability, TwMSG.Set, value); /// - /// Устанавливает значение для указанного capability + /// Sets the value for the specified capability + /// Устанавливает значение для указанного capability /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetCap(TwCap capability,Enumeration value) { - this._SetCapCore(capability,TwMSG.Set,value); - } + public void SetCap(TwCap capability, Enumeration value) => this._SetCapCore(capability, TwMSG.Set, value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetConstraintCap(TwCap capability,object value) { - this._SetCapCore(capability,TwMSG.SetConstraint,value); - } + public void SetConstraintCap(TwCap capability, object value) => this._SetCapCore(capability, TwMSG.SetConstraint, value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetConstraintCap(TwCap capability,object[] value) { - this._SetCapCore(capability,TwMSG.SetConstraint,value); - } + public void SetConstraintCap(TwCap capability, object[] value) => this._SetCapCore(capability, TwMSG.SetConstraint, value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetConstraintCap(TwCap capability,Range value) { - this._SetCapCore(capability,TwMSG.SetConstraint,value); - } + public void SetConstraintCap(TwCap capability, Range value) => this._SetCapCore(capability, TwMSG.SetConstraint, value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Значение перечисления . - /// Устанавливаемое значение. + /// Listing Value .Значение перечисления . + /// The value to set.Устанавливаемое значение. /// Возникает в случае, если источник данных не открыт. - public void SetConstraintCap(TwCap capability,Enumeration value) { - this._SetCapCore(capability,TwMSG.SetConstraint,value); - } + public void SetConstraintCap(TwCap capability, Enumeration value) => this._SetCapCore(capability, TwMSG.SetConstraint, value); #endregion #region DG_IMAGE / IMAGExxxxXFER / MSG_GET operation /// - /// Выполняет передачу изображения (Native Mode Transfer). + /// Performs image transfer (Native Mode Transfer). + /// Выполняет передачу изображения (Native Mode Transfer). /// - private void _NativeTransferPictures() { - if(this._srcds.Id==0) { + private void _NativeTransferPictures() + { + if (this._srcds.Id == 0) + { return; } - IntPtr _hBitmap=IntPtr.Zero; - TwPendingXfers _pxfr=new TwPendingXfers(); - try { + IntPtr _hBitmap = IntPtr.Zero; + TwPendingXfers _pxfr = new TwPendingXfers(); + try + { this._images.Clear(); - do { - _pxfr.Count=0; - _hBitmap=IntPtr.Zero; + do + { + _pxfr.Count = 0; + _hBitmap = IntPtr.Zero; - for(TwRC _rc=this._dsmEntry.DSImageXfer(this._AppId,this._srcds,TwDG.Image,TwDAT.ImageNativeXfer,TwMSG.Get,ref _hBitmap); _rc!=TwRC.XferDone; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DSImageXfer(this._AppId, this._srcds, TwDG.Image, TwDAT.ImageNativeXfer, TwMSG.Get, ref _hBitmap); _rc != TwRC.XferDone;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } // DG_IMAGE / DAT_IMAGEINFO / MSG_GET // DG_IMAGE / DAT_EXTIMAGEINFO / MSG_GET - if(this._OnXferDone(new XferDoneEventArgs(this._GetImageInfo,this._GetExtImageInfo))) { + if (this._OnXferDone(new XferDoneEventArgs(this._GetImageInfo, this._GetExtImageInfo))) + { return; } - IntPtr _pBitmap=_Memory.Lock(_hBitmap); - try { - _Image _img=null; - switch(Environment.OSVersion.Platform) { - case PlatformID.Unix: - _img=Tiff.FromPtrToImage(_pBitmap); - break; - case PlatformID.MacOSX: - throw new NotImplementedException(); - default: - _img=DibToImage.WithStream(_pBitmap,this.GetService(typeof(IStreamProvider)) as IStreamProvider); - break; + IntPtr _pBitmap = _Memory.Lock(_hBitmap); + try + { + _Image _img = null; + + IImageHandler _handler = this.GetService(typeof(IImageHandler)) as IImageHandler; + if (_handler == null) + { + switch (Environment.OSVersion.Platform) + { + case PlatformID.Unix: + _handler = new Tiff(); + break; + case PlatformID.MacOSX: + _handler = new Pict(); + break; + default: + _handler = new DibToImage(); + break; + } } + _img = _handler.PtrToStream(_pBitmap, this.GetService(typeof(IStreamProvider)) as IStreamProvider); + this._images.Add(_img); - if(this._OnEndXfer(new EndXferEventArgs(_img))) { + if (this._OnEndXfer(new EndXferEventArgs(_img))) + { return; } - } finally { + } + finally + { _Memory.Unlock(_hBitmap); _Memory.Free(_hBitmap); } - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.EndXfer,ref _pxfr); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.EndXfer, ref _pxfr); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } while(_pxfr.Count!=0); - } finally { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.Reset,ref _pxfr); + } while (_pxfr.Count != 0); + } + finally + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.Reset, ref _pxfr); } } /// - /// Выполняет передачу изображения (Disk File Mode Transfer). + /// Performs image transfer (Disk File Mode Transfer). + /// Выполняет передачу изображения (Disk File Mode Transfer). /// - private void _FileTransferPictures() { - if(this._srcds.Id==0) { + private void _FileTransferPictures() + { + if (this._srcds.Id == 0) + { return; } - TwPendingXfers _pxfr=new TwPendingXfers(); - try { + TwPendingXfers _pxfr = new TwPendingXfers(); + try + { this._images.Clear(); - do { - _pxfr.Count=0; + do + { + _pxfr.Count = 0; - TwSetupFileXfer _fileXfer=new TwSetupFileXfer { - Format=((this.Capabilities.ImageFileFormat.IsSupported()&TwQC.GetCurrent)!=0)?this.Capabilities.ImageFileFormat.GetCurrent():TwFF.Bmp, - FileName=Path.GetTempFileName() - }; - SetupFileXferEventArgs _args=new SetupFileXferEventArgs(); - if(this._OnSetupFileXfer(_args)) { + SetupFileXferEventArgs _args = new SetupFileXferEventArgs(); + if (this._OnSetupFileXfer(_args)) + { return; } - if(!string.IsNullOrEmpty(_args.FileName)) { - _fileXfer.FileName=_args.FileName; - } - if((this.Capabilities.ImageFileFormat.IsSupported()&TwQC.GetCurrent)!=0) { - _fileXfer.Format=this.Capabilities.ImageFileFormat.GetCurrent(); - } - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.SetupFileXfer,TwMSG.Set,ref _fileXfer); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + TwSetupFileXfer _fileXfer = new TwSetupFileXfer + { + Format = this.Capabilities.ImageFileFormat.IsSupported(TwQC.GetCurrent) ? this.Capabilities.ImageFileFormat.GetCurrent() : TwFF.Bmp, + FileName = string.IsNullOrEmpty(_args.FileName) ? Path.GetTempFileName() : _args.FileName + }; + + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.SetupFileXfer, TwMSG.Set, ref _fileXfer); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - for(TwRC _rc=this._dsmEntry.DsRaw(this._AppId,this._srcds,TwDG.Image,TwDAT.ImageFileXfer,TwMSG.Get,IntPtr.Zero); _rc!=TwRC.XferDone; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsRaw(this._AppId, this._srcds, TwDG.Image, TwDAT.ImageFileXfer, TwMSG.Get, IntPtr.Zero); _rc != TwRC.XferDone;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } // DG_IMAGE / DAT_IMAGEINFO / MSG_GET // DG_IMAGE / DAT_EXTIMAGEINFO / MSG_GET - if(this._OnXferDone(new XferDoneEventArgs(this._GetImageInfo,this._GetExtImageInfo))) { + if (this._OnXferDone(new XferDoneEventArgs(this._GetImageInfo, this._GetExtImageInfo))) + { return; } - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.EndXfer,ref _pxfr); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.EndXfer, ref _pxfr); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.SetupFileXfer,TwMSG.Get,ref _fileXfer); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.SetupFileXfer, TwMSG.Get, ref _fileXfer); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - if(this._OnFileXfer(new FileXferEventArgs(ImageFileXfer.Create(_fileXfer)))) { + if (this._OnFileXfer(new FileXferEventArgs(ImageFileXfer.Create(_fileXfer)))) + { return; } - } while(_pxfr.Count!=0); - } finally { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.Reset,ref _pxfr); + } while (_pxfr.Count != 0); + } + finally + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.Reset, ref _pxfr); } } /// - /// Выполняет передачу изображения (Buffered Memory Mode Transfer and Memory File Mode Transfer). + /// Performs image transfer (Buffered Memory Mode Transfer and Memory File Mode Transfer). + /// Выполняет передачу изображения (Buffered Memory Mode Transfer and Memory File Mode Transfer). /// - private void _MemoryTransferPictures(bool isMemFile) { - if(this._srcds.Id==0) { + private void _MemoryTransferPictures(bool isMemFile) + { + if (this._srcds.Id == 0) + { return; } - TwPendingXfers _pxfr=new TwPendingXfers(); - try { + TwPendingXfers _pxfr = new TwPendingXfers(); + try + { this._images.Clear(); - do { - _pxfr.Count=0; - ImageInfo _info=this._GetImageInfo(); - - if(isMemFile) { - if((this.Capabilities.ImageFileFormat.IsSupported()&TwQC.GetCurrent)!=0) { - TwSetupFileXfer _fileXfer=new TwSetupFileXfer { - Format=this.Capabilities.ImageFileFormat.GetCurrent() + do + { + _pxfr.Count = 0; + ImageInfo _info = this._GetImageInfo(); + + if (isMemFile) + { + if ((this.Capabilities.ImageFileFormat.IsSupported() & TwQC.GetCurrent) != 0) + { + TwSetupFileXfer _fileXfer = new TwSetupFileXfer + { + Format = this.Capabilities.ImageFileFormat.GetCurrent() }; - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.SetupFileXfer,TwMSG.Set,ref _fileXfer); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.SetupFileXfer, TwMSG.Set, ref _fileXfer); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } } } - TwSetupMemXfer _memBufSize=new TwSetupMemXfer(); + TwSetupMemXfer _memBufSize = new TwSetupMemXfer(); - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.SetupMemXfer,TwMSG.Get,ref _memBufSize); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.SetupMemXfer, TwMSG.Get, ref _memBufSize); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - if(this._OnSetupMemXfer(new SetupMemXferEventArgs(_info,_memBufSize.Preferred))) { + if (this._OnSetupMemXfer(new SetupMemXferEventArgs(_info, _memBufSize.Preferred))) + { return; } - IntPtr _hMem=_Memory.Alloc((int)_memBufSize.Preferred); - if(_hMem==IntPtr.Zero) { - throw new TwainException("Ошибка выделениия памяти."); + IntPtr _hMem = _Memory.Alloc((int)_memBufSize.Preferred); + if (_hMem == IntPtr.Zero) + { + throw new TwainException("Error allocating memory."); } - try { - TwMemory _mem=new TwMemory { - Flags=TwMF.AppOwns|TwMF.Pointer, - Length=_memBufSize.Preferred, - TheMem=_Memory.Lock(_hMem) + try + { + TwMemory _mem = new TwMemory + { + Flags = TwMF.AppOwns | TwMF.Pointer, + Length = _memBufSize.Preferred, + TheMem = _Memory.Lock(_hMem) }; - do { - TwImageMemXfer _memXferBuf=new TwImageMemXfer {Memory=_mem}; - _Memory.ZeroMemory(_memXferBuf.Memory.TheMem,(IntPtr)_memXferBuf.Memory.Length); - - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Image,isMemFile?TwDAT.ImageMemFileXfer:TwDAT.ImageMemXfer,TwMSG.Get,ref _memXferBuf); - if(_rc!=TwRC.Success&&_rc!=TwRC.XferDone) { - TwCC _cc=this._GetTwainStatus(); - TwRC _rc2=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.EndXfer,ref _pxfr); - throw new TwainException(_cc,_rc); + do + { + TwImageMemXfer _memXferBuf = new TwImageMemXfer { Memory = _mem }; + _Memory.ZeroMemory(_memXferBuf.Memory.TheMem, (IntPtr)_memXferBuf.Memory.Length); + + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Image, isMemFile ? TwDAT.ImageMemFileXfer : TwDAT.ImageMemXfer, TwMSG.Get, ref _memXferBuf); + if (_rc != TwRC.Success && _rc != TwRC.XferDone) + { + TwCC _cc = this._GetTwainStatus(); + TwRC _rc2 = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.EndXfer, ref _pxfr); + throw new TwainException(_cc, _rc); } - if(this._OnMemXfer(new MemXferEventArgs(_info,ImageMemXfer.Create(_memXferBuf)))) { + if (this._OnMemXfer(new MemXferEventArgs(_info, ImageMemXfer.Create(_memXferBuf)))) + { return; } - if(_rc==TwRC.XferDone) { + if (_rc == TwRC.XferDone) + { // DG_IMAGE / DAT_IMAGEINFO / MSG_GET // DG_IMAGE / DAT_EXTIMAGEINFO / MSG_GET - if(this._OnXferDone(new XferDoneEventArgs(this._GetImageInfo,this._GetExtImageInfo))) { + if (this._OnXferDone(new XferDoneEventArgs(this._GetImageInfo, this._GetExtImageInfo))) + { return; } break; } - } while(true); - } finally { + } while (true); + } + finally + { _Memory.Unlock(_hMem); _Memory.Free(_hMem); } - for(TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.EndXfer,ref _pxfr); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.EndXfer, ref _pxfr); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } while(_pxfr.Count!=0); - } finally { - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.PendingXfers,TwMSG.Reset,ref _pxfr); + } while (_pxfr.Count != 0); + } + finally + { + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.Reset, ref _pxfr); } } #endregion - #region DS events handler + #region DG_CONTROL / DAT_CUSTOMDSDATA / MSG_xxx /// - /// Обработчик событий источника данных. + /// Get or set the Custom Data (DG_CONTROL / DAT_CUSTOMDSDATA / MSG_xxx). /// - /// Описание приложения. - /// Описание источника данных. - /// Описание группы данных. - /// Описание данных. - /// Сообщение. - /// Данные. - /// Результат обработники события. - private TwRC _TwCallbackProc(TwIdentity srcId,TwIdentity appId,TwDG dg,TwDAT dat,TwMSG msg,IntPtr data) { - try { - if(appId==null||appId.Id!=this._AppId.Id) { + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public byte[] CustomDSData + { + get + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + TwCustomDSData _data = new TwCustomDSData { }; + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.CustomDSData, TwMSG.Get, ref _data); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); + } + byte[] _value = new byte[_data.InfoLength]; + Marshal.Copy(_Memory.Lock(_data.hData), _value, 0, _value.Length); + _Memory.Unlock(_data.hData); + _Memory.Free(_data.hData); + return _value; + } + else + { + throw new TwainException("Источник данных не открыт."); + } + } + set + { + if ((this._TwainState & TwainStateFlag.DSOpen) != 0) + { + TwCustomDSData _data = new TwCustomDSData + { + InfoLength = (uint)value.Length, + hData = _Memory.Alloc(value.Length) + }; + Marshal.Copy(value, 0, _Memory.Lock(_data.hData), value.Length); + _Memory.Unlock(_data.hData); + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.CustomDSData, TwMSG.Set, ref _data); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); + } + _Memory.Free(_data.hData); + } + else + { + throw new TwainException("Источник данных не открыт."); + } + } + } + + #endregion + + #region DS events handler + + /// + /// A data source event handler. + /// Обработчик событий источника данных. + /// + /// Description of the application.Описание приложения. + /// Description of the data source.Описание источника данных. + /// Description of the data group.Описание группы данных. + /// Description of the data.Описание данных. + /// Message.Сообщение. + /// Data.Данные. + /// Result event handlers.Результат обработники события. + private TwRC _TwCallbackProc(TwIdentity srcId, TwIdentity appId, TwDG dg, TwDAT dat, TwMSG msg, IntPtr data) + { + try + { + if (appId == null || appId.Id != this._AppId.Id) + { return TwRC.Failure; } - if((this._TwainState&TwainStateFlag.DSEnabled)==0) { - this._TwainState|=TwainStateFlag.DSEnabled|TwainStateFlag.DSReady; + if ((this._TwainState & TwainStateFlag.DSEnabled) == 0) + { + this._TwainState |= TwainStateFlag.DSEnabled | TwainStateFlag.DSReady; } - this._TwCallbackProcCore(msg,isCloseReq => { - if(isCloseReq||this.DisableAfterAcquire) { + this._TwCallbackProcCore(msg, isCloseReq => { + if (isCloseReq || this.DisableAfterAcquire) + { this._DisableDataSource(); } }); - } catch(Exception ex) { - this._OnAcquireError(new AcquireErrorEventArgs(new TwainException(ex.Message,ex))); + } + catch (Exception ex) + { + this._OnAcquireError(new AcquireErrorEventArgs(new TwainException(ex.Message, ex))); } return TwRC.Success; } /// - /// Внутренний обработчик событий источника данных. + /// An internal data source event handler. + /// Внутренний обработчик событий источника данных. /// - /// Сообщение. - /// Действие, завершающее обработку события. - private void _TwCallbackProcCore(TwMSG msg,Action endAction) { - try { - switch(msg) { + /// Message.Сообщение. + /// The action that completes the processing of the event.Действие, завершающее обработку события. + private void _TwCallbackProcCore(TwMSG msg, Action endAction) + { + try + { + switch (msg) + { case TwMSG.XFerReady: - switch(this.Capabilities.XferMech.GetCurrent()) { + switch (this.Capabilities.XferMech.GetCurrent()) + { case TwSX.File: this._FileTransferPictures(); break; @@ -1328,24 +1596,36 @@ private void _TwCallbackProcCore(TwMSG msg,Action endAction) { this._DeviceEventObtain(); break; } - } catch(TwainException ex) { - try { + } + catch (TwainException ex) + { + try + { endAction(false); - } catch { + } + catch + { } this._OnAcquireError(new AcquireErrorEventArgs(ex)); - } catch { - try { + } + catch + { + try + { endAction(false); - } catch { + } + catch + { } throw; } } - private void _DeviceEventObtain() { - TwDeviceEvent _deviceEvent=new TwDeviceEvent(); - if(this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.DeviceEvent,TwMSG.Get,ref _deviceEvent)==TwRC.Success) { + private void _DeviceEventObtain() + { + TwDeviceEvent _deviceEvent = new TwDeviceEvent(); + if (this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.DeviceEvent, TwMSG.Get, ref _deviceEvent) == TwRC.Success) + { this._OnDeviceEvent(new DeviceEventEventArgs(_deviceEvent)); } } @@ -1354,175 +1634,190 @@ private void _DeviceEventObtain() { #region Raise events - private void _OnAcquireCompleted(EventArgs e) { - if(this.AcquireCompleted!=null) { - this.AcquireCompleted(this,e); - } - } + private void _OnAcquireCompleted(EventArgs e) => this.AcquireCompleted?.Invoke(this, e); - private void _OnAcquireError(AcquireErrorEventArgs e) { - if(this.AcquireError!=null) { - this.AcquireError(this,e); - } - } + private void _OnAcquireError(AcquireErrorEventArgs e) => this.AcquireError?.Invoke(this, e); - private bool _OnXferDone(XferDoneEventArgs e) { - if(this.XferDone!=null) { - this.XferDone(this,e); - } + private bool _OnXferDone(XferDoneEventArgs e) + { + this.XferDone?.Invoke(this, e); return e.Cancel; } - private bool _OnEndXfer(EndXferEventArgs e) { - if(this.EndXfer!=null) { - this.EndXfer(this,e); - } + private bool _OnEndXfer(EndXferEventArgs e) + { + this.EndXfer?.Invoke(this, e); return e.Cancel; } - private bool _OnSetupMemXfer(SetupMemXferEventArgs e) { - if(this.SetupMemXferEvent!=null) { - this.SetupMemXferEvent(this,e); - } + private bool _OnSetupMemXfer(SetupMemXferEventArgs e) + { + this.SetupMemXferEvent?.Invoke(this, e); return e.Cancel; } - private bool _OnMemXfer(MemXferEventArgs e) { - if(this.MemXferEvent!=null) { - this.MemXferEvent(this,e); - } + private bool _OnMemXfer(MemXferEventArgs e) + { + this.MemXferEvent?.Invoke(this, e); return e.Cancel; } - private bool _OnSetupFileXfer(SetupFileXferEventArgs e) { - if(this.SetupFileXferEvent!=null) { - this.SetupFileXferEvent(this,e); - } + private bool _OnSetupFileXfer(SetupFileXferEventArgs e) + { + this.SetupFileXferEvent?.Invoke(this, e); return e.Cancel; } - private bool _OnFileXfer(FileXferEventArgs e) { - if(this.FileXferEvent!=null) { - this.FileXferEvent(this,e); - } + private bool _OnFileXfer(FileXferEventArgs e) + { + this.FileXferEvent?.Invoke(this, e); return e.Cancel; } - private void _OnDeviceEvent(DeviceEventEventArgs e) { - if(this.DeviceEvent!=null) { - this.DeviceEvent(this,e); - } - } + private void _OnDeviceEvent(DeviceEventEventArgs e) => this.DeviceEvent?.Invoke(this, e); #endregion /// - /// Получает описание всех доступных источников данных. + /// Gets a description of all available data sources. + /// Получает описание всех доступных источников данных. /// - private void _GetAllSorces() { - List _src=new List(); - TwIdentity _item=new TwIdentity(); - try { - for(TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.GetFirst,ref _item); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + private void _GetAllSorces() + { + List _src = new List(); + TwIdentity _item = new TwIdentity(); + try + { + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.GetFirst, ref _item); _rc != TwRC.Success;) + { + if (_rc == TwRC.EndOfList) + { + return; + } + throw new TwainException(this._GetTwainStatus(), _rc); } _src.Add(_item); - while(true) { - _item=new TwIdentity(); - TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.GetNext,ref _item); - if(_rc==TwRC.Success) { + while (true) + { + _item = new TwIdentity(); + TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.GetNext, ref _item); + if (_rc == TwRC.Success) + { _src.Add(_item); continue; } - if(_rc==TwRC.EndOfList) { + if (_rc == TwRC.EndOfList) + { break; } - throw new TwainException(this._GetTwainStatus(),_rc); + throw new TwainException(this._GetTwainStatus(), _rc); } - for(TwRC _rc=this._dsmEntry.DsmInvoke(this._AppId,TwDG.Control,TwDAT.Identity,TwMSG.GetDefault,ref _srcds); _rc!=TwRC.Success; ) { - throw new TwainException(this._GetTwainStatus(),_rc); + for (TwRC _rc = this._dsmEntry.DsmInvoke(this._AppId, TwDG.Control, TwDAT.Identity, TwMSG.GetDefault, ref _srcds); _rc != TwRC.Success;) + { + throw new TwainException(this._GetTwainStatus(), _rc); } - } finally { - - foreach(TwIdentity twi in _src.ToArray()) + } + finally + { + foreach (TwIdentity twi in _src.ToArray()) { if (twi.ProductName.ToString().Contains("WIA")) { _src.Remove(twi); } - } - this._sources=_src.ToArray(); + } + this._sources = _src.ToArray(); } } /// - /// Возвращает или устанавливает значение флагов состояния. + /// Gets or sets the value of the status flags. + /// Возвращает или устанавливает значение флагов состояния. /// - private TwainStateFlag _TwainState { - get { + private TwainStateFlag _TwainState + { + get + { return this._twainState; } - set { - if(this._twainState!=value) { - this._twainState=value; - if(this.TwainStateChanged!=null) { - this.TwainStateChanged(this,new TwainStateEventArgs(this._twainState)); + set + { + if (this._twainState != value) + { + this._twainState = value; + if (this.TwainStateChanged != null) + { + this.TwainStateChanged(this, new TwainStateEventArgs(this._twainState)); } } } } /// - /// Возвращает код состояния TWAIN. + /// Returns the TWAIN status code. + /// Возвращает код состояния TWAIN. /// /// - private TwCC _GetTwainStatus() { - TwStatus _status=new TwStatus(); - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Control,TwDAT.Status,TwMSG.Get,ref _status); + private TwCC _GetTwainStatus() + { + TwStatus _status = new TwStatus(); + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Control, TwDAT.Status, TwMSG.Get, ref _status); return _status.ConditionCode; } /// - /// Возвращает описание полученного изображения. + /// Returns a description of the received image. + /// Возвращает описание полученного изображения. /// - /// Описание изображения. - private ImageInfo _GetImageInfo() { - TwImageInfo _imageInfo=new TwImageInfo(); - TwRC _rc=this._dsmEntry.DsInvoke(this._AppId,this._srcds,TwDG.Image,TwDAT.ImageInfo,TwMSG.Get,ref _imageInfo); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + /// Description of the image.Описание изображения. + private ImageInfo _GetImageInfo() + { + TwImageInfo _imageInfo = new TwImageInfo(); + TwRC _rc = this._dsmEntry.DsInvoke(this._AppId, this._srcds, TwDG.Image, TwDAT.ImageInfo, TwMSG.Get, ref _imageInfo); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } return ImageInfo.FromTwImageInfo(_imageInfo); } /// - /// Возвращает расширенного описание полученного изображения. + /// Returns an extended description of the resulting image. + /// Возвращает расширенного описание полученного изображения. /// - /// Набор кодов расширенного описания изображения для которых требуется получить описание. - /// Расширенное описание изображения. - private ExtImageInfo _GetExtImageInfo(TwEI[] extInfo) { - TwInfo[] _info=new TwInfo[extInfo.Length]; - for(int i=0; iA set of codes for the extended image description for which you want to get a description.Набор кодов расширенного описания изображения для которых требуется получить описание. + /// Extended image description.Расширенное описание изображения. + private ExtImageInfo _GetExtImageInfo(TwEI[] extInfo) + { + TwInfo[] _info = new TwInfo[extInfo.Length]; + for (int i = 0; i < extInfo.Length; i++) + { + _info[i] = new TwInfo { InfoId = extInfo[i] }; } - IntPtr _extImageInfo=TwExtImageInfo.ToPtr(_info); - try { + IntPtr _extImageInfo = TwExtImageInfo.ToPtr(_info); + try + { - TwRC _rc=this._dsmEntry.DsRaw(this._AppId,this._srcds,TwDG.Image,TwDAT.ExtImageInfo,TwMSG.Get,_extImageInfo); - if(_rc!=TwRC.Success) { - throw new TwainException(this._GetTwainStatus(),_rc); + TwRC _rc = this._dsmEntry.DsRaw(this._AppId, this._srcds, TwDG.Image, TwDAT.ExtImageInfo, TwMSG.Get, _extImageInfo); + if (_rc != TwRC.Success) + { + throw new TwainException(this._GetTwainStatus(), _rc); } return ExtImageInfo.FromPtr(_extImageInfo); - } finally { + } + finally + { Marshal.FreeHGlobal(_extImageInfo); } } /// - /// Флаги состояния. + /// State flags. + /// Флаги состояния. /// [Flags] - public enum TwainStateFlag { + public enum TwainStateFlag + { /// /// The DSM open. @@ -1548,73 +1843,83 @@ public enum TwainStateFlag { #region Events /// - /// Возникает в момент окончания сканирования. Occurs when the acquire is completed. + /// Occurs when the acquire is completed. + /// Возникает в момент окончания сканирования. /// [Category("Action")] - [Description("Возникает в момент окончания сканирования. Occurs when the acquire is completed.")] + [Description("Occurs when the acquire is completed. Возникает в момент окончания сканирования.")] public event EventHandler AcquireCompleted; /// - /// Возникает в момент получения ошибки в процессе сканирования. Occurs when error received during acquire. + /// Occurs when error received during acquire. + /// Возникает в момент получения ошибки в процессе сканирования. /// [Category("Action")] - [Description("Возникает в момент получения ошибки в процессе сканирования. Occurs when error received during acquire.")] + [Description("Occurs when error received during acquire. Возникает в момент получения ошибки в процессе сканирования.")] public event EventHandler AcquireError; /// - /// Возникает в момент окончания получения изображения приложением. Occurs when the transfer into application was completed (Native Mode Transfer). + /// Occurs when the transfer into application was completed (Native Mode Transfer). + /// Возникает в момент окончания получения изображения приложением. /// [Category("Native Mode Action")] - [Description("Возникает в момент окончания получения изображения приложением. Occurs when the transfer into application was completed (Native Mode Transfer).")] + [Description("Occurs when the transfer into application was completed (Native Mode Transfer). Возникает в момент окончания получения изображения приложением.")] public event EventHandler EndXfer; /// - /// Возникает в момент окончания получения изображения источником. + /// Occurs when the transfer was completed. + /// Возникает в момент окончания получения изображения источником. /// [Category("Action")] - [Description("Возникает в момент окончания получения изображения источником. Occurs when the transfer was completed.")] + [Description("Occurs when the transfer was completed. Возникает в момент окончания получения изображения источником.")] public event EventHandler XferDone; /// - /// Возникает в момент установки размера буфера памяти. Occurs when determined size of buffer to use during the transfer (Memory Mode Transfer and MemFile Mode Transfer). + /// Occurs when determined size of buffer to use during the transfer (Memory Mode Transfer and MemFile Mode Transfer). + /// Возникает в момент установки размера буфера памяти. /// [Category("Memory Mode Action")] - [Description("Возникает в момент установки размера буфера памяти. Occurs when determined size of buffer to use during the transfer (Memory Mode Transfer and MemFile Mode Transfer).")] + [Description("Occurs when determined size of buffer to use during the transfer (Memory Mode Transfer and MemFile Mode Transfer). Возникает в момент установки размера буфера памяти.")] public event EventHandler SetupMemXferEvent; /// - /// Возникает в момент получения очередного блока данных. Occurs when the memory block for the data was recived (Memory Mode Transfer and MemFile Mode Transfer). + /// Occurs when the memory block for the data was recived (Memory Mode Transfer and MemFile Mode Transfer). + /// Возникает в момент получения очередного блока данных. /// [Category("Memory Mode Action")] - [Description("Возникает в момент получения очередного блока данных. Occurs when the memory block for the data was recived (Memory Mode Transfer and MemFile Mode Transfer).")] + [Description("Occurs when the memory block for the data was recived (Memory Mode Transfer and MemFile Mode Transfer). Возникает в момент получения очередного блока данных.")] public event EventHandler MemXferEvent; /// - /// Возникает в момент, когда необходимо задать имя файла изображения. Occurs when you need to specify the filename (File Mode Transfer). + /// Occurs when you need to specify the filename (File Mode Transfer). + /// Возникает в момент, когда необходимо задать имя файла изображения. /// [Category("File Mode Action")] - [Description("Возникает в момент, когда необходимо задать имя файла изображения. Occurs when you need to specify the filename. (File Mode Transfer)")] + [Description("Occurs when you need to specify the filename. (File Mode Transfer) Возникает в момент, когда необходимо задать имя файла изображения.")] public event EventHandler SetupFileXferEvent; /// - /// Возникает в момент окончания получения файла изображения приложением. Occurs when the transfer into application was completed (File Mode Transfer). + /// Occurs when the transfer into application was completed (File Mode Transfer). + /// Возникает в момент окончания получения файла изображения приложением. /// [Category("File Mode Action")] - [Description("Возникает в момент окончания получения файла изображения приложением. Occurs when the transfer into application was completed (File Mode Transfer).")] + [Description("Occurs when the transfer into application was completed (File Mode Transfer). Возникает в момент окончания получения файла изображения приложением.")] public event EventHandler FileXferEvent; /// - /// Возникает в момент изменения состояния twain-устройства. Occurs when TWAIN state was changed. + /// Occurs when TWAIN state was changed. + /// Возникает в момент изменения состояния twain-устройства. /// [Category("Behavior")] - [Description("Возникает в момент изменения состояния twain-устройства. Occurs when TWAIN state was changed.")] + [Description("Occurs when TWAIN state was changed. Возникает в момент изменения состояния twain-устройства.")] public event EventHandler TwainStateChanged; /// - /// Возникает в момент, когда источник уведомляет приложение о произошедшем событии. Occurs when enabled the source sends this message to the Application to alert it that some event has taken place. + /// Occurs when enabled the source sends this message to the Application to alert it that some event has taken place. + /// Возникает в момент, когда источник уведомляет приложение о произошедшем событии. /// [Category("Behavior")] - [Description("Возникает в момент, когда источник уведомляет приложение о произошедшем событии. Occurs when enabled the source sends this message to the Application to alert it that some event has taken place.")] + [Description("Occurs when enabled the source sends this message to the Application to alert it that some event has taken place. Возникает в момент, когда источник уведомляет приложение о произошедшем событии.")] public event EventHandler DeviceEvent; #endregion @@ -1622,340 +1927,309 @@ public enum TwainStateFlag { #region Events Args /// - /// Аргументы события EndXfer. + /// Arguments for the EndXfer event. + /// Аргументы события EndXfer. /// [Serializable] - public sealed class EndXferEventArgs:SerializableCancelEventArgs { - private _Image _image; + public sealed class EndXferEventArgs : SerializableCancelEventArgs + { + private readonly _Image _image; /// - /// Инициализирует новый экземпляр класса. + /// Initializes a new instance of the class. + /// Инициализирует новый экземпляр класса. /// - /// Изображение. - internal EndXferEventArgs(object image) { - this._image=image as _Image; + /// Image.Изображение. + internal EndXferEventArgs(object image) + { + this._image = image as _Image; } + public T CreateImage(IImageFactory factory) where T : class => factory.Create(this._image); + /// - /// Возвращает изображение. + /// Returns the image. + /// Возвращает изображение. /// - public Image Image { - get { - return this._image; - } - } + public Image Image => this._image; #if !NET2 /// - /// Возвращает изображение. + /// Returns the image. + /// Возвращает изображение. /// - public System.Windows.Media.ImageSource ImageSource { - get { - return this._image; - } - } + public System.Windows.Media.ImageSource ImageSource => this._image; #endif } /// - /// Аргументы события XferDone. + /// Arguments for the XferDone event. + /// Аргументы события XferDone. /// - public sealed class XferDoneEventArgs:SerializableCancelEventArgs { - private GetImageInfoCallback _imageInfoMethod; - private GetExtImageInfoCallback _extImageInfoMethod; + public sealed class XferDoneEventArgs : SerializableCancelEventArgs + { + private readonly GetImageInfoCallback _imageInfoMethod; + private readonly GetExtImageInfoCallback _extImageInfoMethod; /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - /// Метод обратного вызова для получения описания изображения. - /// Метод обратного вызова для получения расширенного описания изображения. - internal XferDoneEventArgs(GetImageInfoCallback method1,GetExtImageInfoCallback method2) { - this._imageInfoMethod=method1; - this._extImageInfoMethod=method2; + /// Callback method to get image description.Метод обратного вызова для получения описания изображения. + /// Callback method to get an extended image description.Метод обратного вызова для получения расширенного описания изображения. + internal XferDoneEventArgs(GetImageInfoCallback method1, GetExtImageInfoCallback method2) + { + this._imageInfoMethod = method1; + this._extImageInfoMethod = method2; } /// - /// Возвращает описание полученного изображения. + /// Returns a description of the received image. + /// Возвращает описание полученного изображения. /// - /// Описание изображения. - public ImageInfo GetImageInfo() { - return this._imageInfoMethod(); - } + /// Description of the image.Описание изображения. + public ImageInfo GetImageInfo() => this._imageInfoMethod(); /// - /// Возвращает расширенного описание полученного изображения. + /// Returns an extended description of the resulting image. + /// Возвращает расширенного описание полученного изображения. /// - /// Набор кодов расширенного описания изображения для которых требуется получить описание. - /// Расширенное описание изображения. - public ExtImageInfo GetExtImageInfo(params TwEI[] extInfo) { - return this._extImageInfoMethod(extInfo); - } + /// A set of codes for the extended image description for which you want to get a description.Набор кодов расширенного описания изображения для которых требуется получить описание. + /// Extended image description.Расширенное описание изображения. + public ExtImageInfo GetExtImageInfo(params TwEI[] extInfo) => this._extImageInfoMethod(extInfo); } /// - /// Аргументы события SetupMemXferEvent. + /// Arguments for the SetupMemXferEvent event. + /// Аргументы события SetupMemXferEvent. /// [Serializable] - public sealed class SetupMemXferEventArgs:SerializableCancelEventArgs { + public sealed class SetupMemXferEventArgs : SerializableCancelEventArgs + { /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - /// Описание изображения. - /// Размер буфера памяти для передачи данных. - internal SetupMemXferEventArgs(ImageInfo info,uint bufferSize) { - this.ImageInfo=info; - this.BufferSize=bufferSize; + /// Description of the image.Описание изображения. + /// The size of the memory buffer for data transfer.Размер буфера памяти для передачи данных. + internal SetupMemXferEventArgs(ImageInfo info, uint bufferSize) + { + this.ImageInfo = info; + this.BufferSize = bufferSize; } /// - /// Возвращает описание изображения. + /// Returns a description of the image. + /// Возвращает описание изображения. /// - public ImageInfo ImageInfo { - get; - private set; - } + public ImageInfo ImageInfo { get; private set; } /// - /// Возвращает размер буфера памяти для передачи данных. + /// Gets the size of the memory buffer for data transfer. + /// Возвращает размер буфера памяти для передачи данных. /// - public uint BufferSize { - get; - private set; - } + public uint BufferSize { get; private set; } } /// - /// Аргументы события MemXferEvent. + /// Arguments for the MemXferEvent event. + /// Аргументы события MemXferEvent. /// [Serializable] - public sealed class MemXferEventArgs:SerializableCancelEventArgs { + public sealed class MemXferEventArgs : SerializableCancelEventArgs + { /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - /// Описание изображения. - /// Фрагмент данных изображения. - internal MemXferEventArgs(ImageInfo info,ImageMemXfer image) { - this.ImageInfo=info; - this.ImageMemXfer=image; + /// Description of the image.Описание изображения. + /// A fragment of image data.Фрагмент данных изображения. + internal MemXferEventArgs(ImageInfo info, ImageMemXfer image) + { + this.ImageInfo = info; + this.ImageMemXfer = image; } /// - /// Возвращает описание изображения. + /// Returns a description of the image. + /// Возвращает описание изображения. /// - public ImageInfo ImageInfo { - get; - private set; - } + public ImageInfo ImageInfo { get; private set; } /// - /// Возвращает фрагмент данных изображения. + /// Returns a piece of image data. + /// Возвращает фрагмент данных изображения. /// - public ImageMemXfer ImageMemXfer { - get; - private set; - } + public ImageMemXfer ImageMemXfer { get; private set; } } /// - /// Аргументы события SetupFileXferEvent. + /// Arguments for the SetupFileXferEvent event. + /// Аргументы события SetupFileXferEvent. /// [Serializable] - public sealed class SetupFileXferEventArgs:SerializableCancelEventArgs { + public sealed class SetupFileXferEventArgs : SerializableCancelEventArgs + { /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - internal SetupFileXferEventArgs() { + internal SetupFileXferEventArgs() + { } /// - /// Возвращает или устанавливает имя файла изображения. + /// Gets or sets the name of the image file. + /// Возвращает или устанавливает имя файла изображения. /// - public string FileName { - get; - set; - } + public string FileName { get; set; } } /// - /// Аргументы события FileXferEvent. + /// Arguments for the FileXferEvent event. + /// Аргументы события FileXferEvent. /// [Serializable] - public sealed class FileXferEventArgs:SerializableCancelEventArgs { + public sealed class FileXferEventArgs : SerializableCancelEventArgs + { /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - /// Описание файла изображения. - internal FileXferEventArgs(ImageFileXfer image) { - this.ImageFileXfer=image; + /// Description of the image file.Описание файла изображения. + internal FileXferEventArgs(ImageFileXfer image) + { + this.ImageFileXfer = image; } /// - /// Возвращает описание файла изображения. + /// Returns a description of the image file. + /// Возвращает описание файла изображения. /// - public ImageFileXfer ImageFileXfer { - get; - private set; - } + public ImageFileXfer ImageFileXfer { get; private set; } } /// - /// Аргументы события TwainStateChanged. + /// Arguments for the TwainStateChanged event. + /// Аргументы события TwainStateChanged. /// [Serializable] - public sealed class TwainStateEventArgs:EventArgs { + public sealed class TwainStateEventArgs : EventArgs + { /// - /// Инициализирует новый экземпляр класса. + /// Initializes a new instance of the class. + /// Инициализирует новый экземпляр класса. /// - /// Флаги состояния. - internal TwainStateEventArgs(TwainStateFlag flags) { - this.TwainState=flags; + /// State flags.Флаги состояния. + internal TwainStateEventArgs(TwainStateFlag flags) + { + this.TwainState = flags; } /// - /// Возвращает флаги состояния twain-устройства. + /// Returns the status flags of a twain device. + /// Возвращает флаги состояния twain-устройства. /// - public TwainStateFlag TwainState { - get; - private set; - } + public TwainStateFlag TwainState { get; private set; } } /// - /// Аргументы события DeviceEvent. + /// Arguments for the DeviceEvent event. + /// Аргументы события DeviceEvent. /// - public sealed class DeviceEventEventArgs:EventArgs { - private TwDeviceEvent _deviceEvent; + public sealed class DeviceEventEventArgs : EventArgs + { + private readonly TwDeviceEvent _deviceEvent; - internal DeviceEventEventArgs(TwDeviceEvent deviceEvent) { - this._deviceEvent=deviceEvent; + internal DeviceEventEventArgs(TwDeviceEvent deviceEvent) + { + this._deviceEvent = deviceEvent; } /// /// One of the TWDE_xxxx values. /// - public TwDE Event { - get { - return this._deviceEvent.Event; - } - } + public TwDE Event => this._deviceEvent.Event; /// /// The name of the device that generated the event. /// - public string DeviceName { - get { - return this._deviceEvent.DeviceName; - } - } + public string DeviceName => this._deviceEvent.DeviceName; /// /// Battery Minutes Remaining. /// - public uint BatteryMinutes { - get { - return this._deviceEvent.BatteryMinutes; - } - } + public uint BatteryMinutes => this._deviceEvent.BatteryMinutes; /// /// Battery Percentage Remaining. /// - public short BatteryPercentAge { - get { - return this._deviceEvent.BatteryPercentAge; - } - } + public short BatteryPercentAge => this._deviceEvent.BatteryPercentAge; /// /// Power Supply. /// - public int PowerSupply { - get { - return this._deviceEvent.PowerSupply; - } - } + public int PowerSupply => this._deviceEvent.PowerSupply; /// /// Resolution. /// - public float XResolution { - get { - return this._deviceEvent.XResolution; - } - } + public float XResolution => this._deviceEvent.XResolution; /// /// Resolution. /// - public float YResolution { - get { - return this._deviceEvent.YResolution; - } - } + public float YResolution => this._deviceEvent.YResolution; /// /// Flash Used2. /// - public uint FlashUsed2 { - get { - return this._deviceEvent.FlashUsed2; - } - } + public uint FlashUsed2 => this._deviceEvent.FlashUsed2; /// /// Automatic Capture. /// - public uint AutomaticCapture { - get { - return this._deviceEvent.AutomaticCapture; - } - } + public uint AutomaticCapture => this._deviceEvent.AutomaticCapture; /// /// Automatic Capture. /// - public uint TimeBeforeFirstCapture { - get { - return this._deviceEvent.TimeBeforeFirstCapture; - } - } + public uint TimeBeforeFirstCapture => this._deviceEvent.TimeBeforeFirstCapture; /// /// Automatic Capture. /// - public uint TimeBetweenCaptures { - get { - return this._deviceEvent.TimeBetweenCaptures; - } - } + public uint TimeBetweenCaptures => this._deviceEvent.TimeBetweenCaptures; } /// - /// Аргументы события AcquireError. + /// Arguments for the AcquireError event. + /// Аргументы события AcquireError. /// [Serializable] - public sealed class AcquireErrorEventArgs:EventArgs { + public sealed class AcquireErrorEventArgs : EventArgs + { /// - /// Инициализирует новый экземпляр класса. + /// Initializes a new instance of the class. + /// Инициализирует новый экземпляр класса. /// - /// Экземпляр класса исключения. - internal AcquireErrorEventArgs(TwainException ex) { - this.Exception=ex; + /// An instance of the exception class.Экземпляр класса исключения. + internal AcquireErrorEventArgs(TwainException ex) + { + this.Exception = ex; } /// - /// Возвращает экземпляр класса исключения. + /// Gets an instance of the exception class. + /// Возвращает экземпляр класса исключения. /// - public TwainException Exception { - get; - private set; - } + public TwainException Exception { get; private set; } } /// @@ -1963,18 +2237,17 @@ public TwainException Exception { /// /// [Serializable] - public class SerializableCancelEventArgs:EventArgs { + public class SerializableCancelEventArgs : EventArgs + { /// - /// Получает или задает значение, показывающее, следует ли отменить событие. Gets or sets a value indicating whether the event should be canceled. + /// Gets or sets a value indicating whether the event should be canceled. + /// Получает или задает значение, показывающее, следует ли отменить событие. /// /// - /// Значение true, если событие следует отменить, в противном случае — значение false. true if cancel; otherwise, false. + /// Значение true, если событие следует отменить, в противном случае — значение false. /// - public bool Cancel { - get; - set; - } + public bool Cancel { get; set; } } #endregion @@ -1982,164 +2255,198 @@ public bool Cancel { #region Nested classes /// - /// Точки входа для работы с DSM. + /// Entry points for working with DSM. + /// Точки входа для работы с DSM. /// - private sealed class _DsmEntry { + private sealed class _DsmEntry + { /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - /// Указатель на DSM_Entry. - private _DsmEntry(IntPtr ptr) { - switch(Environment.OSVersion.Platform) { + /// Pointer to DSM_Entry.Указатель на DSM_Entry. + private _DsmEntry(IntPtr ptr) + { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - this.DsmParent=_DsmEntry._LinuxDsmParent; - this.DsmRaw=_DsmEntry._LinuxDsmRaw; - this.DSImageXfer=_DsmEntry._LinuxDsImageXfer; - this.DsRaw=_DsmEntry._LinuxDsRaw; + this.DsmParent = _DsmEntry._LinuxDsmParent; + this.DsmRaw = _DsmEntry._LinuxDsmRaw; + this.DSImageXfer = _DsmEntry._LinuxDsImageXfer; + this.DsRaw = _DsmEntry._LinuxDsRaw; break; case PlatformID.MacOSX: - throw new NotImplementedException(); + this.DsmParent = _DsmEntry._MacosxDsmParent; + this.DsmRaw = _DsmEntry._MacosxDsmRaw; + this.DSImageXfer = _DsmEntry._MacosxDsImageXfer; + this.DsRaw = _DsmEntry._MacosxDsRaw; + break; default: - MethodInfo _createDelegate=typeof(_DsmEntry).GetMethod("CreateDelegate",BindingFlags.Static|BindingFlags.NonPublic); - foreach(PropertyInfo _prop in typeof(_DsmEntry).GetProperties()) { - _prop.SetValue(this,_createDelegate.MakeGenericMethod(_prop.PropertyType).Invoke(this,new object[] { ptr }),null); + MethodInfo _createDelegate = typeof(_DsmEntry).GetMethod("CreateDelegate", BindingFlags.Static | BindingFlags.NonPublic); + foreach (PropertyInfo _prop in typeof(_DsmEntry).GetProperties()) + { + _prop.SetValue(this, _createDelegate.MakeGenericMethod(_prop.PropertyType).Invoke(this, new object[] { ptr }), null); } break; } } /// - /// Создает и возвращает новый экземпляр класса . + /// Creates and returns a new instance of the class . + /// Создает и возвращает новый экземпляр класса . /// - /// Указатель на DSM_Entry. - /// Экземпляр класса . - public static _DsmEntry Create(IntPtr ptr) { - return new _DsmEntry(ptr); - } + /// Pointer to DSM_Entry.Указатель на DSM_Entry. + /// Class instance .Экземпляр класса . + public static _DsmEntry Create(IntPtr ptr) => new _DsmEntry(ptr); /// - /// Приводит указатель к требуемомы делегату. + /// Casts a pointer to the requested delegate. + /// Приводит указатель к требуемомы делегату. /// /// Требуемый делегат. - /// Указатель на DSM_Entry. - /// Делегат. - private static T CreateDelegate(IntPtr ptr) where T:class { - return Marshal.GetDelegateForFunctionPointer(ptr,typeof(T)) as T; - } + /// Pointer to DSM_Entry.Указатель на DSM_Entry. + /// Delegate.Делегат. + private static T CreateDelegate(IntPtr ptr) where T : class => Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T; - public TwRC DsmInvoke(TwIdentity origin,TwDG dg,TwDAT dat,TwMSG msg,ref T data) where T:class { - if(data==null) { + public TwRC DsmInvoke(TwIdentity origin, TwDG dg, TwDAT dat, TwMSG msg, ref T data) where T : class + { + if (data == null) + { throw new ArgumentNullException(); } - IntPtr _data=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T))); - try { - Marshal.StructureToPtr(data,_data,true); + IntPtr _data = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T))); + try + { + Marshal.StructureToPtr(data, _data, true); - TwRC _rc=this.DsmRaw(origin,IntPtr.Zero,dg,dat,msg,_data); - if(_rc==TwRC.Success) { - data=(T)Marshal.PtrToStructure(_data,typeof(T)); + TwRC _rc = this.DsmRaw(origin, IntPtr.Zero, dg, dat, msg, _data); + if (_rc == TwRC.Success) + { + data = (T)Marshal.PtrToStructure(_data, typeof(T)); } return _rc; - } finally { + } + finally + { Marshal.FreeHGlobal(_data); } } - public TwRC DsInvoke(TwIdentity origin,TwIdentity dest,TwDG dg,TwDAT dat,TwMSG msg,ref T data) where T:class { - if(data==null) { + public TwRC DsInvoke(TwIdentity origin, TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref T data) where T : class + { + if (data == null) + { throw new ArgumentNullException(); } - IntPtr _data=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T))); - try { - Marshal.StructureToPtr(data,_data,true); + IntPtr _data = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T))); + try + { + Marshal.StructureToPtr(data, _data, true); - TwRC _rc=this.DsRaw(origin,dest,dg,dat,msg,_data); - if(_rc==TwRC.Success||_rc==TwRC.DSEvent||_rc==TwRC.XferDone) { - data=(T)Marshal.PtrToStructure(_data,typeof(T)); + TwRC _rc = this.DsRaw(origin, dest, dg, dat, msg, _data); + if (_rc == TwRC.Success || _rc == TwRC.DSEvent || _rc == TwRC.XferDone) + { + data = (T)Marshal.PtrToStructure(_data, typeof(T)); } return _rc; - } finally { + } + finally + { Marshal.FreeHGlobal(_data); } } #region Properties - public _DSMparent DsmParent { - get; - private set; - } + public _DSMparent DsmParent { get; private set; } - public _DSMraw DsmRaw { - get; - private set; - } + public _DSMraw DsmRaw { get; private set; } - public _DSixfer DSImageXfer { - get; - private set; - } + public _DSixfer DSImageXfer { get; private set; } - public _DSraw DsRaw { - get; - private set; - } + public _DSraw DsRaw { get; private set; } #endregion - #region import libtwaindsm.so + #region import libtwaindsm.so (Unix) - [DllImport("/usr/local/lib/libtwaindsm.so",EntryPoint="DSM_Entry",CharSet=CharSet.Ansi)] - private static extern TwRC _LinuxDsmParent([In,Out] TwIdentity origin,IntPtr zeroptr,TwDG dg,TwDAT dat,TwMSG msg,ref IntPtr refptr); + [DllImport("/usr/local/lib/libtwaindsm.so", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _LinuxDsmParent([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr); - [DllImport("/usr/local/lib/libtwaindsm.so",EntryPoint="DSM_Entry",CharSet=CharSet.Ansi)] - private static extern TwRC _LinuxDsmRaw([In,Out] TwIdentity origin,IntPtr zeroptr,TwDG dg,TwDAT dat,TwMSG msg,IntPtr rawData); + [DllImport("/usr/local/lib/libtwaindsm.so", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _LinuxDsmRaw([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, IntPtr rawData); - [DllImport("/usr/local/lib/libtwaindsm.so",EntryPoint="DSM_Entry",CharSet=CharSet.Ansi)] - private static extern TwRC _LinuxDsImageXfer([In,Out] TwIdentity origin,[In,Out] TwIdentity dest,TwDG dg,TwDAT dat,TwMSG msg,ref IntPtr hbitmap); + [DllImport("/usr/local/lib/libtwaindsm.so", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _LinuxDsImageXfer([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap); - [DllImport("/usr/local/lib/libtwaindsm.so",EntryPoint="DSM_Entry",CharSet=CharSet.Ansi)] - private static extern TwRC _LinuxDsRaw([In,Out] TwIdentity origin,[In,Out] TwIdentity dest,TwDG dg,TwDAT dat,TwMSG msg,IntPtr arg); + [DllImport("/usr/local/lib/libtwaindsm.so", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _LinuxDsRaw([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, IntPtr arg); + + #endregion + + #region import TWAIN.framework/TWAIN (MacOSX) + + [DllImport("/System/Library/Frameworks/TWAIN.framework/TWAIN", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _MacosxDsmParent([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr); + + [DllImport("/System/Library/Frameworks/TWAIN.framework/TWAIN", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _MacosxDsmRaw([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, IntPtr rawData); + + [DllImport("/System/Library/Frameworks/TWAIN.framework/TWAIN", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _MacosxDsImageXfer([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap); + + [DllImport("/System/Library/Frameworks/TWAIN.framework/TWAIN", EntryPoint = "DSM_Entry", CharSet = CharSet.Ansi)] + private static extern TwRC _MacosxDsRaw([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, IntPtr arg); #endregion } /// - /// Точки входа для функций управления памятью. + /// Entry points for memory management functions. + /// Точки входа для функций управления памятью. /// - internal sealed class _Memory { + internal sealed class _Memory + { private static TwEntryPoint _entryPoint; /// - /// Выделяет блок памяти указанного размера. + /// Allocates a memory block of the specified size. + /// Выделяет блок памяти указанного размера. /// - /// Размер блока памяти. - /// Дескриптор памяти. - public static IntPtr Alloc(int size) { - if(_Memory._entryPoint!=null&&_Memory._entryPoint.MemoryAllocate!=null) { + /// The size of the memory block.Размер блока памяти. + /// Memory descriptor.Дескриптор памяти. + public static IntPtr Alloc(int size) + { + if (_Memory._entryPoint != null && _Memory._entryPoint.MemoryAllocate != null) + { return _Memory._entryPoint.MemoryAllocate(size); } - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: case PlatformID.MacOSX: throw new NotSupportedException(); default: - return _Memory.GlobalAlloc(0x42,size); + return _Memory.GlobalAlloc(0x42, size); } } /// - /// Освобождает память. + /// Frees up memory. + /// Освобождает память. /// - /// Дескриптор памяти. - public static void Free(IntPtr handle) { - if(_Memory._entryPoint!=null&&_Memory._entryPoint.MemoryFree!=null) { + /// Memory descriptor.Дескриптор памяти. + public static void Free(IntPtr handle) + { + if (_Memory._entryPoint != null && _Memory._entryPoint.MemoryFree != null) + { _Memory._entryPoint.MemoryFree(handle); return; } - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: case PlatformID.MacOSX: throw new NotSupportedException(); @@ -2150,15 +2457,19 @@ public static void Free(IntPtr handle) { } /// - /// Выполняет блокировку памяти. + /// Performs a memory lock. + /// Выполняет блокировку памяти. /// - /// Дескриптор памяти. - /// Указатель на блок памяти. - public static IntPtr Lock(IntPtr handle) { - if(_Memory._entryPoint!=null&&_Memory._entryPoint.MemoryLock!=null) { + /// Memory descriptor.Дескриптор памяти. + /// Pointer to a block of memory.Указатель на блок памяти. + public static IntPtr Lock(IntPtr handle) + { + if (_Memory._entryPoint != null && _Memory._entryPoint.MemoryLock != null) + { return _Memory._entryPoint.MemoryLock(handle); } - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: case PlatformID.MacOSX: throw new NotSupportedException(); @@ -2168,15 +2479,19 @@ public static IntPtr Lock(IntPtr handle) { } /// - /// Выполняет разблокировку памяти. + /// Unlocks memory. + /// Выполняет разблокировку памяти. /// - /// Дескриптор памяти. - public static void Unlock(IntPtr handle) { - if(_Memory._entryPoint!=null&&_Memory._entryPoint.MemoryUnlock!=null) { + /// Memory descriptor.Дескриптор памяти. + public static void Unlock(IntPtr handle) + { + if (_Memory._entryPoint != null && _Memory._entryPoint.MemoryUnlock != null) + { _Memory._entryPoint.MemoryUnlock(handle); return; } - switch(Environment.OSVersion.Platform) { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: case PlatformID.MacOSX: throw new NotSupportedException(); @@ -2186,81 +2501,86 @@ public static void Unlock(IntPtr handle) { } } - public static void ZeroMemory(IntPtr dest,IntPtr size) { - switch(Environment.OSVersion.Platform) { + public static void ZeroMemory(IntPtr dest, IntPtr size) + { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - byte[] _data=new byte[size.ToInt32()]; - Marshal.Copy(_data,0,dest,_data.Length); - break; case PlatformID.MacOSX: - throw new NotImplementedException(); + byte[] _data = new byte[size.ToInt32()]; + Marshal.Copy(_data, 0, dest, _data.Length); + break; default: - _Memory._ZeroMemory(dest,size); + _Memory._ZeroMemory(dest, size); break; } } /// - /// Устаначливает точки входа. + /// Sets entry points. + /// Устаначливает точки входа. /// - /// Точки входа. - internal static void _SetEntryPoints(TwEntryPoint entry) { - _Memory._entryPoint=entry; - } + /// Entry points.Точки входа. + internal static void _SetEntryPoints(TwEntryPoint entry) => _Memory._entryPoint = entry; #region import kernel32.dll - [DllImport("kernel32.dll",ExactSpelling=true)] - private static extern IntPtr GlobalAlloc(int flags,int size); + [DllImport("kernel32.dll", ExactSpelling = true)] + private static extern IntPtr GlobalAlloc(int flags, int size); - [DllImport("kernel32.dll",ExactSpelling=true)] + [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GlobalLock(IntPtr handle); - [DllImport("kernel32.dll",ExactSpelling=true)] + [DllImport("kernel32.dll", ExactSpelling = true)] private static extern bool GlobalUnlock(IntPtr handle); - [DllImport("kernel32.dll",ExactSpelling=true)] + [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GlobalFree(IntPtr handle); - [DllImport("kernel32.dll",EntryPoint="RtlZeroMemory",SetLastError=false)] - private static extern void _ZeroMemory(IntPtr dest,IntPtr size); + [DllImport("kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false)] + private static extern void _ZeroMemory(IntPtr dest, IntPtr size); #endregion } /// - /// Точки входа для функций платформы. + /// Entry points for platform features. + /// Точки входа для функций платформы. /// - internal sealed class _Platform { + internal sealed class _Platform + { /// - /// Загружает указаную библиотеку в память процесса. + /// Loads the specified library into the process memory. + /// Загружает указаную библиотеку в память процесса. /// - /// Имя библиотеки. - /// Дескриптор модуля. - internal static IntPtr Load(string fileName) { - switch(Environment.OSVersion.Platform) { + /// The name of the library.Имя библиотеки. + /// Module descriptor.Дескриптор модуля. + internal static IntPtr Load(string fileName) + { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - return _Platform.dlopen(fileName,0x01); case PlatformID.MacOSX: - throw new NotImplementedException(); + throw new NotSupportedException(); default: return _Platform.LoadLibrary(fileName); } } /// - /// Выгружает указаную библиотеку из памяти процесса. + /// Unloads the specified library from the process memory. + /// Выгружает указаную библиотеку из памяти процесса. /// - /// Дескриптор модуля - internal static void Unload(IntPtr hModule) { - switch(Environment.OSVersion.Platform) { + /// Module descriptorДескриптор модуля + internal static void Unload(IntPtr hModule) + { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - _Platform.dlclose(hModule); - break; case PlatformID.MacOSX: - throw new NotImplementedException(); + break; default: _Platform.FreeLibrary(hModule); break; @@ -2268,68 +2588,69 @@ internal static void Unload(IntPtr hModule) { } /// - /// Возвращает адрес указанной процедуры. + /// Returns the address of the specified procedure. + /// Возвращает адрес указанной процедуры. /// - /// Дескриптор модуля. - /// Имя процедуры. - /// Указатель на процедуру. - internal static IntPtr GetProcAddr(IntPtr hModule,string procName) { - switch(Environment.OSVersion.Platform) { + /// Module descriptor.Дескриптор модуля. + /// The name of the procedure.Имя процедуры. + /// Pointer to a procedure.Указатель на процедуру. + internal static IntPtr GetProcAddr(IntPtr hModule, string procName) + { + switch (Environment.OSVersion.Platform) + { case PlatformID.Unix: - return _Platform.dlsym(hModule,procName); case PlatformID.MacOSX: - throw new NotImplementedException(); + throw new NotSupportedException(); default: - return _Platform.GetProcAddress(hModule,procName); + return _Platform.GetProcAddress(hModule, procName); } } - [DllImport("kernel32.dll",CharSet=CharSet.Unicode)] + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr LoadLibrary(string fileName); - [DllImport("kernel32.dll",ExactSpelling=true)] + [DllImport("kernel32.dll", ExactSpelling = true)] private static extern bool FreeLibrary(IntPtr hModule); - [DllImport("kernel32.dll",CharSet=CharSet.Ansi,ExactSpelling=true)] - private static extern IntPtr GetProcAddress(IntPtr hModule,string procName); - - [DllImport("libdl.so")] - private static extern IntPtr dlopen(string fileName,int flags); - - [DllImport("libdl.so")] - private static extern bool dlclose(IntPtr hModule); - - [DllImport("libdl.so")] - private static extern IntPtr dlsym(IntPtr hModule,string procName); + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); } /// - /// Фильтр win32-сообщений. + /// Win32 message filter. + /// Фильтр win32-сообщений. /// - private sealed class _MessageFilter:IMessageFilter,IDisposable { + private sealed class _MessageFilter : IMessageFilter, IDisposable + { private Twain32 _twain; - private bool _is_set_filter=false; - private TwEvent _evtmsg=new TwEvent(); + private bool _is_set_filter = false; + private TwEvent _evtmsg = new TwEvent(); - public _MessageFilter(Twain32 twain) { - this._twain=twain; - this._evtmsg.EventPtr=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINMSG))); + public _MessageFilter(Twain32 twain) + { + this._twain = twain; + this._evtmsg.EventPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINMSG))); } #region IMessageFilter - public bool PreFilterMessage(ref Message m) { - try { - if(this._twain._srcds.Id==0) { + public bool PreFilterMessage(ref Message m) + { + try + { + if (this._twain._srcds.Id == 0) + { return false; } - Marshal.StructureToPtr(new WINMSG {hwnd=m.HWnd,message=m.Msg,wParam=m.WParam,lParam=m.LParam},this._evtmsg.EventPtr,true); - this._evtmsg.Message=TwMSG.Null; + Marshal.StructureToPtr(new WINMSG { hwnd = m.HWnd, message = m.Msg, wParam = m.WParam, lParam = m.LParam }, this._evtmsg.EventPtr, true); + this._evtmsg.Message = TwMSG.Null; - switch(this._twain._dsmEntry.DsInvoke(this._twain._AppId,this._twain._srcds,TwDG.Control,TwDAT.Event,TwMSG.ProcessEvent,ref this._evtmsg)) { + switch (this._twain._dsmEntry.DsInvoke(this._twain._AppId, this._twain._srcds, TwDG.Control, TwDAT.Event, TwMSG.ProcessEvent, ref this._evtmsg)) + { case TwRC.DSEvent: - this._twain._TwCallbackProcCore(this._evtmsg.Message,isCloseReq => { - if(isCloseReq||this._twain.DisableAfterAcquire) { + this._twain._TwCallbackProcCore(this._evtmsg.Message, isCloseReq => { + if (isCloseReq || this._twain.DisableAfterAcquire) + { this._RemoveFilter(); this._twain._DisableDataSource(); } @@ -2338,14 +2659,18 @@ public bool PreFilterMessage(ref Message m) { case TwRC.NotDSEvent: return false; case TwRC.Failure: - throw new TwainException(this._twain._GetTwainStatus(),TwRC.Failure); + throw new TwainException(this._twain._GetTwainStatus(), TwRC.Failure); default: throw new InvalidOperationException("Получен неверный код результата операции. Invalid a Return Code value."); } - } catch(TwainException ex) { + } + catch (TwainException ex) + { this._twain._OnAcquireError(new AcquireErrorEventArgs(ex)); - } catch(Exception ex) { - this._twain._OnAcquireError(new AcquireErrorEventArgs(new TwainException(ex.Message,ex))); + } + catch (Exception ex) + { + this._twain._OnAcquireError(new AcquireErrorEventArgs(new TwainException(ex.Message, ex))); } return true; } @@ -2354,29 +2679,35 @@ public bool PreFilterMessage(ref Message m) { #region IDisposable - public void Dispose() { - if(this._evtmsg!=null&&this._evtmsg.EventPtr!=IntPtr.Zero) { + public void Dispose() + { + if (this._evtmsg != null && this._evtmsg.EventPtr != IntPtr.Zero) + { Marshal.FreeHGlobal(this._evtmsg.EventPtr); - this._evtmsg.EventPtr=IntPtr.Zero; + this._evtmsg.EventPtr = IntPtr.Zero; } } #endregion - public void SetFilter() { - if(!this._is_set_filter) { - this._is_set_filter=true; + public void SetFilter() + { + if (!this._is_set_filter) + { + this._is_set_filter = true; Application.AddMessageFilter(this); } } - private void _RemoveFilter() { + private void _RemoveFilter() + { Application.RemoveMessageFilter(this); - this._is_set_filter=false; + this._is_set_filter = false; } - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal struct WINMSG { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal struct WINMSG + { public IntPtr hwnd; public int message; public IntPtr wParam; @@ -2385,7 +2716,8 @@ internal struct WINMSG { } [Serializable] - private sealed class _Image { + private sealed class _Image + { private Stream _stream = null; [NonSerialized] @@ -2395,29 +2727,38 @@ private sealed class _Image { private System.Windows.Media.Imaging.BitmapImage _image2 = null; #endif - private _Image() { + private _Image() + { } - public static implicit operator _Image(Stream stream) { - return new _Image { _stream=stream }; + public static implicit operator _Image(Stream stream) => new _Image { _stream = stream }; + + public static implicit operator Stream(_Image image) + { + image._stream.Seek(0L, SeekOrigin.Begin); + return image._stream; } - public static implicit operator Image(_Image value) { - if(value._image==null) { - value._stream.Seek(0L,SeekOrigin.Begin); - value._image=Image.FromStream(value._stream); + public static implicit operator Image(_Image value) + { + if (value._image == null) + { + value._stream.Seek(0L, SeekOrigin.Begin); + value._image = Image.FromStream(value._stream); } return value._image; } #if !NET2 - public static implicit operator System.Windows.Media.ImageSource(_Image value) { - if(value._image2==null) { - value._stream.Seek(0L,SeekOrigin.Begin); - value._image2=new System.Windows.Media.Imaging.BitmapImage(); + public static implicit operator System.Windows.Media.ImageSource(_Image value) + { + if (value._image2 == null) + { + value._stream.Seek(0L, SeekOrigin.Begin); + value._image2 = new System.Windows.Media.Imaging.BitmapImage(); value._image2.BeginInit(); - value._image2.StreamSource=value._stream; - value._image2.CacheOption=System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; + value._image2.StreamSource = value._stream; + value._image2.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; value._image2.EndInit(); value._image2.Freeze(); } @@ -2427,273 +2768,283 @@ public static implicit operator System.Windows.Media.ImageSource(_Image value) { } /// - /// Диапазон значений. + /// Range of values. + /// Диапазон значений. /// [Serializable] - public sealed class Range { + public sealed class Range + { /// /// Prevents a default instance of the class from being created. /// - private Range() { + private Range() + { } /// /// Prevents a default instance of the class from being created. /// /// The range. - private Range(TwRange range) { - this.MinValue=TwTypeHelper.CastToCommon(range.ItemType,TwTypeHelper.ValueToTw(range.ItemType,range.MinValue)); - this.MaxValue=TwTypeHelper.CastToCommon(range.ItemType,TwTypeHelper.ValueToTw(range.ItemType,range.MaxValue)); - this.StepSize=TwTypeHelper.CastToCommon(range.ItemType,TwTypeHelper.ValueToTw(range.ItemType,range.StepSize)); - this.CurrentValue=TwTypeHelper.CastToCommon(range.ItemType,TwTypeHelper.ValueToTw(range.ItemType,range.CurrentValue)); - this.DefaultValue=TwTypeHelper.CastToCommon(range.ItemType,TwTypeHelper.ValueToTw(range.ItemType,range.DefaultValue)); - } - - /// - /// Создает и возвращает экземпляр . - /// - /// Экземпляр . - /// Экземпляр . - internal static Range CreateRange(TwRange range) { - return new Range(range); - } - - /// - /// Создает и возвращает экземпляр . - /// - /// Минимальное значение. - /// Максимальное значение. - /// Шаг. - /// Значение по умолчанию. - /// Текущее значение. - /// Экземпляр . - public static Range CreateRange(object minValue,object maxValue,object stepSize,object defaultValue,object currentValue) { - return new Range() { - MinValue=minValue, MaxValue=maxValue, StepSize=stepSize, DefaultValue=defaultValue, CurrentValue=currentValue - }; - } + private Range(TwRange range) + { + this.MinValue = TwTypeHelper.CastToCommon(range.ItemType, TwTypeHelper.ValueToTw(range.ItemType, range.MinValue)); + this.MaxValue = TwTypeHelper.CastToCommon(range.ItemType, TwTypeHelper.ValueToTw(range.ItemType, range.MaxValue)); + this.StepSize = TwTypeHelper.CastToCommon(range.ItemType, TwTypeHelper.ValueToTw(range.ItemType, range.StepSize)); + this.CurrentValue = TwTypeHelper.CastToCommon(range.ItemType, TwTypeHelper.ValueToTw(range.ItemType, range.CurrentValue)); + this.DefaultValue = TwTypeHelper.CastToCommon(range.ItemType, TwTypeHelper.ValueToTw(range.ItemType, range.DefaultValue)); + } + + /// + /// Creates and returns an instance . + /// Создает и возвращает экземпляр . + /// + /// Instance .Экземпляр . + /// Instance .Экземпляр . + internal static Range CreateRange(TwRange range) => new Range(range); + + /// + /// Creates and returns an instance . + /// Создает и возвращает экземпляр . + /// + /// Minimum value.Минимальное значение. + /// The maximum value.Максимальное значение. + /// Step.Шаг. + /// The default value.Значение по умолчанию. + /// Present value.Текущее значение. + /// Instance .Экземпляр . + public static Range CreateRange(object minValue, object maxValue, object stepSize, object defaultValue, object currentValue) => new Range() + { + MinValue = minValue, + MaxValue = maxValue, + StepSize = stepSize, + DefaultValue = defaultValue, + CurrentValue = currentValue + }; /// - /// Возвращает или устанавливает минимальное значение. + /// Gets or sets the minimum value. + /// Возвращает или устанавливает минимальное значение. /// - public object MinValue { - get; - set; - } + public object MinValue { get; set; } /// - /// Возвращает или устанавливает максимальное значение. + /// Gets or sets the maximum value. + /// Возвращает или устанавливает максимальное значение. /// - public object MaxValue { - get; - set; - } + public object MaxValue { get; set; } /// - /// Возвращает или устанавливает шаг. + /// Gets or sets the step. + /// Возвращает или устанавливает шаг. /// - public object StepSize { - get; - set; - } + public object StepSize { get; set; } /// - /// Возвращает или устанавливает значае по умолчанию. + /// Gets or sets the default value. + /// Возвращает или устанавливает значае по умолчанию. /// - public object DefaultValue { - get; - set; - } + public object DefaultValue { get; set; } /// - /// Возвращает или устанавливает текущее значение. + /// Gets or sets the current value. + /// Возвращает или устанавливает текущее значение. /// - public object CurrentValue { - get; - set; - } + public object CurrentValue { get; set; } /// - /// Конвертирует экземпляр класса в экземпляр . + /// Converts an instance of a class to an instance . + /// Конвертирует экземпляр класса в экземпляр . /// - /// Экземпляр . - internal TwRange ToTwRange() { - TwType _type=TwTypeHelper.TypeOf(this.CurrentValue.GetType()); - return new TwRange() { - ItemType=_type, - MinValue=TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type,this.MinValue)), - MaxValue=TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type,this.MaxValue)), - StepSize=TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type,this.StepSize)), - DefaultValue=TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type,this.DefaultValue)), - CurrentValue=TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type,this.CurrentValue)) + /// Instance .Экземпляр . + internal TwRange ToTwRange() + { + TwType _type = TwTypeHelper.TypeOf(this.CurrentValue.GetType()); + return new TwRange() + { + ItemType = _type, + MinValue = TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type, this.MinValue)), + MaxValue = TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type, this.MaxValue)), + StepSize = TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type, this.StepSize)), + DefaultValue = TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type, this.DefaultValue)), + CurrentValue = TwTypeHelper.ValueFromTw(TwTypeHelper.CastToTw(_type, this.CurrentValue)) }; } } /// - /// Перечисление. + /// Enumeration. + /// Перечисление. /// [Serializable] - public sealed class Enumeration { + public sealed class Enumeration + { private object[] _items; /// /// Prevents a default instance of the class from being created. /// - /// Элементы перечисления. - /// Текущий индекс. - /// Индекс по умолчанию. - private Enumeration(object[] items,int currentIndex,int defaultIndex) { - this._items=items; - this.CurrentIndex=currentIndex; - this.DefaultIndex=defaultIndex; + /// Listing items.Элементы перечисления. + /// Current index.Текущий индекс. + /// The default index.Индекс по умолчанию. + private Enumeration(object[] items, int currentIndex, int defaultIndex) + { + this._items = items; + this.CurrentIndex = currentIndex; + this.DefaultIndex = defaultIndex; } /// - /// Создает и возвращает экземпляр . + /// Creates and returns an instance . + /// Создает и возвращает экземпляр . /// - /// Элементы перечисления. - /// Текущий индекс. - /// Индекс по умолчанию. - /// Экземпляр . - public static Enumeration CreateEnumeration(object[] items,int currentIndex,int defaultIndex) { - return new Enumeration(items,currentIndex,defaultIndex); - } + /// Listing items.Элементы перечисления. + /// Current index.Текущий индекс. + /// The default index.Индекс по умолчанию. + /// Instance .Экземпляр . + public static Enumeration CreateEnumeration(object[] items, int currentIndex, int defaultIndex) => new Enumeration(items, currentIndex, defaultIndex); /// - /// Возвращает количество элементов. + /// Returns the number of items. + /// Возвращает количество элементов. /// - public int Count { - get { - return this._items.Length; - } - } + public int Count => this._items.Length; /// - /// Возвращает текущий индекс. + /// Returns the current index. + /// Возвращает текущий индекс. /// - public int CurrentIndex { - get; - private set; - } + public int CurrentIndex { get; private set; } /// - /// Возвращает индекс по умолчанию. + /// Returns the default index. + /// Возвращает индекс по умолчанию. /// - public int DefaultIndex { - get; - private set; - } + public int DefaultIndex { get; private set; } /// - /// Возвращает элемент по указанному индексу. + /// Returns the element at the specified index. + /// Возвращает элемент по указанному индексу. /// - /// Индекс. - /// Элемент по указанному индексу. - public object this[int index] { - get { + /// Index.Индекс. + /// The item at the specified index.Элемент по указанному индексу. + public object this[int index] + { + get + { return this._items[index]; } - internal set { - this._items[index]=value; + internal set + { + this._items[index] = value; } } - internal object[] Items { - get { - return this._items; - } - } + internal object[] Items => this._items; /// - /// Создает и возвращает экземпляр . + /// Creates and returns an instance . + /// Создает и возвращает экземпляр . /// - /// Экземпляр . - /// Экземпляр . - public static Enumeration FromRange(Range value) { - int _currentIndex=0,_defaultIndex=0; - object[] _items=new object[(int)((Convert.ToSingle(value.MaxValue)-Convert.ToSingle(value.MinValue))/Convert.ToSingle(value.StepSize))]; - for(int i=0; i<_items.Length; i++) { - _items[i]=Convert.ToSingle(value.MinValue)+(Convert.ToSingle(value.StepSize)*(float)i); - if(Convert.ToSingle(_items[i])==Convert.ToSingle(value.CurrentValue)) { - _currentIndex=i; + /// Instance .Экземпляр . + /// Instance .Экземпляр . + public static Enumeration FromRange(Range value) + { + int _currentIndex = 0, _defaultIndex = 0; + object[] _items = new object[(int)((Convert.ToSingle(value.MaxValue) - Convert.ToSingle(value.MinValue)) / Convert.ToSingle(value.StepSize)) + 1]; + for (int i = 0; i < _items.Length; i++) + { + _items[i] = Convert.ToSingle(value.MinValue) + (Convert.ToSingle(value.StepSize) * i); + if (Convert.ToSingle(_items[i]) == Convert.ToSingle(value.CurrentValue)) + { + _currentIndex = i; } - if(Convert.ToSingle(_items[i])==Convert.ToSingle(value.DefaultValue)) { - _defaultIndex=i; + if (Convert.ToSingle(_items[i]) == Convert.ToSingle(value.DefaultValue)) + { + _defaultIndex = i; } } - return Enumeration.CreateEnumeration(_items,_currentIndex,_defaultIndex); + return Enumeration.CreateEnumeration(_items, _currentIndex, _defaultIndex); } /// - /// Создает и возвращает экземпляр . + /// Creates and returns an instance . + /// Создает и возвращает экземпляр . /// - /// Массив значений. - /// Экземпляр . - public static Enumeration FromArray(object[] value) { - return Enumeration.CreateEnumeration(value, 0, 0); - } + /// An array of values.Массив значений. + /// Instance .Экземпляр . + public static Enumeration FromArray(object[] value) => Enumeration.CreateEnumeration(value, 0, 0); /// - /// Создает и возвращает экземпляр . + /// Creates and returns an instance . + /// Создает и возвращает экземпляр . /// - /// Значение. - /// Экземпляр . - public static Enumeration FromOneValue(ValueType value) { + /// Value.Значение. + /// Instance .Экземпляр . + public static Enumeration FromOneValue(ValueType value) + { return Enumeration.CreateEnumeration(new object[] { value }, 0, 0); } - internal static Enumeration FromObject(object value) { - if(value is Range) { - return Enumeration.FromRange((Range)value); + internal static Enumeration FromObject(object value) + { + if (value is Range _v1) + { + return Enumeration.FromRange(_v1); } - if(value is object[]) { - return Enumeration.FromArray((object[])value); + if (value is object[] _v2) + { + return Enumeration.FromArray(_v2); } - if(value is ValueType) { - return Enumeration.FromOneValue((ValueType)value); + if (value is ValueType _v3) + { + return Enumeration.FromOneValue(_v3); } - if(value is string) { - return Enumeration.CreateEnumeration(new object[] { value },0,0); + if (value is string) + { + return Enumeration.CreateEnumeration(new object[] { value }, 0, 0); } return value as Enumeration; } } /// - /// Описание изображения. + /// Description of the image. + /// Описание изображения. /// [Serializable] - public sealed class ImageInfo { - - private ImageInfo() { - } - - /// - /// Создает и возвращает новый экземпляр класса ImageInfo на основе экземпляра класса TwImageInfo. - /// - /// Описание изображения. - /// Экземпляр класса ImageInfo. - internal static ImageInfo FromTwImageInfo(TwImageInfo info) { - - return new ImageInfo { - BitsPerPixel=info.BitsPerPixel, - BitsPerSample=ImageInfo._Copy(info.BitsPerSample,info.SamplesPerPixel), - Compression=info.Compression, - ImageLength=info.ImageLength, - ImageWidth=info.ImageWidth, - PixelType=info.PixelType, - Planar=info.Planar, - XResolution=info.XResolution, - YResolution=info.YResolution - }; - } + public sealed class ImageInfo + { + + private ImageInfo() + { + } + + /// + /// Creates and returns a new instance of the ImageInfo class based on an instance of the TwImageInfo class. + /// Создает и возвращает новый экземпляр класса ImageInfo на основе экземпляра класса TwImageInfo. + /// + /// Description of the image.Описание изображения. + /// An instance of the ImageInfo class.Экземпляр класса ImageInfo. + internal static ImageInfo FromTwImageInfo(TwImageInfo info) => new ImageInfo + { + BitsPerPixel = info.BitsPerPixel, + BitsPerSample = ImageInfo._Copy(info.BitsPerSample, info.SamplesPerPixel), + Compression = info.Compression, + ImageLength = info.ImageLength, + ImageWidth = info.ImageWidth, + PixelType = info.PixelType, + Planar = info.Planar, + XResolution = info.XResolution, + YResolution = info.YResolution + }; - private static short[] _Copy(short[] array,int len) { + private static short[] _Copy(short[] array, int len) + { var _result = new short[len]; - for(var i = 0; i /// Resolution in the horizontal /// - public float XResolution { - get; - private set; - } + public float XResolution { get; private set; } /// /// Resolution in the vertical /// - public float YResolution { - get; - private set; - } + public float YResolution { get; private set; } /// /// Columns in the image, -1 if unknown by DS /// - public int ImageWidth { - get; - private set; - } + public int ImageWidth { get; private set; } /// /// Rows in the image, -1 if unknown by DS /// - public int ImageLength { - get; - private set; - } + public int ImageLength { get; private set; } /// /// Number of bits for each sample /// - public short[] BitsPerSample { - get; - private set; - } + public short[] BitsPerSample { get; private set; } /// /// Number of bits for each padded pixel /// - public short BitsPerPixel { - get; - private set; - } + public short BitsPerPixel { get; private set; } /// /// True if Planar, False if chunky /// - public bool Planar { - get; - private set; - } + public bool Planar { get; private set; } /// /// How to interp data; photo interp /// - public TwPixelType PixelType { - get; - private set; - } + public TwPixelType PixelType { get; private set; } /// /// How the data is compressed /// - public TwCompression Compression { - get; - private set; - } + public TwCompression Compression { get; private set; } } /// - /// Расширенное описание изображения. + /// Extended image description. + /// Расширенное описание изображения. /// [Serializable] - public sealed class ExtImageInfo:Collection { + public sealed class ExtImageInfo : Collection + { - private ExtImageInfo() { + private ExtImageInfo() + { } /// - /// Создает и возвращает экземпляр класса ExtImageInfo из блока неуправляемой памяти. + /// Creates and returns an instance of the ExtImageInfo class from an unmanaged memory block. + /// Создает и возвращает экземпляр класса ExtImageInfo из блока неуправляемой памяти. /// - /// Указатель на блок неуправляемой памяти. - /// Экземпляр класса ExtImageInfo. - internal static ExtImageInfo FromPtr(IntPtr ptr) { - int _twExtImageInfoSize=Marshal.SizeOf(typeof(TwExtImageInfo)); - int _twInfoSize=Marshal.SizeOf(typeof(TwInfo)); - TwExtImageInfo _extImageInfo=Marshal.PtrToStructure(ptr,typeof(TwExtImageInfo)) as TwExtImageInfo; - ExtImageInfo _result=new ExtImageInfo(); - for(int i=0; i<_extImageInfo.NumInfos; i++) { - using(TwInfo _item=Marshal.PtrToStructure((IntPtr)(ptr.ToInt64()+_twExtImageInfoSize+(_twInfoSize*i)),typeof(TwInfo)) as TwInfo) { + /// Pointer to an unmanaged memory block.Указатель на блок неуправляемой памяти. + /// An instance of the ExtImageInfo class.Экземпляр класса ExtImageInfo. + internal static ExtImageInfo FromPtr(IntPtr ptr) + { + int _twExtImageInfoSize = Marshal.SizeOf(typeof(TwExtImageInfo)); + int _twInfoSize = Marshal.SizeOf(typeof(TwInfo)); + TwExtImageInfo _extImageInfo = Marshal.PtrToStructure(ptr, typeof(TwExtImageInfo)) as TwExtImageInfo; + ExtImageInfo _result = new ExtImageInfo(); + for (int i = 0; i < _extImageInfo.NumInfos; i++) + { + using (TwInfo _item = Marshal.PtrToStructure((IntPtr)(ptr.ToInt64() + _twExtImageInfoSize + (_twInfoSize * i)), typeof(TwInfo)) as TwInfo) + { _result.Add(InfoItem.FromTwInfo(_item)); } } @@ -2799,15 +3130,20 @@ internal static ExtImageInfo FromPtr(IntPtr ptr) { } /// - /// Возвращает элемент описания расширенной информации о изображении по его коду. + /// Returns a description element of the extended image information by its code. + /// Возвращает элемент описания расширенной информации о изображении по его коду. /// - /// Код элемента описания расширенной информации о изображении. - /// Элемент описания расширенной информации о изображении. + /// Description element code for extended image information.Код элемента описания расширенной информации о изображении. + /// Description element for extended image information.Элемент описания расширенной информации о изображении. /// Для указанного кода отсутствует соответствующий элемент. - public InfoItem this[TwEI infoId] { - get { - foreach(InfoItem _item in this) { - if(_item.InfoId==infoId) { + public InfoItem this[TwEI infoId] + { + get + { + foreach (InfoItem _item in this) + { + if (_item.InfoId == infoId) + { return _item; } } @@ -2816,69 +3152,62 @@ public InfoItem this[TwEI infoId] { } /// - /// Элемент описания расширенной информации о изображении. + /// Description element for extended image information. + /// Элемент описания расширенной информации о изображении. /// [Serializable] [DebuggerDisplay("InfoId = {InfoId}, IsSuccess = {IsSuccess}, Value = {Value}")] - public sealed class InfoItem { + public sealed class InfoItem + { - private InfoItem() { + private InfoItem() + { } /// - /// Создает и возвращает экземпляр класса элемента описания расширенной информации о изображении из внутреннего экземпляра класса элемента описания расширенной информации о изображении. + /// Creates and returns an instance class of an extended image information description element from an internal instance of an extended image information description element class. + /// Создает и возвращает экземпляр класса элемента описания расширенной информации о изображении из внутреннего экземпляра класса элемента описания расширенной информации о изображении. /// - /// Внутрений экземпляр класса элемента описания расширенной информации о изображении. - /// Экземпляр класса элемента описания расширенной информации о изображении. - internal static InfoItem FromTwInfo(TwInfo info) { - return new InfoItem { - InfoId=info.InfoId, - IsNotSupported=info.ReturnCode==TwRC.InfoNotSupported, - IsNotAvailable=info.ReturnCode==TwRC.DataNotAvailable, - IsSuccess=info.ReturnCode==TwRC.Success, - Value=info.GetValue() - }; - } + /// An internal instance of the extended image information description element class.Внутрений экземпляр класса элемента описания расширенной информации о изображении. + /// An instance of the extended image information description item class.Экземпляр класса элемента описания расширенной информации о изображении. + internal static InfoItem FromTwInfo(TwInfo info) => new InfoItem + { + InfoId = info.InfoId, + IsNotSupported = info.ReturnCode == TwRC.InfoNotSupported, + IsNotAvailable = info.ReturnCode == TwRC.DataNotAvailable, + IsSuccess = info.ReturnCode == TwRC.Success, + Value = info.GetValue() + }; /// - /// Возвращает код расширенной информации о изображении. + /// Returns a code for extended image information. + /// Возвращает код расширенной информации о изображении. /// - public TwEI InfoId { - get; - private set; - } + public TwEI InfoId { get; private set; } /// - /// Возвращает true, если запрошенная информация не поддерживается источником данных; иначе, false. + /// Вreturns true if the requested information is not supported by the data source; otherwise false. + /// Возвращает true, если запрошенная информация не поддерживается источником данных; иначе, false. /// - public bool IsNotSupported { - get; - private set; - } + public bool IsNotSupported { get; private set; } /// - /// Возвращает true, если запрошенная информация поддерживается источником данных, но в данный момент недоступна; иначе, false. + /// Returns true if the requested information is supported by the data source but is currently unavailable; otherwise false. + /// Возвращает true, если запрошенная информация поддерживается источником данных, но в данный момент недоступна; иначе, false. /// - public bool IsNotAvailable { - get; - private set; - } + public bool IsNotAvailable { get; private set; } /// - /// Возвращает true, если запрошенная информация была успешно извлечена; иначе, false. + /// Returns true if the requested information was successfully retrieved; otherwise false. + /// Возвращает true, если запрошенная информация была успешно извлечена; иначе, false. /// - public bool IsSuccess { - get; - private set; - } + public bool IsSuccess { get; private set; } /// - /// Возвращает значение элемента. + /// Returns the value of an element. + /// Возвращает значение элемента. /// - public object Value { - get; - private set; - } + public object Value { get; private set; } } } @@ -2886,31 +3215,41 @@ public object Value { /// Used to pass image data (e.g. in strips) from DS to application. /// [Serializable] - public sealed class ImageMemXfer { + public sealed class ImageMemXfer + { - private ImageMemXfer() { + private ImageMemXfer() + { } - internal static ImageMemXfer Create(TwImageMemXfer data) { - ImageMemXfer _res=new ImageMemXfer() { - BytesPerRow=data.BytesPerRow, - Columns=data.Columns, - Compression=data.Compression, - Rows=data.Rows, - XOffset=data.XOffset, - YOffset=data.YOffset + internal static ImageMemXfer Create(TwImageMemXfer data) + { + ImageMemXfer _res = new ImageMemXfer() + { + BytesPerRow = data.BytesPerRow, + Columns = data.Columns, + Compression = data.Compression, + Rows = data.Rows, + XOffset = data.XOffset, + YOffset = data.YOffset }; - if((data.Memory.Flags&TwMF.Handle)!=0) { - IntPtr _data=Twain32._Memory.Lock(data.Memory.TheMem); - try { - _res.ImageData=new byte[data.BytesWritten]; - Marshal.Copy(_data,_res.ImageData,0,_res.ImageData.Length); - } finally { + if ((data.Memory.Flags & TwMF.Handle) != 0) + { + IntPtr _data = Twain32._Memory.Lock(data.Memory.TheMem); + try + { + _res.ImageData = new byte[data.BytesWritten]; + Marshal.Copy(_data, _res.ImageData, 0, _res.ImageData.Length); + } + finally + { Twain32._Memory.Unlock(data.Memory.TheMem); } - } else { - _res.ImageData=new byte[data.BytesWritten]; - Marshal.Copy(data.Memory.TheMem,_res.ImageData,0,_res.ImageData.Length); + } + else + { + _res.ImageData = new byte[data.BytesWritten]; + Marshal.Copy(data.Memory.TheMem, _res.ImageData, 0, _res.ImageData.Length); } return _res; } @@ -2918,207 +3257,206 @@ internal static ImageMemXfer Create(TwImageMemXfer data) { /// /// How the data is compressed. /// - public TwCompression Compression { - get; - private set; - } + public TwCompression Compression { get; private set; } /// /// Number of bytes in a row of data. /// - public uint BytesPerRow { - get; - private set; - } + public uint BytesPerRow { get; private set; } /// /// How many columns. /// - public uint Columns { - get; - private set; - } + public uint Columns { get; private set; } /// /// How many rows. /// - public uint Rows { - get; - private set; - } + public uint Rows { get; private set; } /// /// How far from the side of the image. /// - public uint XOffset { - get; - private set; - } + public uint XOffset { get; private set; } /// /// How far from the top of the image. /// - public uint YOffset { - get; - private set; - } + public uint YOffset { get; private set; } /// /// Data. /// - public byte[] ImageData { - get; - private set; - } + public byte[] ImageData { get; private set; } } /// - /// Описание файла изображения. + /// Description of the image file. + /// Описание файла изображения. /// [Serializable] - public sealed class ImageFileXfer { + public sealed class ImageFileXfer + { /// - /// Инициализирует новый экземпляр . + /// Initializes a new instance . + /// Инициализирует новый экземпляр . /// - private ImageFileXfer() { + private ImageFileXfer() + { } /// - /// Создает и возвращает новый экземпляр . + /// Creates and returns a new instance . + /// Создает и возвращает новый экземпляр . /// - /// Описание файла. - /// Экземпляр . - internal static ImageFileXfer Create(TwSetupFileXfer data) { - return new ImageFileXfer { - FileName=data.FileName, - Format=data.Format - }; - } + /// File description.Описание файла. + /// Instance .Экземпляр . + internal static ImageFileXfer Create(TwSetupFileXfer data) => new ImageFileXfer + { + FileName = data.FileName, + Format = data.Format + }; /// - /// Возвращает имя файла. + /// Returns the file name. + /// Возвращает имя файла. /// - public string FileName { - get; - private set; - } + public string FileName { get; private set; } /// - /// Фозвращает формат файла. + /// Returns the file format. + /// Фозвращает формат файла. /// - public TwFF Format { - get; - private set; - } + public TwFF Format { get; private set; } } /// - /// Набор операций для работы с цветовой палитрой. + /// A set of operations for working with a color palette. + /// Набор операций для работы с цветовой палитрой. /// - public sealed class TwainPalette:MarshalByRefObject { + public sealed class TwainPalette : MarshalByRefObject + { private Twain32 _twain; /// - /// Инициализирует новый экземпляр класса . + /// Initializes a new instance of the class . + /// Инициализирует новый экземпляр класса . /// - /// Экземпляр класса . - internal TwainPalette(Twain32 twain) { - this._twain=twain; + /// Class instance .Экземпляр класса . + internal TwainPalette(Twain32 twain) + { + this._twain = twain; } /// - /// Возвращает текущую цветовую палитру. + /// Returns the current color palette. + /// Возвращает текущую цветовую палитру. /// - /// Экземпляр класса . - public ColorPalette Get() { - TwPalette8 _palette=new TwPalette8(); - TwRC _rc=this._twain._dsmEntry.DsInvoke(this._twain._AppId,this._twain._srcds,TwDG.Image,TwDAT.Palette8,TwMSG.Get,ref _palette); - if(_rc!=TwRC.Success) { - throw new TwainException(this._twain._GetTwainStatus(),_rc); + /// Class instance .Экземпляр класса . + public ColorPalette Get() + { + TwPalette8 _palette = new TwPalette8(); + TwRC _rc = this._twain._dsmEntry.DsInvoke(this._twain._AppId, this._twain._srcds, TwDG.Image, TwDAT.Palette8, TwMSG.Get, ref _palette); + if (_rc != TwRC.Success) + { + throw new TwainException(this._twain._GetTwainStatus(), _rc); } return _palette; } /// - /// Возвращает текущую цветовую палитру, используемую по умолчанию. + /// Returns the current default color palette. + /// Возвращает текущую цветовую палитру, используемую по умолчанию. /// - /// Экземпляр класса . - public ColorPalette GetDefault() { - TwPalette8 _palette=new TwPalette8(); - TwRC _rc=this._twain._dsmEntry.DsInvoke(this._twain._AppId,this._twain._srcds,TwDG.Image,TwDAT.Palette8,TwMSG.GetDefault,ref _palette); - if(_rc!=TwRC.Success) { - throw new TwainException(this._twain._GetTwainStatus(),_rc); + /// Class instance .Экземпляр класса . + public ColorPalette GetDefault() + { + TwPalette8 _palette = new TwPalette8(); + TwRC _rc = this._twain._dsmEntry.DsInvoke(this._twain._AppId, this._twain._srcds, TwDG.Image, TwDAT.Palette8, TwMSG.GetDefault, ref _palette); + if (_rc != TwRC.Success) + { + throw new TwainException(this._twain._GetTwainStatus(), _rc); } return _palette; } /// - /// Сбрасывает текущую цветовую палитру и устанавливает указанную. + /// Resets the current color palette and sets the specified one. + /// Сбрасывает текущую цветовую палитру и устанавливает указанную. /// - /// Экземпляр класса . - public void Reset(ColorPalette palette) { - TwRC _rc=this._twain._dsmEntry.DsInvoke(this._twain._AppId,this._twain._srcds,TwDG.Image,TwDAT.Palette8,TwMSG.Reset,ref palette); - if(_rc!=TwRC.Success) { - throw new TwainException(this._twain._GetTwainStatus(),_rc); + /// Class instance .Экземпляр класса . + public void Reset(ColorPalette palette) + { + TwRC _rc = this._twain._dsmEntry.DsInvoke(this._twain._AppId, this._twain._srcds, TwDG.Image, TwDAT.Palette8, TwMSG.Reset, ref palette); + if (_rc != TwRC.Success) + { + throw new TwainException(this._twain._GetTwainStatus(), _rc); } } /// - /// Устанавливает указанную цветовую палитру. + /// Sets the specified color palette. + /// Устанавливает указанную цветовую палитру. /// - /// Экземпляр класса . - public void Set(ColorPalette palette) { - TwRC _rc=this._twain._dsmEntry.DsInvoke(this._twain._AppId,this._twain._srcds,TwDG.Image,TwDAT.Palette8,TwMSG.Set,ref palette); - if(_rc!=TwRC.Success) { - throw new TwainException(this._twain._GetTwainStatus(),_rc); + /// Class instance .Экземпляр класса . + public void Set(ColorPalette palette) + { + TwRC _rc = this._twain._dsmEntry.DsInvoke(this._twain._AppId, this._twain._srcds, TwDG.Image, TwDAT.Palette8, TwMSG.Set, ref palette); + if (_rc != TwRC.Success) + { + throw new TwainException(this._twain._GetTwainStatus(), _rc); } } } /// - /// Цветовая палитра. + /// Color palette. + /// Цветовая палитра. /// [Serializable] - public sealed class ColorPalette { + public sealed class ColorPalette + { /// - /// Инициализирует новый экземпляр . + /// Initializes a new instance . + /// Инициализирует новый экземпляр . /// - private ColorPalette() { + private ColorPalette() + { } /// - /// Создает и возвращает новый экземпляр . + /// Creates and returns a new instance . + /// Создает и возвращает новый экземпляр . /// - /// Цветовая палитра. - /// Экземпляр . - internal static ColorPalette Create(TwPalette8 palette) { - Twain32.ColorPalette _result=new Twain32.ColorPalette { - PaletteType=palette.PaletteType, - Colors=new Color[palette.NumColors] + /// Color palette.Цветовая палитра. + /// Instance .Экземпляр . + internal static ColorPalette Create(TwPalette8 palette) + { + Twain32.ColorPalette _result = new Twain32.ColorPalette + { + PaletteType = palette.PaletteType, + Colors = new Color[palette.NumColors] }; - for(int i=0; i - /// Возвращает тип палитры. + /// Returns the type of palette. + /// Возвращает тип палитры. /// - public TwPA PaletteType { - get; - private set; - } + public TwPA PaletteType { get; private set; } /// - /// Возвращает цвета, входящие в состав палитры. + /// Returns the colors that make up the palette. + /// Возвращает цвета, входящие в состав палитры. /// - public Color[] Colors { - get; - private set; - } + public Color[] Colors { get; private set; } } /// @@ -3126,18 +3464,20 @@ public Color[] Colors { /// [Serializable] [DebuggerDisplay("{Name}, Version = {Version}")] - public sealed class Identity { + public sealed class Identity + { /// /// Initializes a new instance of the class. /// /// The identity. - internal Identity(TwIdentity identity) { - this.Family=identity.ProductFamily; - this.Manufacturer=identity.Manufacturer; - this.Name=identity.ProductName; - this.ProtocolVersion=new Version(identity.ProtocolMajor,identity.ProtocolMinor); - this.Version=new Version(identity.Version.MajorNum,identity.Version.MinorNum); + internal Identity(TwIdentity identity) + { + this.Family = identity.ProductFamily; + this.Manufacturer = identity.Manufacturer; + this.Name = identity.ProductName; + this.ProtocolVersion = new Version(identity.ProtocolMajor, identity.ProtocolMinor); + this.Version = new Version(identity.Version.MajorNum, identity.Version.MinorNum); } /// @@ -3146,10 +3486,7 @@ internal Identity(TwIdentity identity) { /// /// The version. /// - public Version Version { - get; - private set; - } + public Version Version { get; private set; } /// /// Get the protocol version. @@ -3157,34 +3494,22 @@ public Version Version { /// /// The protocol version. /// - public Version ProtocolVersion { - get; - private set; - } + public Version ProtocolVersion { get; private set; } /// /// Get manufacturer name, e.g. "Hewlett-Packard". /// - public string Manufacturer { - get; - private set; - } + public string Manufacturer { get; private set; } /// /// Get product family name, e.g. "ScanJet". /// - public string Family { - get; - private set; - } + public string Family { get; private set; } /// /// Get product name, e.g. "ScanJet Plus". /// - public string Name { - get; - private set; - } + public string Name { get; private set; } } #endregion @@ -3193,17 +3518,17 @@ public string Name { #region DSM delegates DAT_ variants - private delegate TwRC _DSMparent([In,Out] TwIdentity origin,IntPtr zeroptr,TwDG dg,TwDAT dat,TwMSG msg,ref IntPtr refptr); + private delegate TwRC _DSMparent([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr); - private delegate TwRC _DSMraw([In,Out] TwIdentity origin,IntPtr zeroptr,TwDG dg,TwDAT dat,TwMSG msg,IntPtr rawData); + private delegate TwRC _DSMraw([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, IntPtr rawData); #endregion #region DS delegates DAT_ variants to DS - private delegate TwRC _DSixfer([In,Out] TwIdentity origin,[In,Out] TwIdentity dest,TwDG dg,TwDAT dat,TwMSG msg,ref IntPtr hbitmap); + private delegate TwRC _DSixfer([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap); - private delegate TwRC _DSraw([In,Out] TwIdentity origin,[In,Out] TwIdentity dest,TwDG dg,TwDAT dat,TwMSG msg,IntPtr arg); + private delegate TwRC _DSraw([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, IntPtr arg); #endregion @@ -3215,4 +3540,4 @@ public string Name { #endregion } -} +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/TwainCapabilities.cs b/TownSuite.TwainScanner/TwainCapabilities.cs index c180a54..4be0fab 100644 --- a/TownSuite.TwainScanner/TwainCapabilities.cs +++ b/TownSuite.TwainScanner/TwainCapabilities.cs @@ -39,27 +39,30 @@ namespace TownSuite.TwainScanner { /// - /// Набор возможностей (Capabilities). + /// A set of capabilities + /// Набор возможностей (Capabilities). /// [DebuggerDisplay("SupportedCaps = {SupportedCaps.Get().Count}")] - public sealed class TwainCapabilities:MarshalByRefObject { - private Dictionary _caps=new Dictionary(); - - internal TwainCapabilities(Twain32 twain) { - MethodInfo _сreateCapability=typeof(TwainCapabilities).GetMethod("CreateCapability",BindingFlags.Instance|BindingFlags.NonPublic); - foreach(PropertyInfo _prop in typeof(TwainCapabilities).GetProperties()) { - object[] _attrs=_prop.GetCustomAttributes(typeof(CapabilityAttribute),false); - if(_attrs.Length>0) { - CapabilityAttribute _attr=_attrs[0] as CapabilityAttribute; - this._caps.Add(_attr.Cap,_prop.PropertyType); - _prop.SetValue(this,_сreateCapability.MakeGenericMethod(_prop.PropertyType.GetGenericArguments()[0]).Invoke(this,new object[] { twain,_attr.Cap }),null); + public sealed class TwainCapabilities : MarshalByRefObject + { + private Dictionary _caps = new Dictionary(); + + internal TwainCapabilities(Twain32 twain) + { + MethodInfo _сreateCapability = typeof(TwainCapabilities).GetMethod("CreateCapability", BindingFlags.Instance | BindingFlags.NonPublic); + foreach (PropertyInfo _prop in typeof(TwainCapabilities).GetProperties()) + { + object[] _attrs = _prop.GetCustomAttributes(typeof(CapabilityAttribute), false); + if (_attrs.Length > 0) + { + CapabilityAttribute _attr = _attrs[0] as CapabilityAttribute; + this._caps.Add(_attr.Cap, _prop.PropertyType); + _prop.SetValue(this, _сreateCapability.MakeGenericMethod(_prop.PropertyType.GetGenericArguments()[0]).Invoke(this, new object[] { twain, _attr.Cap }), null); } } } - private Capability CreateCapability(Twain32 twain,TwCap cap) { - return Activator.CreateInstance(typeof(Capability),new object[] { twain,cap }) as Capability; - } + private Capability CreateCapability(Twain32 twain, TwCap cap) => Activator.CreateInstance(typeof(Capability), new object[] { twain, cap }) as Capability; #region Properties @@ -71,10 +74,7 @@ private Capability CreateCapability(Twain32 twain,TwCap cap) { /// (no events set). /// [Capability(TwCap.DeviceEvent)] - public ICapability2 DeviceEvent { - get; - private set; - } + public ICapability2 DeviceEvent { get; private set; } #endregion @@ -84,19 +84,13 @@ public ICapability2 DeviceEvent { /// CAP_ALARMS. Turns specific audible alarms on and off. /// [Capability(TwCap.Alarms)] - public ICapability2 Alarms { - get; - private set; - } + public ICapability2 Alarms { get; private set; } /// /// CAP_ALARMVOLUME. Controls the volume of a device’s audible alarm. /// [Capability(TwCap.AlarmVolume)] - public ICapability AlarmVolume { - get; - private set; - } + public ICapability AlarmVolume { get; private set; } #endregion @@ -107,28 +101,19 @@ public ICapability AlarmVolume { /// Document Feeder. /// [Capability(TwCap.AutomaticSenseMedium)] - public ICapability AutomaticSenseMedium { - get; - private set; - } + public ICapability AutomaticSenseMedium { get; private set; } /// /// ICAP_AUTODISCARDBLANKPAGES. Discards blank pages. /// [Capability(TwCap.AutoDiscardBlankPages)] - public ICapability AutoDiscardBlankPages { - get; - private set; - } + public ICapability AutoDiscardBlankPages { get; private set; } /// /// ICAP_AUTOMATICBORDERDETECTION. Turns automatic border detection on and off. /// [Capability(TwCap.AutomaticBorderDetection)] - public ICapability AutomaticBorderDetection { - get; - private set; - } + public ICapability AutomaticBorderDetection { get; private set; } /// /// ICAP_AUTOMATICCOLORENABLED. Detects the pixel type of the image and returns either a color @@ -136,59 +121,41 @@ public ICapability AutomaticBorderDetection { /// ICAP_AUTOMATICCOLORNONCOLORPIXELTYPE. /// [Capability(TwCap.AutomaticColorEnabled)] - public ICapability AutomaticColorEnabled { - get; - private set; - } + public ICapability AutomaticColorEnabled { get; private set; } /// /// ICAP_AUTOMATICCOLORNONCOLORPIXELTYPE. Specifies the non-color pixel type to use when automatic color /// is enabled. /// [Capability(TwCap.AutomaticColorNonColorPixelType)] - public ICapability AutomaticColorNonColorPixelType { - get; - private set; - } + public ICapability AutomaticColorNonColorPixelType { get; private set; } /// /// ICAP_AUTOMATICCROPUSESFRAME. Reduces the amount of data captured from the device, /// potentially improving the performance of the driver. /// [Capability(TwCap.AutomaticCropUsesFrame)] - public ICapability AutomaticCropUsesFrame { - get; - private set; - } + public ICapability AutomaticCropUsesFrame { get; private set; } /// /// ICAP_AUTOMATICDESKEW. Turns automatic skew correction on and off. /// [Capability(TwCap.AutomaticDeskew)] - public ICapability AutomaticDeskew { - get; - private set; - } + public ICapability AutomaticDeskew { get; private set; } /// /// ICAP_AUTOMATICLENGTHDETECTION. Controls the automatic detection of the length of a document, /// this is intended for use with an Automatic Document Feeder. /// [Capability(TwCap.AutomaticLengthDetection)] - public ICapability AutomaticLengthDetection { - get; - private set; - } + public ICapability AutomaticLengthDetection { get; private set; } /// /// ICAP_AUTOMATICROTATE. When TRUE, depends on source to automatically rotate the /// image. /// [Capability(TwCap.AutomaticRotate)] - public ICapability AutomaticRotate { - get; - private set; - } + public ICapability AutomaticRotate { get; private set; } /// /// ICAP_AUTOSIZE. Force the output image dimensions to match either the current @@ -196,38 +163,26 @@ public ICapability AutomaticRotate { /// values. /// [Capability(TwCap.AutoSize)] - public ICapability AutoSize { - get; - private set; - } + public ICapability AutoSize { get; private set; } /// /// ICAP_FLIPROTATION. Orients images that flip orientation every other image. /// [Capability(TwCap.FlipRotation)] - public ICapability FlipRotation { - get; - private set; - } + public ICapability FlipRotation { get; private set; } /// /// ICAP_IMAGEMERGE. Merges the front and rear image of a document in one of four /// orientations: front on the top. /// [Capability(TwCap.ImageMerge)] - public ICapability ImageMerge { - get; - private set; - } + public ICapability ImageMerge { get; private set; } /// /// ICAP_IMAGEMERGEHEIGHTTHRESHOLD. Specifies a Y-Offset in ICAP_UNITS units. /// [Capability(TwCap.ImageMergeHeightThreshold)] - public ICapability ImageMergeHeightThreshold { - get; - private set; - } + public ICapability ImageMergeHeightThreshold { get; private set; } #endregion @@ -237,29 +192,20 @@ public ICapability ImageMergeHeightThreshold { /// CAP_AUTOMATICCAPTURE. Specifies the number of images to automatically capture. /// [Capability(TwCap.AutomaticCapture)] - public ICapability AutomaticCapture { - get; - private set; - } + public ICapability AutomaticCapture { get; private set; } /// /// CAP_TIMEBEFOREFIRSTCAPTURE. Selects the number of seconds before the first picture taken. /// [Capability(TwCap.TimeBeforeFirstCapture)] - public ICapability TimeBeforeFirstCapture { - get; - private set; - } + public ICapability TimeBeforeFirstCapture { get; private set; } /// /// CAP_TIMEBETWEENCAPTURES. Selects the hundredths of a second to wait between pictures /// taken. /// [Capability(TwCap.TimeBetweenCaptures)] - public ICapability TimeBetweenCaptures { - get; - private set; - } + public ICapability TimeBetweenCaptures { get; private set; } #endregion @@ -269,58 +215,40 @@ public ICapability TimeBetweenCaptures { /// CAP_AUTOSCAN. Enables the source’s automatic document scanning process. /// [Capability(TwCap.AutoScan)] - public ICapability AutoScan { - get; - private set; - } + public ICapability AutoScan { get; private set; } /// /// CAP_CAMERAENABLED. Delivers images from the current camera. /// [Capability(TwCap.CameraEnabled)] - public ICapability CameraEnabled { - get; - private set; - } + public ICapability CameraEnabled { get; private set; } /// /// CAP_CAMERAORDER. Selects the order of output for Single Document Multiple Image /// mode. /// [Capability(TwCap.CameraOrder)] - public ICapability2 CameraOrder { - get; - private set; - } + public ICapability2 CameraOrder { get; private set; } /// /// CAP_CAMERASIDE. Sets the top and bottom values of cameras in a scanning device. /// [Capability(TwCap.CameraSide)] - public ICapability CameraSide { - get; - private set; - } + public ICapability CameraSide { get; private set; } /// /// CAP_CLEARBUFFERS. MSG_GET reports presence of data in scanner’s buffers; /// MSG_SET clears the buffers. /// [Capability(TwCap.ClearBuffers)] - public ICapability ClearBuffers { - get; - private set; - } + public ICapability ClearBuffers { get; private set; } /// /// CAP_MAXBATCHBUFFERS. Describes the number of pages that the scanner can buffer when /// CAP_AUTOSCAN is enabled. /// [Capability(TwCap.MaxBatchBuffers)] - public ICapability MaxBatchBuffers { - get; - private set; - } + public ICapability MaxBatchBuffers { get; private set; } #endregion @@ -330,69 +258,48 @@ public ICapability MaxBatchBuffers { /// ICAP_BARCODEDETECTIONENABLED. Turns bar code detection on and off. /// [Capability(TwCap.BarCodeDetectionEnabled)] - public ICapability BarCodeDetectionEnabled { - get; - private set; - } + public ICapability BarCodeDetectionEnabled { get; private set; } /// /// ICAP_SUPPORTEDBARCODETYPES. Provides a list of bar code types that can be detected by current /// data source. /// [Capability(TwCap.SupportedBarCodeTypes)] - public ICapability2 SupportedBarCodeTypes { - get; - private set; - } + public ICapability2 SupportedBarCodeTypes { get; private set; } /// /// ICAP_BARCODEMAXRETRIES. Restricts the number of times a search will be retried if no bar /// codes are found. /// [Capability(TwCap.BarCodeMaxRetries)] - public ICapability BarCodeMaxRetries { - get; - private set; - } + public ICapability BarCodeMaxRetries { get; private set; } /// /// ICAP_BARCODEMAXSEARCHPRIORITIES. Specifies the maximum number of supported search priorities. /// [Capability(TwCap.BarCodeMaxSearchPriorities)] - public ICapability BarCodeMaxSearchPriorities { - get; - private set; - } + public ICapability BarCodeMaxSearchPriorities { get; private set; } /// /// ICAP_BARCODESEARCHMODE. Restricts bar code searching to certain orientations, or /// prioritizes one orientation over another. /// [Capability(TwCap.BarCodeSearchMode)] - public ICapability BarCodeSearchMode { - get; - private set; - } + public ICapability BarCodeSearchMode { get; private set; } /// /// ICAP_BARCODESEARCHPRIORITIES A prioritized list of bar code types dictating the order in which /// they will be sought. /// [Capability(TwCap.BarCodeSearchPriorities)] - public ICapability2 BarCodeSearchPriorities { - get; - private set; - } + public ICapability2 BarCodeSearchPriorities { get; private set; } /// /// ICAP_BARCODETIMEOUT. Restricts the total time spent on searching for bar codes on a /// page. /// [Capability(TwCap.BarCodeTimeout)] - public ICapability BarCodeTimeout { - get; - private set; - } + public ICapability BarCodeTimeout { get; private set; } #endregion @@ -402,10 +309,7 @@ public ICapability BarCodeTimeout { /// CAP_SUPPORTEDCAPS. Inquire Source’s capabilities valid for MSG_GET. /// [Capability(TwCap.SupportedCaps)] - public ICapability2 SupportedCaps { - get; - private set; - } + public ICapability2 SupportedCaps { get; private set; } #endregion @@ -416,47 +320,32 @@ public ICapability2 SupportedCaps { /// grayscale images, resulting in output that that could be termed “raw”. /// [Capability(TwCap.ColorManagementEnabled)] - public ICapability ColorManagementEnabled { - get; - private set; - } + public ICapability ColorManagementEnabled { get; private set; } /// /// ICAP_FILTER. Color characteristics of the subtractive filter applied to the /// image data. /// [Capability(TwCap.Filter)] - public ICapability2 Filter { - get; - private set; - } + public ICapability2 Filter { get; private set; } /// /// ICAP_GAMMA. Gamma correction value for the image data. /// [Capability(TwCap.Gamma)] - public ICapability Gamma { - get; - private set; - } + public ICapability Gamma { get; private set; } /// /// ICAP_ICCPROFILE. Embeds or links ICC profiles into files. /// [Capability(TwCap.IccProfile)] - public ICapability IccProfile { - get; - private set; - } + public ICapability IccProfile { get; private set; } /// /// ICAP_PLANARCHUNKY. Color data format - Planar or Chunky. /// [Capability(TwCap.PlanarChunky)] - public ICapability PlanarChunky { - get; - private set; - } + public ICapability PlanarChunky { get; private set; } #endregion @@ -466,73 +355,49 @@ public ICapability PlanarChunky { /// ICAP_BITORDERCODES. CCITT Compression. /// [Capability(TwCap.BitOrderCodes)] - public ICapability BitOrderCodes { - get; - private set; - } + public ICapability BitOrderCodes { get; private set; } /// /// ICAP_CCITTKFACTOR. CCITT Compression. /// [Capability(TwCap.CcittKFactor)] - public ICapability CcittKFactor { - get; - private set; - } + public ICapability CcittKFactor { get; private set; } /// /// ICAP_COMPRESSION. Compression method for Buffered Memory Transfers. /// [Capability(TwCap.ICompression)] - public ICapability Compression { - get; - private set; - } + public ICapability Compression { get; private set; } /// /// ICAP_JPEGPIXELTYPE. JPEG Compression. /// [Capability(TwCap.JpegPixelType)] - public ICapability JpegPixelType { - get; - private set; - } + public ICapability JpegPixelType { get; private set; } /// /// ICAP_JPEGQUALITY. JPEG quality. /// [Capability(TwCap.JpegQuality)] - public ICapability JpegQuality { - get; - private set; - } + public ICapability JpegQuality { get; private set; } /// /// ICAP_JPEGSUBSAMPLING. JPEG subsampling. /// [Capability(TwCap.JpegSubSampling)] - public ICapability JpegSubSampling { - get; - private set; - } + public ICapability JpegSubSampling { get; private set; } /// /// ICAP_PIXELFLAVORCODES. CCITT Compression. /// [Capability(TwCap.PixelFlavor)] - public ICapability PixelFlavor { - get; - private set; - } + public ICapability PixelFlavor { get; private set; } /// /// ICAP_TIMEFILL. CCITT Compression. /// [Capability(TwCap.TimeFill)] - public ICapability TimeFill { - get; - private set; - } + public ICapability TimeFill { get; private set; } #endregion @@ -542,162 +407,111 @@ public ICapability TimeFill { /// CAP_DEVICEONLINE. Determines if hardware is on and ready. /// [Capability(TwCap.DeviceOnline)] - public ICapability DeviceOnline { - get; - private set; - } + public ICapability DeviceOnline { get; private set; } /// /// CAP_DEVICETIMEDATE. Date and time of a device’s clock. /// [Capability(TwCap.DeviceTimeDate)] // TW_STR32 - public ICapability DeviceTimeDate { - get; - private set; - } + public ICapability DeviceTimeDate { get; private set; } /// /// CAP_SERIALNUMBER. The serial number of the currently selected source device. /// [Capability(TwCap.SerialNumber)] // TW_STR255 - public ICapability SerialNumber { - get; - private set; - } + public ICapability SerialNumber { get; private set; } /// /// ICAP_MINIMUMHEIGHT Allows the source to define the minimum height (Y-axis) that /// the source can acquire. /// [Capability(TwCap.MinimumHeight)] - public ICapability MinimumHeight { - get; - private set; - } + public ICapability MinimumHeight { get; private set; } /// /// ICAP_MINIMUMWIDTH Allows the source to define the minimum width (X-axis) that /// the source can acquire. /// [Capability(TwCap.MinimumWidth)] - public ICapability MinimumWidth { - get; - private set; - } + public ICapability MinimumWidth { get; private set; } /// /// ICAP_EXPOSURETIME. Exposure time used to capture the image, in seconds. /// [Capability(TwCap.ExposureTime)] - public ICapability ExposureTime { - get; - private set; - } + public ICapability ExposureTime { get; private set; } /// /// ICAP_FLASHUSED2. For devices that support a flash, MSG_SET selects the flash to be /// used; MSG_GET reports the current setting. /// [Capability(TwCap.FlashUsed2)] - public ICapability FlashUsed2 { - get; - private set; - } + public ICapability FlashUsed2 { get; private set; } /// /// ICAP_IMAGEFILTER. For devices that support image filtering, selects the algorithm to /// be used. /// [Capability(TwCap.ImageFilter)] - public ICapability ImageFilter { - get; - private set; - } + public ICapability ImageFilter { get; private set; } /// /// ICAP_LAMPSTATE. Is the lamp on? /// [Capability(TwCap.LampState)] - public ICapability LampState { - get; - private set; - } + public ICapability LampState { get; private set; } /// /// ICAP_LIGHTPATH. Image was captured transmissively or reflectively. /// [Capability(TwCap.LightPath)] - public ICapability LightPath { - get; - private set; - } + public ICapability LightPath { get; private set; } /// /// ICAP_LIGHTSOURCE. Describes the color characteristic of the light source used to /// acquire the image. /// [Capability(TwCap.LightSource)] - public ICapability LightSource { - get; - private set; - } + public ICapability LightSource { get; private set; } /// /// ICAP_NOISEFILTER. For devices that support noise filtering, selects the algorithm to /// be used. /// [Capability(TwCap.NoiseFilter)] - public ICapability NoiseFilter { - get; - private set; - } + public ICapability NoiseFilter { get; private set; } /// /// ICAP_OVERSCAN. For devices that support overscanning, controls whether /// additional rows or columns are appended to the image. /// [Capability(TwCap.OverScan)] - public ICapability OverScan { - get; - private set; - } + public ICapability OverScan { get; private set; } /// /// ICAP_PHYSICALHEIGHT. Maximum height Source can acquire (in ICAP_UNITS). /// [Capability(TwCap.PhysicalHeight)] - public ICapability PhysicalHeight { - get; - private set; - } + public ICapability PhysicalHeight { get; private set; } /// /// ICAP_PHYSICALWIDTH. Maximum width Source can acquire (in ICAP_UNITS). /// - [Capability( TwCap.PhysicalWidth)] - public ICapability PhysicalWidth { - get; - private set; - } + [Capability(TwCap.PhysicalWidth)] + public ICapability PhysicalWidth { get; private set; } /// /// ICAP_UNITS. Unit of measure (inches, centimeters, etc.). /// [Capability(TwCap.IUnits)] - public ICapability Units { - get; - private set; - } + public ICapability Units { get; private set; } /// /// ICAP_ZOOMFACTOR. With MSG_GET, returns all camera supported lens zooming /// range. /// [Capability(TwCap.ZoomFactor)] - public ICapability ZoomFactor { - get; - private set; - } + public ICapability ZoomFactor { get; private set; } #endregion @@ -707,37 +521,25 @@ public ICapability ZoomFactor { /// CAP_DOUBLEFEEDDETECTION. Control DFD functionality. /// [Capability(TwCap.DoubleFeedDetection)] - public ICapability2 DoubleFeedDetection { - get; - private set; - } + public ICapability2 DoubleFeedDetection { get; private set; } /// /// CAP_DOUBLEFEEDDETECTIONLENGTH. Set the minimum length. /// [Capability(TwCap.DoubleFeedDetectionLength)] - public ICapability DoubleFeedDetectionLength { - get; - private set; - } + public ICapability DoubleFeedDetectionLength { get; private set; } /// /// CAP_DOUBLEFEEDDETECTIONSENSITIVITY. Set detector sensitivity. /// [Capability(TwCap.DoubleFeedDetectionSensitivity)] - public ICapability DoubleFeedDetectionSensitivity { - get; - private set; - } + public ICapability DoubleFeedDetectionSensitivity { get; private set; } /// /// CAP_DOUBLEFEEDDETECTIONRESPONSE. Describe Source behavior in case of DFD. /// [Capability(TwCap.DoubleFeedDetectionResponse)] - public ICapability2 DoubleFeedDetectionResponse { - get; - private set; - } + public ICapability2 DoubleFeedDetectionResponse { get; private set; } #endregion @@ -747,75 +549,51 @@ public ICapability2 DoubleFeedDetectionResponse { /// CAP_ENDORSER. Allows the application to specify the starting endorser / imprinter number. /// [Capability(TwCap.Endorser)] - public ICapability Endorser { - get; - private set; - } + public ICapability Endorser { get; private set; } /// /// CAP_PRINTER. MSG_GET returns current list of available printer devices; /// MSG_SET selects the device for negotiation. /// [Capability(TwCap.Printer)] - public ICapability Printer { - get; - private set; - } + public ICapability Printer { get; private set; } /// /// CAP_PRINTERENABLED. Turns the current CAP_PRINTER device on or off. /// [Capability(TwCap.PrinterEnabled)] - public ICapability PrinterEnabled { - get; - private set; - } + public ICapability PrinterEnabled { get; private set; } /// /// CAP_PRINTERINDEX. Starting number for the CAP_PRINTER device. /// [Capability(TwCap.PrinterIndex)] - public ICapability PrinterIndex { - get; - private set; - } + public ICapability PrinterIndex { get; private set; } /// /// CAP_PRINTERMODE. Specifies appropriate current CAP_PRINTER device mode. /// [Capability(TwCap.PrinterMode)] - public ICapability PrinterMode { - get; - private set; - } + public ICapability PrinterMode { get; private set; } /// /// CAP_PRINTERSTRING. String(s) to be used in the string component when /// CAP_PRINTER device is enabled. /// [Capability(TwCap.PrinterString)] // TW_STR255 - public ICapability PrinterString { - get; - private set; - } + public ICapability PrinterString { get; private set; } /// /// CAP_PRINTERSUFFIX. String to be used as current CAP_PRINTER device’s suffix. /// [Capability(TwCap.PrinterSuffix)] // TW_STR255 - public ICapability PrinterSuffix { - get; - private set; - } + public ICapability PrinterSuffix { get; private set; } /// /// CAP_PRINTERVERTICALOFFSET. Y-Offset for current CAP_PRINTER device. /// [Capability(TwCap.PrinterVerticalOffset)] - public ICapability PrinterVerticalOffset { - get; - private set; - } + public ICapability PrinterVerticalOffset { get; private set; } #endregion @@ -825,48 +603,33 @@ public ICapability PrinterVerticalOffset { /// CAP_AUTHOR. Author of acquired image (may include a copyright string). /// [Capability(TwCap.Author)] // TW_STR128 - public ICapability Author { - get; - private set; - } + public ICapability Author { get; private set; } /// /// CAP_CAPTION. General note about acquired image. /// [Capability(TwCap.Caption)] // TW_STR255 - public ICapability Caption { - get; - private set; - } + public ICapability Caption { get; private set; } /// /// CAP_TIMEDATE Date and Time the image was acquired (entered State 7). /// [Capability(TwCap.TimeDate)] // TW_STR32 - public ICapability TimeDate { - get; - private set; - } + public ICapability TimeDate { get; private set; } /// /// ICAP_EXTIMAGEINFO. Allows the application to query the data source to see if it /// supports the new operation triplet DG_IMAGE / DAT_EXTIMAGEINFO/ MSG_GET. /// [Capability(TwCap.ExtImageInfo)] - public ICapability ExtImageInfo { - get; - private set; - } + public ICapability ExtImageInfo { get; private set; } /// /// ICAP_SUPPORTEDEXTIMAGEINFO. Lists all of the information that the Source is capable of /// returning from a call to DAT_EXTIMAGEINFO. /// [Capability(TwCap.SupportedExtImageInfo)] - public ICapability2 SupportedExtImageInfo { - get; - private set; - } + public ICapability2 SupportedExtImageInfo { get; private set; } #endregion @@ -877,113 +640,77 @@ public ICapability2 SupportedExtImageInfo { /// representations for the set of images that are to be delivered. /// [Capability(TwCap.ThumbnailsEnabled)] - public ICapability ThumbnailsEnabled { - get; - private set; - } + public ICapability ThumbnailsEnabled { get; private set; } /// /// ICAP_AUTOBRIGHT. Enable Source’s Auto-brightness function. /// [Capability(TwCap.AutoBright)] - public ICapability AutoBright { - get; - private set; - } + public ICapability AutoBright { get; private set; } /// /// ICAP_BRIGHTNESS. Source brightness values. /// [Capability(TwCap.Brightness)] - public ICapability Brightness { - get; - private set; - } + public ICapability Brightness { get; private set; } /// /// ICAP_CONTRAST. Source contrast values. /// [Capability(TwCap.Contrast)] - public ICapability Contrast { - get; - private set; - } + public ICapability Contrast { get; private set; } /// /// ICAP_HIGHLIGHT. Lightest highlight, values lighter than this value will be set to /// this value. /// [Capability(TwCap.Highlight)] - public ICapability Highlight { - get; - private set; - } + public ICapability Highlight { get; private set; } /// /// ICAP_IMAGEDATASET. Gets or sets the image indices that will be delivered during the /// standard image transfer done in States 6 and 7. /// [Capability(TwCap.ImageDataSet)] - public ICapability2 ImageDataSet { - get; - private set; - } + public ICapability2 ImageDataSet { get; private set; } /// /// ICAP_MIRROR. Source can, or should, mirror image. /// [Capability(TwCap.Mirror)] - public ICapability Mirror { - get; - private set; - } + public ICapability Mirror { get; private set; } /// /// ICAP_ORIENTATION Defines which edge of the paper is the top: Portrait or /// Landscape. /// [Capability(TwCap.Orientation)] - public ICapability Orientation { - get; - private set; - } + public ICapability Orientation { get; private set; } /// /// ICAP_ROTATION. Source can, or should, rotate image this number of degrees. /// [Capability(TwCap.Rotation)] - public ICapability Rotation { - get; - private set; - } + public ICapability Rotation { get; private set; } /// /// ICAP_SHADOW. Darkest shadow, values darker than this value will be set to this /// value. /// [Capability(TwCap.Shadow)] - public ICapability Shadow { - get; - private set; - } + public ICapability Shadow { get; private set; } /// /// ICAP_XSCALING. Source Scaling value (1.0 = 100%) for x-axis. /// [Capability(TwCap.XScaling)] - public ICapability XScaling { - get; - private set; - } + public ICapability XScaling { get; private set; } /// /// ICAP_YSCALING. Source Scaling value (1.0 = 100%) for y-axis. /// [Capability(TwCap.YScaling)] - public ICapability YScaling { - get; - private set; - } + public ICapability YScaling { get; private set; } #endregion @@ -993,64 +720,43 @@ public ICapability YScaling { /// ICAP_BITDEPTH. Pixel bit depth for Current value of ICAP_PIXELTYPE. /// [Capability(TwCap.BitDepth)] - public ICapability BitDepth { - get; - private set; - } + public ICapability BitDepth { get; private set; } /// /// ICAP_BITDEPTHREDUCTION. Allows a choice of the reduction method for bit depth loss. /// [Capability(TwCap.BitDepthReduction)] - public ICapability BitDepthReduction { - get; - private set; - } + public ICapability BitDepthReduction { get; private set; } /// /// ICAP_BITORDER. Specifies how the bytes in an image are filled by the Source. /// [Capability(TwCap.BitOrder)] - public ICapability BitOrder { - get; - private set; - } + public ICapability BitOrder { get; private set; } /// /// ICAP_CUSTHALFTONE. Square-cell halftone (dithering) matrix to be used. /// [Capability(TwCap.CustHalftone)] - public ICapability2 CustHalftone { - get; - private set; - } + public ICapability2 CustHalftone { get; private set; } /// /// ICAP_HALFTONES. Source halftone patterns. /// [Capability(TwCap.Halftones)] // TW_STR32 - public ICapability Halftones { - get; - private set; - } + public ICapability Halftones { get; private set; } /// /// ICAP_PIXELTYPE. The type of pixel data (B/W, gray, color, etc.) /// [Capability(TwCap.IPixelType)] - public ICapability PixelType { - get; - private set; - } + public ICapability PixelType { get; private set; } /// /// ICAP_THRESHOLD. Specifies the dividing line between black and white values. /// [Capability(TwCap.Threshold)] - public ICapability Threshold { - get; - private set; - } + public ICapability Threshold { get; private set; } #endregion @@ -1061,10 +767,7 @@ public ICapability Threshold { /// have in common. /// [Capability(TwCap.Language)] - public ICapability Language { - get; - private set; - } + public ICapability Language { get; private set; } #endregion @@ -1074,10 +777,7 @@ public ICapability Language { /// CAP_MICRENABLED. Enables actions needed to support check scanning. /// [Capability(TwCap.MicrEnabled)] - public ICapability MicrEnabled { - get; - private set; - } + public ICapability MicrEnabled { get; private set; } #endregion @@ -1087,37 +787,25 @@ public ICapability MicrEnabled { /// CAP_SEGMENTED. Describes the segmentation setting for captured images. /// [Capability(TwCap.Segmented)] - public ICapability Segmented { - get; - private set; - } + public ICapability Segmented { get; private set; } /// /// ICAP_FRAMES. Size and location of frames on page. /// [Capability(TwCap.Frames)] - public ICapability Frames { - get; - private set; - } + public ICapability Frames { get; private set; } /// /// ICAP_MAXFRAMES. Maximum number of frames possible per page. /// [Capability(TwCap.MaxFrames)] - public ICapability MaxFrames { - get; - private set; - } + public ICapability MaxFrames { get; private set; } /// /// ICAP_SUPPORTEDSIZES. Fixed frame sizes for typical page sizes. /// [Capability(TwCap.SupportedSizes)] - public ICapability SupportedSizes { - get; - private set; - } + public ICapability SupportedSizes { get; private set; } #endregion @@ -1127,147 +815,99 @@ public ICapability SupportedSizes { /// CAP_AUTOFEED. MSG_SET to TRUE to enable Source’s automatic feeding. /// [Capability(TwCap.AutoFeed)] - public ICapability AutoFeed { - get; - private set; - } + public ICapability AutoFeed { get; private set; } /// /// CAP_CLEARPAGE. MSG_SET to TRUE to eject current page and leave acquire area empty. /// [Capability(TwCap.ClearPage)] - public ICapability ClearPage { - get; - private set; - } + public ICapability ClearPage { get; private set; } /// /// CAP_DUPLEX. Indicates whether the scanner supports duplex. /// [Capability(TwCap.Duplex)] - public ICapability Duplex { - get; - private set; - } + public ICapability Duplex { get; private set; } /// /// CAP_DUPLEXENABLED. Enables the user to set the duplex option to be TRUE or FALSE. /// [Capability(TwCap.DuplexEnabled)] - public ICapability DuplexEnabled { - get; - private set; - } + public ICapability DuplexEnabled { get; private set; } /// /// CAP_FEEDERALIGNMENT. Indicates the alignment of the document feeder. /// [Capability(TwCap.FeederAlignment)] - public ICapability FeederAlignment { - get; - private set; - } + public ICapability FeederAlignment { get; private set; } /// /// CAP_FEEDERENABLED. If TRUE, Source’s feeder is available. /// [Capability(TwCap.FeederEnabled)] - public ICapability FeederEnabled { - get; - private set; - } + public ICapability FeederEnabled { get; private set; } /// /// CAP_FEEDERLOADED. If TRUE, Source has documents loaded in feeder (MSG_GET only). /// [Capability(TwCap.FeederLoaded)] - public ICapability FeederLoaded { - get; - private set; - } + public ICapability FeederLoaded { get; private set; } /// /// CAP_FEEDERORDER. Specifies whether feeder starts with top of first or last page. /// [Capability(TwCap.FeederOrder)] - public ICapability FeederOrder { - get; - private set; - } + public ICapability FeederOrder { get; private set; } /// /// CAP_FEEDERPOCKET. Report what pockets are available as paper leaves a device. /// [Capability(TwCap.FeederPocket)] - public ICapability2 FeederPocket { - get; - private set; - } + public ICapability2 FeederPocket { get; private set; } /// /// CAP_FEEDERPREP. Improve the movement of paper through a scanner ADF. /// [Capability(TwCap.FeederPrep)] - public ICapability FeederPrep { - get; - private set; - } + public ICapability FeederPrep { get; private set; } /// /// CAP_FEEDPAGE. MSG_SET to TRUE to eject current page and feed next page. /// [Capability(TwCap.FeedPage)] - public ICapability FeedPage { - get; - private set; - } + public ICapability FeedPage { get; private set; } /// /// CAP_PAPERDETECTABLE. Determines whether source can detect documents on the ADF. /// [Capability(TwCap.PaperDetectable)] - public ICapability PaperDetectable { - get; - private set; - } + public ICapability PaperDetectable { get; private set; } /// /// CAP_PAPERHANDLING. Control paper handling. /// [Capability(TwCap.PaperHandling)] - public ICapability2 PaperHandling { - get; - private set; - } + public ICapability2 PaperHandling { get; private set; } /// /// CAP_REACQUIREALLOWED. Capable of acquring muliple images of the same page wihtout /// changing the physical registraion of that page. /// [Capability(TwCap.ReacquireAllowed)] - public ICapability ReacquireAllowed { - get; - private set; - } + public ICapability ReacquireAllowed { get; private set; } /// /// CAP_REWINDPAGE. MSG_SET to TRUE to do a reverse feed. /// [Capability(TwCap.RewindPage)] - public ICapability RewindPage { - get; - private set; - } + public ICapability RewindPage { get; private set; } /// /// ICAP_FEEDERTYPE. Allows application to set scan parameters depending on the /// type of feeder being used. /// [Capability(TwCap.FeederType)] - public ICapability FeederType { - get; - private set; - } + public ICapability FeederType { get; private set; } #endregion @@ -1277,68 +917,47 @@ public ICapability FeederType { /// ICAP_PATCHCODEDETECTIONENABLED. Turns patch code detection on and off. /// [Capability(TwCap.PatchCodeDetectionEnabled)] - public ICapability PatchCodeDetectionEnabled { - get; - private set; - } + public ICapability PatchCodeDetectionEnabled { get; private set; } /// /// ICAP_SUPPORTEDPATCHCODETYPES. List of patch code types that can be detected by current data /// source. /// [Capability(TwCap.SupportedPatchCodeTypes)] - public ICapability2 SupportedPatchCodeTypes { - get; - private set; - } + public ICapability2 SupportedPatchCodeTypes { get; private set; } /// /// ICAP_PATCHCODEMAXSEARCHPRIORITIES. Maximum number of search priorities. /// [Capability(TwCap.PatchCodeMaxSearchPriorities)] - public ICapability PatchCodeMaxSearchPriorities { - get; - private set; - } + public ICapability PatchCodeMaxSearchPriorities { get; private set; } /// /// ICAP_PATCHCODESEARCHPRIORITIES. List of patch code types dictating the order in which patch /// codes will be sought. /// [Capability(TwCap.PatchCodeSearchPriorities)] - public ICapability2 PatchCodeSearchPriorities { - get; - private set; - } + public ICapability2 PatchCodeSearchPriorities { get; private set; } /// /// ICAP_PATCHCODESEARCHMODE. Restricts patch code searching to certain orientations, or /// prioritizes one orientation over another. /// [Capability(TwCap.PatchCodeSearchMode)] - public ICapability PatchCodeSearchMode { - get; - private set; - } + public ICapability PatchCodeSearchMode { get; private set; } /// /// ICAP_PATCHCODEMAXRETRIES. Restricts the number of times a search will be retried if none are /// found on a page. /// [Capability(TwCap.PatchCodeMaxRetries)] - public ICapability PatchCodeMaxRetries { - get; - private set; - } + public ICapability PatchCodeMaxRetries { get; private set; } /// /// ICAP_PATCHCODETIMEOUT. Restricts total time for searching for a patch code on a page. /// [Capability(TwCap.PatchCodeTimeout)] - public ICapability PatchCodeTimeout { - get; - private set; - } + public ICapability PatchCodeTimeout { get; private set; } #endregion @@ -1348,39 +967,27 @@ public ICapability PatchCodeTimeout { /// CAP_BATTERYMINUTES. The minutes of battery power remaining on a device. /// [Capability(TwCap.BatteryMinutes)] - public ICapability BatteryMinutes { - get; - private set; - } + public ICapability BatteryMinutes { get; private set; } /// /// CAP_BATTERYPERCENTAGE. With MSG_GET, indicates battery power status. /// [Capability(TwCap.BatteryPercentage)] - public ICapability BatteryPercentage { - get; - private set; - } + public ICapability BatteryPercentage { get; private set; } /// /// CAP_POWERSAVETIME. With MSG_SET, sets the camera power down timer in seconds; /// with MSG_GET, returns the current setting of the power down time. /// [Capability(TwCap.PowerSaveTime)] - public ICapability PowerSaveTime { - get; - private set; - } + public ICapability PowerSaveTime { get; private set; } /// /// CAP_POWERSUPPLY. MSG_GET reports the kinds of power available; /// MSG_GETCURRENT reports the current power supply to use. /// [Capability(TwCap.PowerSupply)] - public ICapability PowerSupply { - get; - private set; - } + public ICapability PowerSupply { get; private set; } #endregion @@ -1390,37 +997,25 @@ public ICapability PowerSupply { /// ICAP_XNATIVERESOLUTION. Native optical resolution of device for x-axis. /// [Capability(TwCap.XNativeResolution)] - public ICapability XNativeResolution { - get; - private set; - } + public ICapability XNativeResolution { get; private set; } /// /// ICAP_XRESOLUTION. Current/Available optical resolutions for x-axis. /// [Capability(TwCap.XResolution)] - public ICapability XResolution { - get; - private set; - } + public ICapability XResolution { get; private set; } /// /// ICAP_YNATIVERESOLUTION. Native optical resolution of device for y-axis. /// [Capability(TwCap.YNativeResolution)] - public ICapability YNativeResolution { - get; - private set; - } + public ICapability YNativeResolution { get; private set; } /// /// ICAP_YRESOLUTION. Current/Available optical resolutions for y-axis. /// [Capability(TwCap.YResolution)] - public ICapability YResolution { - get; - private set; - } + public ICapability YResolution { get; private set; } #endregion @@ -1430,56 +1025,44 @@ public ICapability YResolution { /// CAP_JOBCONTROL. Allows multiple jobs in batch mode. /// [Capability(TwCap.JobControl)] - public ICapability JobControl { - get; - private set; - } + public ICapability JobControl { get; private set; } + + /// + /// CAP_SHEETCOUNT. Capture the specified number of sheets of paper. + /// + [Capability(TwCap.SheetCount)] + public ICapability SheetCount { get; private set; } /// /// CAP_XFERCOUNT. Number of images the application is willing to accept this session. /// [Capability(TwCap.XferCount)] - public ICapability XferCount { - get; - private set; - } + public ICapability XferCount { get; private set; } /// /// ICAP_IMAGEFILEFORMAT. File formats for file transfers. /// [Capability(TwCap.ImageFileFormat)] - public ICapability ImageFileFormat { - get; - private set; - } + public ICapability ImageFileFormat { get; private set; } /// /// ICAP_TILES. Tiled image data. /// [Capability(TwCap.Tiles)] - public ICapability Tiles { - get; - private set; - } + public ICapability Tiles { get; private set; } /// /// ICAP_UNDEFINEDIMAGESIZE. The application will accept undefined image size. /// [Capability(TwCap.UndefinedImageSize)] - public ICapability UndefinedImageSize { - get; - private set; - } + public ICapability UndefinedImageSize { get; private set; } /// /// ICAP_XFERMECH. Transfer mechanism - used to learn options and set-up for /// upcoming transfer. /// [Capability(TwCap.IXferMech)] - public ICapability XferMech { - get; - private set; - } + public ICapability XferMech { get; private set; } #endregion @@ -1489,10 +1072,7 @@ public ICapability XferMech { /// CAP_CAMERAPREVIEWUI. Queries the source for UI support for preview mode. /// [Capability(TwCap.CameraPreviewUI)] - public ICapability CameraPreviewUI { - get; - private set; - } + public ICapability CameraPreviewUI { get; private set; } /// /// CAP_CUSTOMDSDATA. Allows the application to query the data source to see if it @@ -1500,346 +1080,349 @@ public ICapability CameraPreviewUI { /// DG_CONTROL / DAT_CUSTOMDSDATA / MSG_SET. /// [Capability(TwCap.CustomDSData)] - public ICapability CustomDSData { - get; - private set; - } + public ICapability CustomDSData { get; private set; } /// /// CAP_CUSTOMINTERFACEGUID. Uniquely identifies an interface for a Data Source. /// [Capability(TwCap.CustomInterfaceGuid)] - public ICapability CustomInterfaceGuid { - get; - private set; - } + public ICapability CustomInterfaceGuid { get; private set; } /// /// CAP_ENABLEDSUIONLY. Queries an application to see if it implements the new user /// interface settings dialog. /// [Capability(TwCap.EnableDSUIOnly)] - public ICapability EnableDSUIOnly { - get; - private set; - } + public ICapability EnableDSUIOnly { get; private set; } /// /// CAP_INDICATORS. Use the Source’s progress indicator? (valid only when /// ShowUI==FALSE). /// [Capability(TwCap.Indicators)] - public ICapability Indicators { - get; - private set; - } + public ICapability Indicators { get; private set; } /// /// CAP_INDICATORSMODE. List of messages types that can be display if /// ICAP_INDICATORS is TRUE. /// [Capability(TwCap.IndicatorsMode)] - public ICapability2 IndicatorsMode { - get; - private set; - } + public ICapability2 IndicatorsMode { get; private set; } /// /// CAP_UICONTROLLABLE. Indicates that Source supports acquisitions with UI disabled. /// [Capability(TwCap.UIControllable)] - public ICapability UIControllable { - get; - private set; - } + public ICapability UIControllable { get; private set; } #endregion #endregion [DebuggerDisplay("{ToString()}")] - private class Capability:ICapability,ICapability2 { + private class Capability : ICapability, ICapability2 + { - public Capability(Twain32 twain,TwCap cap) { - this._Twain32=twain; - this._Cap=cap; + public Capability(Twain32 twain, TwCap cap) + { + this._Twain32 = twain; + this._Cap = cap; } - public Twain32.Enumeration Get() { - return this.ToEnumeration(this._Twain32.GetCap(this._Cap)); - } + public Twain32.Enumeration Get() => this.ToEnumeration(this._Twain32.GetCap(this._Cap)); - public T GetCurrent() { - return (T)this._Twain32.GetCurrentCap(this._Cap); - } + public T GetCurrent() => (T)this._Twain32.GetCurrentCap(this._Cap); - public object[] GetCurrentArray() { - return this.ToEnumeration(this._Twain32.GetCurrentCap(this._Cap)).Items; - } + public object[] GetCurrentArray() => this.ToEnumeration(this._Twain32.GetCurrentCap(this._Cap)).Items; - public T GetDefault() { - return (T)this._Twain32.GetDefaultCap(this._Cap); - } + public T GetDefault() => (T)this._Twain32.GetDefaultCap(this._Cap); - public object[] GetDefaultArray() { - return this.ToEnumeration(this._Twain32.GetDefaultCap(this._Cap)).Items; - } + public object[] GetDefaultArray() => this.ToEnumeration(this._Twain32.GetDefaultCap(this._Cap)).Items; - public void Set(T value) { - if(this._Twain32.Capabilities._caps[this._Cap]==typeof(ICapability2)||!this.GetCurrent().Equals(value)) { - this._Twain32.SetCap(this._Cap,value); + public void Set(T value) + { + if (this._Twain32.Capabilities._caps[this._Cap] == typeof(ICapability2) || !this.GetCurrent().Equals(value)) + { + this._Twain32.SetCap(this._Cap, value); } } - public void Set(params T[] value) { - var _val=new object[value.Length]; - for(var i=0; i<_val.Length; i++) { - _val[i]=value[i]; + public void Set(params T[] value) + { + var _val = new object[value.Length]; + for (var i = 0; i < _val.Length; i++) + { + _val[i] = value[i]; } - this._Twain32.SetCap(this._Cap,_val); + this._Twain32.SetCap(this._Cap, _val); } /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. - public void SetConstraint(T value) { - this._Twain32.SetConstraintCap(this._Cap,value); - } + /// The value to set.Устанавливаемое значение. + public void SetConstraint(T value) => this._Twain32.SetConstraintCap(this._Cap, value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. - public void SetConstraint(params T[] value) { + /// The value to set.Устанавливаемое значение. + public void SetConstraint(params T[] value) + { var _val = new object[value.Length]; - for(var i = 0; i<_val.Length; i++) { - _val[i]=value[i]; + for (var i = 0; i < _val.Length; i++) + { + _val[i] = value[i]; } - this._Twain32.SetConstraintCap(this._Cap,_val); + this._Twain32.SetConstraintCap(this._Cap, _val); } /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. - public void SetConstraint(Twain32.Range value) { - if(value.CurrentValue.GetType()!=typeof(T)) { + /// The value to set.Устанавливаемое значение. + public void SetConstraint(Twain32.Range value) + { + if (value.CurrentValue.GetType() != typeof(T)) + { throw new ArgumentException(); } - this._Twain32.SetConstraintCap(this._Cap,value); + this._Twain32.SetConstraintCap(this._Cap, value); } /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. - public void SetConstraint(Twain32.Enumeration value) { - if(value.Items==null||value.Items.Length==0||value.Items[0].GetType()!=typeof(T)) { + /// The value to set.Устанавливаемое значение. + public void SetConstraint(Twain32.Enumeration value) + { + if (value.Items == null || value.Items.Length == 0 || value.Items[0].GetType() != typeof(T)) + { throw new ArgumentException(); } - this._Twain32.SetConstraintCap(this._Cap,value); + this._Twain32.SetConstraintCap(this._Cap, value); } - public void Reset() { - this._Twain32.ResetCap(this._Cap); - } + public void Reset() => this._Twain32.ResetCap(this._Cap); - public TwQC IsSupported() { - return this._Twain32.IsCapSupported(this._Cap); - } + public TwQC IsSupported() => this._Twain32.IsCapSupported(this._Cap); - public bool IsSupported(TwQC operation) { - return (this.IsSupported()&operation)==operation; - } + public bool IsSupported(TwQC operation) => (this.IsSupported() & operation) == operation; - protected Twain32 _Twain32 { - get; - private set; - } + protected Twain32 _Twain32 { get; private set; } - protected TwCap _Cap { - get; - private set; - } + protected TwCap _Cap { get; private set; } - private Twain32.Enumeration ToEnumeration(object value) { - Twain32.Enumeration _val=Twain32.Enumeration.FromObject(value); - for(int i=0; i<_val.Count; i++) { - _val[i]=typeof(T).IsEnum?(T)_val[i]:Convert.ChangeType(_val[i],typeof(T)); + private Twain32.Enumeration ToEnumeration(object value) + { + Twain32.Enumeration _val = Twain32.Enumeration.FromObject(value); + for (int i = 0; i < _val.Count; i++) + { + _val[i] = typeof(T).IsEnum ? (T)_val[i] : Convert.ChangeType(_val[i], typeof(T)); } return _val; } - public override string ToString() { - var _supported=this.IsSupported(); - return string.Format("{0}, {1}{2}{3}{4}",this._Cap,_supported==0?"Not Supported":"",(_supported&TwQC.GetCurrent)!=0?string.Format("Current = {0}, ",this.GetCurrent()):"",(_supported&TwQC.GetDefault)!=0?string.Format("Default = {0}, ",this.GetDefault()):"",_supported!=0?string.Format("Supported = {{{0}}}",this.IsSupported()):""); + public override string ToString() + { + var _supported = this.IsSupported(); + return string.Format("{0}, {1}{2}{3}{4}", this._Cap, _supported == 0 ? "Not Supported" : "", (_supported & TwQC.GetCurrent) != 0 ? string.Format("Current = {0}, ", this.GetCurrent()) : "", (_supported & TwQC.GetDefault) != 0 ? string.Format("Default = {0}, ", this.GetDefault()) : "", _supported != 0 ? string.Format("Supported = {{{0}}}", this.IsSupported()) : ""); } } - [AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=false)] - private sealed class CapabilityAttribute:Attribute { + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] + private sealed class CapabilityAttribute : Attribute + { - public CapabilityAttribute(TwCap cap) { - this.Cap=cap; + public CapabilityAttribute(TwCap cap) + { + this.Cap = cap; } - public TwCap Cap { - get; - private set; - } + public TwCap Cap { get; private set; } } } /// - /// Представляет возможность (Capability). + /// Presents an capability. + /// Представляет возможность (Capability). /// /// Тип. - public interface ICapability { + public interface ICapability + { /// - /// Возвращает значения возможности (capability). + /// Returns capability values. + /// Возвращает значения возможности (capability). /// - /// Значения возможности (capability). + /// Capability Values.Значения возможности (capability). Twain32.Enumeration Get(); /// - /// Возвращает текущее значение возможности (capability). + /// Returns the current capability value. + /// Возвращает текущее значение возможности (capability). /// - /// Текущее значение возможности (capability). + /// Current Capability Value.Текущее значение возможности (capability). T GetCurrent(); /// - /// Возвращает значение по умолчанию возможности (capability). + /// Returns default value of feature (capability). + /// Возвращает значение по умолчанию возможности (capability). /// - /// Значение по умолчанию возможности (capability). + /// Feature Default (capability).Значение по умолчанию возможности (capability). T GetDefault(); /// - /// Устанавливает текущее значение возможности (capability). + /// Sets the current value of the capability. + /// Устанавливает текущее значение возможности (capability). /// - /// Значение. + /// Value.Значение. void Set(T value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(T value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(params T[] value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(Twain32.Range value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(Twain32.Enumeration value); /// - /// Сбрасывает текущее значение возможности (capability) в значение по умолчанию. + /// Resets the current capability value to the default value. + /// Сбрасывает текущее значение возможности (capability) в значение по умолчанию. /// void Reset(); /// - /// Возвращает набор флагов поддерживаемых операций. + /// Returns a set of flags of supported operations. + /// Возвращает набор флагов поддерживаемых операций. /// - /// Набор флагов поддерживаемых операций. + /// Set of flags of supported operations.Набор флагов поддерживаемых операций. TwQC IsSupported(); /// - /// Определяет поддерживаются ли указанные операции. Determines whether the specified operation is supported. + /// Determines whether the specified operation is supported. + /// Определяет поддерживаются ли указанные операции. /// - /// Набор битовых флагов, определяющих требуемые операйии. The operation. - /// Истина, если все указанные операции поддерживаются, иначе лож. True, if all specified operation is supported, otherwise false. + /// A set of bit flags defining the required operations.Набор битовых флагов, определяющих требуемые операйии. + /// True, if all specified operation is supported, otherwise false.Истина, если все указанные операции поддерживаются, иначе лож. bool IsSupported(TwQC operation); } /// - /// Представляет возможность (Capability). + /// Represents Capability. + /// Представляет возможность (Capability). /// /// Тип. - public interface ICapability2 { + public interface ICapability2 + { /// - /// Возвращает значения возможности (capability). + /// Returns the capability values. + /// Возвращает значения возможности (capability). /// - /// Значения возможности (capability). + /// Values of capability.Значения возможности (capability). Twain32.Enumeration Get(); /// - /// Возвращает текущие значения возможности (capability). + /// Returns the current capability value. + /// Возвращает текущие значения возможности (capability). /// - /// Текущие значения возможности (capability). + /// Current values of capability.Текущие значения возможности (capability). object[] GetCurrentArray(); /// - /// Возвращает значения по умолчанию возможности (capability). + /// Returns the default values of capability. + /// Возвращает значения по умолчанию возможности (capability). /// - /// Значения по умолчанию возможности (capability). + /// The default values are capability.Значения по умолчанию возможности (capability). object[] GetDefaultArray(); /// - /// Устанавливает текущее значение возможности (capability). + /// Sets the current value of capability. + /// Устанавливает текущее значение возможности (capability). /// - /// Значение. + /// Value.Значение. void Set(T value); /// - /// Устанавливает текущее значение возможности (capability). + /// Sets the current value of capability. + /// Устанавливает текущее значение возможности (capability). /// - /// Значение. + /// Value.Значение. void Set(params T[] value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(T value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(params T[] value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(Twain32.Range value); /// - /// Устанавливает ограничение на значения указанной возможности. + /// Sets a limit on the values of the specified feature. + /// Устанавливает ограничение на значения указанной возможности. /// - /// Устанавливаемое значение. + /// The value to set.Устанавливаемое значение. void SetConstraint(Twain32.Enumeration value); /// - /// Сбрасывает текущее значение возможности (capability) в значение по умолчанию. + /// Resets the current capability value to the default value. + /// Сбрасывает текущее значение возможности (capability) в значение по умолчанию. /// void Reset(); /// - /// Возвращает набор флагов поддерживаемых операций. + /// Returns a set of flags of supported operations. + /// Возвращает набор флагов поддерживаемых операций. /// - /// Набор флагов поддерживаемых операций. + /// Set of flags of supported operations.Набор флагов поддерживаемых операций. TwQC IsSupported(); /// - /// Определяет поддерживаются ли указанные операции. Determines whether the specified operation is supported. + /// Determines whether the specified operation is supported. + /// Определяет поддерживаются ли указанные операции. /// - /// Набор битовых флагов, определяющих требуемые операйии. The operation. - /// Истина, если все указанные операции поддерживаются, иначе лож. True, if all specified operation is supported, otherwise false. + /// A set of bit flags defining the required operations. The operation.Набор битовых флагов, определяющих требуемые операйии. + /// True, if all specified operation is supported, otherwise false.Истина, если все указанные операции поддерживаются, иначе лож. bool IsSupported(TwQC operation); } -} +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/TwainDefs.cs b/TownSuite.TwainScanner/TwainDefs.cs index 42e9fc3..dfdff9e 100644 --- a/TownSuite.TwainScanner/TwainDefs.cs +++ b/TownSuite.TwainScanner/TwainDefs.cs @@ -44,158 +44,161 @@ namespace TownSuite.TwainScanner /// Data Groups. /// [Flags] - internal enum TwDG:uint { // DG_..... + internal enum TwDG : uint + { // DG_..... /// /// Data pertaining to control. /// - Control=0x0001, + Control = 0x0001, /// /// Data pertaining to raster images. /// - Image=0x0002, + Image = 0x0002, /// /// Data pertaining to audio. /// - Audio=0x0004, + Audio = 0x0004, /// /// added to the identity by the DSM. /// - DSM2=0x10000000, + DSM2 = 0x10000000, /// /// Set by the App to indicate it would prefer to use DSM2. /// - APP2=0x20000000, + APP2 = 0x20000000, /// /// Set by the DS to indicate it would prefer to use DSM2. /// - DS2=0x40000000 + DS2 = 0x40000000 } /// /// Data codes. /// - internal enum TwDAT:ushort { // DAT_.... + internal enum TwDAT : ushort + { // DAT_.... #region Data Argument Types for the DG_CONTROL Data Group. - Null=0x0000, - Capability=0x0001, - Event=0x0002, - Identity=0x0003, - Parent=0x0004, - PendingXfers=0x0005, - SetupMemXfer=0x0006, - SetupFileXfer=0x0007, - Status=0x0008, - UserInterface=0x0009, - XferGroup=0x000a, - TwunkIdentity=0x000b, - CustomDSData=0x000c, - DeviceEvent=0x000d, - FileSystem=0x000e, - PassThru=0x000f, - Callback=0x0010, /* TW_CALLBACK Added 2.0 */ - StatusUtf8=0x0011, /* TW_STATUSUTF8 Added 2.1 */ - Callback2=0x0012, + Null = 0x0000, + Capability = 0x0001, + Event = 0x0002, + Identity = 0x0003, + Parent = 0x0004, + PendingXfers = 0x0005, + SetupMemXfer = 0x0006, + SetupFileXfer = 0x0007, + Status = 0x0008, + UserInterface = 0x0009, + XferGroup = 0x000a, + TwunkIdentity = 0x000b, + CustomDSData = 0x000c, + DeviceEvent = 0x000d, + FileSystem = 0x000e, + PassThru = 0x000f, + Callback = 0x0010, /* TW_CALLBACK Added 2.0 */ + StatusUtf8 = 0x0011, /* TW_STATUSUTF8 Added 2.1 */ + Callback2 = 0x0012, #endregion #region Data Argument Types for the DG_IMAGE Data Group. - ImageInfo=0x0101, - ImageLayout=0x0102, - ImageMemXfer=0x0103, - ImageNativeXfer=0x0104, - ImageFileXfer=0x0105, - CieColor=0x0106, - GrayResponse=0x0107, - RGBResponse=0x0108, - JpegCompression=0x0109, - Palette8=0x010a, - ExtImageInfo=0x010b, + ImageInfo = 0x0101, + ImageLayout = 0x0102, + ImageMemXfer = 0x0103, + ImageNativeXfer = 0x0104, + ImageFileXfer = 0x0105, + CieColor = 0x0106, + GrayResponse = 0x0107, + RGBResponse = 0x0108, + JpegCompression = 0x0109, + Palette8 = 0x010a, + ExtImageInfo = 0x010b, #endregion #region misplaced - IccProfile=0x0401, /* TW_MEMORY Added 1.91 This Data Argument is misplaced but belongs to the DG_IMAGE Data Group */ - ImageMemFileXfer=0x0402, /* TW_IMAGEMEMXFER Added 1.91 This Data Argument is misplaced but belongs to the DG_IMAGE Data Group */ - EntryPoint=0x0403, /* TW_ENTRYPOINT Added 2.0 This Data Argument is misplaced but belongs to the DG_CONTROL Data Group */ - + IccProfile = 0x0401, /* TW_MEMORY Added 1.91 This Data Argument is misplaced but belongs to the DG_IMAGE Data Group */ + ImageMemFileXfer = 0x0402, /* TW_IMAGEMEMXFER Added 1.91 This Data Argument is misplaced but belongs to the DG_IMAGE Data Group */ + EntryPoint = 0x0403, /* TW_ENTRYPOINT Added 2.0 This Data Argument is misplaced but belongs to the DG_CONTROL Data Group */ + #endregion } /// /// Messages. /// - internal enum TwMSG:ushort { // MSG_..... + internal enum TwMSG : ushort + { // MSG_..... #region Generic messages may be used with any of several DATs. /// /// Used in TW_EVENT structure. /// - Null=0x0000, + Null = 0x0000, /// /// Get one or more values. /// - Get=0x0001, + Get = 0x0001, /// /// Get current value. /// - GetCurrent=0x0002, + GetCurrent = 0x0002, /// /// Get default (e.g. power up) value. /// - GetDefault=0x0003, + GetDefault = 0x0003, /// /// Get first of a series of items, e.g. DSs. /// - GetFirst=0x0004, + GetFirst = 0x0004, /// /// Iterate through a series of items. /// - GetNext=0x0005, + GetNext = 0x0005, /// /// Set one or more values. /// - Set=0x0006, + Set = 0x0006, /// /// Set current value to default value. /// - Reset=0x0007, + Reset = 0x0007, /// /// Get supported operations on the cap. /// - QuerySupport=0x0008, + QuerySupport = 0x0008, - GetHelp=0x0009, - GetLabel=0x000a, - GetLabelEnum=0x000b, - SetConstraint=0x000c, + GetHelp = 0x0009, + GetLabel = 0x000a, + GetLabelEnum = 0x000b, + SetConstraint = 0x000c, #endregion #region Messages used with DAT_NULL - XFerReady=0x0101, - CloseDSReq=0x0102, - CloseDSOK=0x0103, - DeviceEvent=0x0104, + XFerReady = 0x0101, + CloseDSReq = 0x0102, + CloseDSOK = 0x0103, + DeviceEvent = 0x0104, #endregion @@ -204,7 +207,7 @@ internal enum TwMSG:ushort { // MSG_..... /// /// Get status information /// - CheckStatus=0x0201, + CheckStatus = 0x0201, #endregion @@ -213,12 +216,12 @@ internal enum TwMSG:ushort { // MSG_..... /// /// Open the DSM /// - OpenDSM=0x0301, + OpenDSM = 0x0301, /// /// Close the DSM /// - CloseDSM=0x0302, + CloseDSM = 0x0302, #endregion @@ -227,17 +230,17 @@ internal enum TwMSG:ushort { // MSG_..... /// /// Open a data source /// - OpenDS=0x0401, + OpenDS = 0x0401, /// /// Close a data source /// - CloseDS=0x0402, + CloseDS = 0x0402, /// /// Put up a dialog of all DS /// - UserSelect=0x0403, + UserSelect = 0x0403, #endregion @@ -246,64 +249,64 @@ internal enum TwMSG:ushort { // MSG_..... /// /// Disable data transfer in the DS /// - DisableDS=0x0501, + DisableDS = 0x0501, /// /// Enable data transfer in the DS /// - EnableDS=0x0502, + EnableDS = 0x0502, /// /// Enable for saving DS state only. /// - EnableDSUIOnly=0x0503, + EnableDSUIOnly = 0x0503, #endregion #region Messages used with a pointer to a DAT_EVENT structure - ProcessEvent=0x0601, + ProcessEvent = 0x0601, #endregion #region Messages used with a pointer to a DAT_PENDINGXFERS structure - EndXfer=0x0701, - StopFeeder=0x0702, + EndXfer = 0x0701, + StopFeeder = 0x0702, #endregion #region Messages used with a pointer to a DAT_FILESYSTEM structure - ChangeDirectory=0x0801, - CreateDirectory=0x0802, - Delete=0x0803, - FormatMedia=0x0804, - GetClose=0x0805, - GetFirstFile=0x0806, - GetInfo=0x0807, - GetNextFile=0x0808, - Rename=0x0809, - Copy=0x080A, - AutoCaptureDir=0x080B, + ChangeDirectory = 0x0801, + CreateDirectory = 0x0802, + Delete = 0x0803, + FormatMedia = 0x0804, + GetClose = 0x0805, + GetFirstFile = 0x0806, + GetInfo = 0x0807, + GetNextFile = 0x0808, + Rename = 0x0809, + Copy = 0x080A, + AutoCaptureDir = 0x080B, #endregion #region Messages used with a pointer to a DAT_PASSTHRU structure - PassThru=0x0901, + PassThru = 0x0901, #endregion #region used with DAT_CALLBACK - RegisterCallback=0x0902, + RegisterCallback = 0x0902, #endregion #region used with DAT_CAPABILITY - ResetAll=0x0A01 + ResetAll = 0x0A01 #endregion } @@ -311,7 +314,8 @@ internal enum TwMSG:ushort { // MSG_..... /// /// Return Codes /// - public enum TwRC:ushort { // TWRC_.... + public enum TwRC : ushort + { // TWRC_.... /// /// Operation was successful. @@ -382,7 +386,8 @@ public enum TwRC:ushort { // TWRC_.... /// /// Condition Codes /// - public enum TwCC:ushort { // TWCC_.... + public enum TwCC : ushort + { // TWCC_.... /// /// Operation was successful. This value should only be paired with TWRC_SUCCESS. @@ -550,57 +555,61 @@ public enum TwCC:ushort { // TWCC_.... /// /// Generic Constants /// - internal enum TwOn:ushort { // TWON_.... + internal enum TwOn : ushort + { // TWON_.... /// /// Indicates TW_ARRAY container /// - Array=0x0003, + Array = 0x0003, /// /// Indicates TW_ENUMERATION container /// - Enum=0x0004, + Enum = 0x0004, /// /// Indicates TW_ONEVALUE container /// - One=0x0005, + One = 0x0005, /// /// Indicates TW_RANGE container /// - Range=0x0006, - DontCare=0xffff + Range = 0x0006, + DontCare = 0xffff } /// /// Data Types /// - internal enum TwType:ushort { // TWTY_.... - Int8=0x0000, - Int16=0x0001, - Int32=0x0002, - UInt8=0x0003, - UInt16=0x0004, - UInt32=0x0005, - Bool=0x0006, - Fix32=0x0007, - Frame=0x0008, - Str32=0x0009, - Str64=0x000a, - Str128=0x000b, - Str255=0x000c, - Str1024=0x000d, - Uni512=0x000e, - Handle=0x000f - } - - /// - /// Вспомогательный класс для типов twain. - /// - internal sealed class TwTypeHelper { - private static Dictionary _typeof=new Dictionary { + internal enum TwType : ushort + { // TWTY_.... + Int8 = 0x0000, + Int16 = 0x0001, + Int32 = 0x0002, + UInt8 = 0x0003, + UInt16 = 0x0004, + UInt32 = 0x0005, + Bool = 0x0006, + Fix32 = 0x0007, + Frame = 0x0008, + Str32 = 0x0009, + Str64 = 0x000a, + Str128 = 0x000b, + Str255 = 0x000c, + Str1024 = 0x000d, + Uni512 = 0x000e, + Handle = 0x000f + } + + /// + /// Helper class for twain types. + /// Вспомогательный класс для типов twain. + /// + internal sealed class TwTypeHelper + { + private static Dictionary _typeof = new Dictionary { {TwType.Int8,typeof(sbyte)}, {TwType.Int16,typeof(short)}, {TwType.Int32,typeof(int)}, @@ -618,7 +627,7 @@ internal sealed class TwTypeHelper { {TwType.Uni512,typeof(TwUni512)}, {TwType.Handle,typeof(IntPtr)} }; - private static Dictionary _typeofAux=new Dictionary { + private static Dictionary _typeofAux = new Dictionary { {32,TwType.Str32}, {64,TwType.Str64}, {128,TwType.Str128}, @@ -628,67 +637,84 @@ internal sealed class TwTypeHelper { }; /// - /// Возвращает соответствующий twain-типу управляемый тип. + /// Returns the corresponding twain type of the managed type. + /// Возвращает соответствующий twain-типу управляемый тип. /// - /// Код типа данный twain. - /// Управляемый тип. - internal static Type TypeOf(TwType type) { + /// Type code given by twain.Код типа данный twain. + /// Managed type.Управляемый тип. + internal static Type TypeOf(TwType type) + { return TwTypeHelper._typeof[type]; } /// - /// Возвращает соответствующий управляемому типу twain-тип. + /// Returns the corresponding twain type for the managed type. + /// Возвращает соответствующий управляемому типу twain-тип. /// - /// Управляемый тип. - /// Код типа данный twain. - internal static TwType TypeOf(Type type) { - Type _type=type.IsEnum?Enum.GetUnderlyingType(type):type; - foreach(var _item in TwTypeHelper._typeof) { - if(_item.Value==_type) { + /// Managed type.Управляемый тип. + /// Type code given by twain.Код типа данный twain. + internal static TwType TypeOf(Type type) + { + Type _type = type.IsEnum ? Enum.GetUnderlyingType(type) : type; + foreach (var _item in TwTypeHelper._typeof) + { + if (_item.Value == _type) + { return _item.Key; } } - if(type==typeof(bool)) { + if (type == typeof(bool)) + { return TwType.Bool; } - if(type==typeof(float)) { + if (type == typeof(float)) + { return TwType.Fix32; } - if(type==typeof(RectangleF)) { + if (type == typeof(RectangleF)) + { return TwType.Frame; } throw new KeyNotFoundException(); } /// - /// Возвращает соответствующий объекту twain-тип. + /// Returns the corresponding twain type. + /// Возвращает соответствующий объекту twain-тип. /// - /// Объект. - /// Код типа данный twain. - internal static TwType TypeOf(object obj) { - if(obj is string) { + /// An object.Объект. + /// Type code given by twain.Код типа данный twain. + internal static TwType TypeOf(object obj) + { + if (obj is string) + { return TwTypeHelper._typeofAux[((string)obj).Length]; } return TwTypeHelper.TypeOf(obj.GetType()); } /// - /// Возвращает размер twain-типа в неуправляемом блоке памяти. + /// Returns the size of a twain type in an unmanaged memory block. + /// Возвращает размер twain-типа в неуправляемом блоке памяти. /// - /// Код типа данный twain. - /// Размер в байтах. - internal static int SizeOf(TwType type) { + /// Type code given by twain.Код типа данный twain. + /// Size in bytes.Размер в байтах. + internal static int SizeOf(TwType type) + { return Marshal.SizeOf(TwTypeHelper._typeof[type]); } /// - /// Приводит внутренние типы компонента к общим типам среды. + /// Converts internal component types to common environment types. + /// Приводит внутренние типы компонента к общим типам среды. /// - /// Код twain-типа. - /// Экземпляр объекта. - /// Экземпляр объекта. - internal static object CastToCommon(TwType type,object value) { - switch(type) { + /// Twain type code.Код twain-типа. + /// Instance of the object.Экземпляр объекта. + /// Instance of the object.Экземпляр объекта. + internal static object CastToCommon(TwType type, object value) + { + switch (type) + { case TwType.Bool: return (bool)(TwBool)value; case TwType.Fix32: @@ -707,13 +733,16 @@ internal static object CastToCommon(TwType type,object value) { } /// - /// Приводит общие типы среды к внутренним типам компонента. + /// Converts generic media types to internal component types. + /// Приводит общие типы среды к внутренним типам компонента. /// - /// Код twain-типа. - /// Экземпляр объекта. - /// Экземпляр объекта. - internal static object CastToTw(TwType type,object value) { - switch(type) { + /// Twain type code.Код twain-типа. + /// Instance of the object.Экземпляр объекта. + /// Instance of the object.Экземпляр объекта. + internal static object CastToTw(TwType type, object value) + { + switch (type) + { case TwType.Bool: return (TwBool)(bool)value; case TwType.Fix32: @@ -734,60 +763,74 @@ internal static object CastToTw(TwType type,object value) { return (TwStr1024)value.ToString(); } - Type _type=value.GetType(); - if(_type.IsEnum&&Enum.GetUnderlyingType(_type)==TwTypeHelper.TypeOf(type)) { - return Convert.ChangeType(value,Enum.GetUnderlyingType(_type)); + Type _type = value.GetType(); + if (_type.IsEnum && Enum.GetUnderlyingType(_type) == TwTypeHelper.TypeOf(type)) + { + return Convert.ChangeType(value, Enum.GetUnderlyingType(_type)); } return value; } /// - /// Выполняет преобразование значения в экземпляр внутреннего типа компонента. + /// Converts a value to an instance of the component's internal type. + /// Выполняет преобразование значения в экземпляр внутреннего типа компонента. /// /// Тип значения. - /// Код twain-типа. - /// Значение. - /// Экземпляр объекта. - internal static object ValueToTw(TwType type,T value) { - int _size=Marshal.SizeOf(typeof(T)); - IntPtr _mem=Marshal.AllocHGlobal(_size); - Twain32._Memory.ZeroMemory(_mem,(IntPtr)_size); - try { - Marshal.StructureToPtr(value,_mem,true); - return Marshal.PtrToStructure(_mem,TwTypeHelper.TypeOf(type)); - } finally { + /// Twain type code.Код twain-типа. + /// Value.Значение. + /// Instance of the object.Экземпляр объекта. + internal static object ValueToTw(TwType type, T value) + { + int _size = Marshal.SizeOf(typeof(T)); + IntPtr _mem = Marshal.AllocHGlobal(_size); + Twain32._Memory.ZeroMemory(_mem, (IntPtr)_size); + try + { + Marshal.StructureToPtr(value, _mem, true); + return Marshal.PtrToStructure(_mem, TwTypeHelper.TypeOf(type)); + } + finally + { Marshal.FreeHGlobal(_mem); } } /// - /// Выполняет преобразование экземпляра внутреннего типа компонента в значение. + /// Converts an instance of an internal component type to a value. + /// Выполняет преобразование экземпляра внутреннего типа компонента в значение. /// /// Тип значения. - /// Экземпляр объекта. - /// Значение. - internal static T ValueFromTw(object value) { - int _size=Math.Max(Marshal.SizeOf(typeof(T)),Marshal.SizeOf(value)); - IntPtr _mem=Marshal.AllocHGlobal(_size); - Twain32._Memory.ZeroMemory(_mem,(IntPtr)_size); - try { - Marshal.StructureToPtr(value,_mem,true); - return (T)Marshal.PtrToStructure(_mem,typeof(T)); - } finally { + /// Instance of the object.Экземпляр объекта. + /// Value.Значение. + internal static T ValueFromTw(object value) + { + int _size = Math.Max(Marshal.SizeOf(typeof(T)), Marshal.SizeOf(value)); + IntPtr _mem = Marshal.AllocHGlobal(_size); + Twain32._Memory.ZeroMemory(_mem, (IntPtr)_size); + try + { + Marshal.StructureToPtr(value, _mem, true); + return (T)Marshal.PtrToStructure(_mem, typeof(T)); + } + finally + { Marshal.FreeHGlobal(_mem); } } } - [AttributeUsage(AttributeTargets.Field,AllowMultiple=false,Inherited=false)] - internal sealed class TwTypeAttribute:Attribute { + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] + internal sealed class TwTypeAttribute : Attribute + { - public TwTypeAttribute(TwType type) { - this.TwType=type; + public TwTypeAttribute(TwType type) + { + this.TwType = type; } - public TwType TwType { + public TwType TwType + { get; private set; } @@ -796,207 +839,210 @@ public TwType TwType { /// /// Capability Constants /// - public enum TwCap:ushort { + public enum TwCap : ushort + { /* image data sources MAY support these caps */ -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - XferCount=0x0001, // all data sources are REQUIRED to support these caps - ICompression=0x0100, // ICAP_... - IPixelType=0x0101, - IUnits=0x0102, //default is TWUN_INCHES - IXferMech=0x0103, - AutoBright=0x1100, - Brightness=0x1101, - Contrast=0x1103, - CustHalftone=0x1104, - ExposureTime=0x1105, - Filter=0x1106, - FlashUsed=0x1107, - Gamma=0x1108, - +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + XferCount = 0x0001, // all data sources are REQUIRED to support these caps + ICompression = 0x0100, // ICAP_... + IPixelType = 0x0101, + IUnits = 0x0102, //default is TWUN_INCHES + IXferMech = 0x0103, + AutoBright = 0x1100, + Brightness = 0x1101, + Contrast = 0x1103, + CustHalftone = 0x1104, + ExposureTime = 0x1105, + Filter = 0x1106, + FlashUsed = 0x1107, + Gamma = 0x1108, + [TwType(TwType.Str32)] - Halftones=0x1109, - - Highlight=0x110a, - ImageFileFormat=0x110c, - LampState=0x110d, - LightSource=0x110e, - Orientation=0x1110, - PhysicalWidth=0x1111, - PhysicalHeight=0x1112, - Shadow=0x1113, - Frames=0x1114, - XNativeResolution=0x1116, - YNativeResolution=0x1117, - XResolution=0x1118, - YResolution=0x1119, - MaxFrames=0x111a, - Tiles=0x111b, - BitOrder=0x111c, - CcittKFactor=0x111d, - LightPath=0x111e, - PixelFlavor=0x111f, - PlanarChunky=0x1120, - Rotation=0x1121, - SupportedSizes=0x1122, - Threshold=0x1123, - XScaling=0x1124, - YScaling=0x1125, - BitOrderCodes=0x1126, - PixelFlavorCodes=0x1127, - JpegPixelType=0x1128, - TimeFill=0x112a, - BitDepth=0x112b, - BitDepthReduction=0x112c, /* Added 1.5 */ - UndefinedImageSize=0x112d, /* Added 1.6 */ - ImageDataSet=0x112e, /* Added 1.7 */ - ExtImageInfo=0x112f, /* Added 1.7 */ - MinimumHeight=0x1130, /* Added 1.7 */ - MinimumWidth=0x1131, /* Added 1.7 */ - AutoDiscardBlankPages=0x1134, /* Added 2.0 */ - FlipRotation=0x1136, /* Added 1.8 */ - BarCodeDetectionEnabled=0x1137, /* Added 1.8 */ - SupportedBarCodeTypes=0x1138, /* Added 1.8 */ - BarCodeMaxSearchPriorities=0x1139, /* Added 1.8 */ - BarCodeSearchPriorities=0x113a, /* Added 1.8 */ - BarCodeSearchMode=0x113b, /* Added 1.8 */ - BarCodeMaxRetries=0x113c, /* Added 1.8 */ - BarCodeTimeout=0x113d, /* Added 1.8 */ - ZoomFactor=0x113e, /* Added 1.8 */ - PatchCodeDetectionEnabled=0x113f, /* Added 1.8 */ - SupportedPatchCodeTypes=0x1140, /* Added 1.8 */ - PatchCodeMaxSearchPriorities=0x1141, /* Added 1.8 */ - PatchCodeSearchPriorities=0x1142, /* Added 1.8 */ - PatchCodeSearchMode=0x1143, /* Added 1.8 */ - PatchCodeMaxRetries=0x1144, /* Added 1.8 */ - PatchCodeTimeout=0x1145, /* Added 1.8 */ - FlashUsed2=0x1146, /* Added 1.8 */ - ImageFilter=0x1147, /* Added 1.8 */ - NoiseFilter=0x1148, /* Added 1.8 */ - OverScan=0x1149, /* Added 1.8 */ - AutomaticBorderDetection=0x1150, /* Added 1.8 */ - AutomaticDeskew=0x1151, /* Added 1.8 */ - AutomaticRotate=0x1152, /* Added 1.8 */ - JpegQuality=0x1153, /* Added 1.9 */ - FeederType=0x1154, - IccProfile=0x1155, - AutoSize=0x1156, - AutomaticCropUsesFrame=0x1157, - AutomaticLengthDetection=0x1158, - AutomaticColorEnabled=0x1159, - AutomaticColorNonColorPixelType=0x115a, - ColorManagementEnabled=0x115b, - ImageMerge=0x115c, - ImageMergeHeightThreshold=0x115d, - SupportedExtImageInfo=0x115e, - FilmType=0x115f, - Mirror=0x1160, - JpegSubSampling=0x1161, + Halftones = 0x1109, + + Highlight = 0x110a, + ImageFileFormat = 0x110c, + LampState = 0x110d, + LightSource = 0x110e, + Orientation = 0x1110, + PhysicalWidth = 0x1111, + PhysicalHeight = 0x1112, + Shadow = 0x1113, + Frames = 0x1114, + XNativeResolution = 0x1116, + YNativeResolution = 0x1117, + XResolution = 0x1118, + YResolution = 0x1119, + MaxFrames = 0x111a, + Tiles = 0x111b, + BitOrder = 0x111c, + CcittKFactor = 0x111d, + LightPath = 0x111e, + PixelFlavor = 0x111f, + PlanarChunky = 0x1120, + Rotation = 0x1121, + SupportedSizes = 0x1122, + Threshold = 0x1123, + XScaling = 0x1124, + YScaling = 0x1125, + BitOrderCodes = 0x1126, + PixelFlavorCodes = 0x1127, + JpegPixelType = 0x1128, + TimeFill = 0x112a, + BitDepth = 0x112b, + BitDepthReduction = 0x112c, /* Added 1.5 */ + UndefinedImageSize = 0x112d, /* Added 1.6 */ + ImageDataSet = 0x112e, /* Added 1.7 */ + ExtImageInfo = 0x112f, /* Added 1.7 */ + MinimumHeight = 0x1130, /* Added 1.7 */ + MinimumWidth = 0x1131, /* Added 1.7 */ + AutoDiscardBlankPages = 0x1134, /* Added 2.0 */ + FlipRotation = 0x1136, /* Added 1.8 */ + BarCodeDetectionEnabled = 0x1137, /* Added 1.8 */ + SupportedBarCodeTypes = 0x1138, /* Added 1.8 */ + BarCodeMaxSearchPriorities = 0x1139, /* Added 1.8 */ + BarCodeSearchPriorities = 0x113a, /* Added 1.8 */ + BarCodeSearchMode = 0x113b, /* Added 1.8 */ + BarCodeMaxRetries = 0x113c, /* Added 1.8 */ + BarCodeTimeout = 0x113d, /* Added 1.8 */ + ZoomFactor = 0x113e, /* Added 1.8 */ + PatchCodeDetectionEnabled = 0x113f, /* Added 1.8 */ + SupportedPatchCodeTypes = 0x1140, /* Added 1.8 */ + PatchCodeMaxSearchPriorities = 0x1141, /* Added 1.8 */ + PatchCodeSearchPriorities = 0x1142, /* Added 1.8 */ + PatchCodeSearchMode = 0x1143, /* Added 1.8 */ + PatchCodeMaxRetries = 0x1144, /* Added 1.8 */ + PatchCodeTimeout = 0x1145, /* Added 1.8 */ + FlashUsed2 = 0x1146, /* Added 1.8 */ + ImageFilter = 0x1147, /* Added 1.8 */ + NoiseFilter = 0x1148, /* Added 1.8 */ + OverScan = 0x1149, /* Added 1.8 */ + AutomaticBorderDetection = 0x1150, /* Added 1.8 */ + AutomaticDeskew = 0x1151, /* Added 1.8 */ + AutomaticRotate = 0x1152, /* Added 1.8 */ + JpegQuality = 0x1153, /* Added 1.9 */ + FeederType = 0x1154, + IccProfile = 0x1155, + AutoSize = 0x1156, + AutomaticCropUsesFrame = 0x1157, + AutomaticLengthDetection = 0x1158, + AutomaticColorEnabled = 0x1159, + AutomaticColorNonColorPixelType = 0x115a, + ColorManagementEnabled = 0x115b, + ImageMerge = 0x115c, + ImageMergeHeightThreshold = 0x115d, + SupportedExtImageInfo = 0x115e, + FilmType = 0x115f, + Mirror = 0x1160, + JpegSubSampling = 0x1161, /* all data sources MAY support these caps */ [TwType(TwType.Str128)] - Author=0x1000, + Author = 0x1000, [TwType(TwType.Str255)] - Caption=0x1001, + Caption = 0x1001, - FeederEnabled=0x1002, - FeederLoaded=0x1003, + FeederEnabled = 0x1002, + FeederLoaded = 0x1003, [TwType(TwType.Str32)] - TimeDate=0x1004, - - SupportedCaps=0x1005, - ExtendedCaps=0x1006, - AutoFeed=0x1007, - ClearPage=0x1008, - FeedPage=0x1009, - RewindPage=0x100a, - Indicators=0x100b, /* Added 1.1 */ - SupportedCapsExt=0x100c, /* Added 1.6 */ - PaperDetectable=0x100d, /* Added 1.6 */ - UIControllable=0x100e, /* Added 1.6 */ - DeviceOnline=0x100f, /* Added 1.6 */ - AutoScan=0x1010, /* Added 1.6 */ - ThumbnailsEnabled=0x1011, /* Added 1.7 */ - Duplex=0x1012, /* Added 1.7 */ - DuplexEnabled=0x1013, /* Added 1.7 */ - EnableDSUIOnly=0x1014, /* Added 1.7 */ - CustomDSData=0x1015, /* Added 1.7 */ - Endorser=0x1016, /* Added 1.7 */ - JobControl=0x1017, /* Added 1.7 */ - Alarms=0x1018, /* Added 1.8 */ - AlarmVolume=0x1019, /* Added 1.8 */ - AutomaticCapture=0x101a, /* Added 1.8 */ - TimeBeforeFirstCapture=0x101b, /* Added 1.8 */ - TimeBetweenCaptures=0x101c, /* Added 1.8 */ - ClearBuffers=0x101d, /* Added 1.8 */ - MaxBatchBuffers=0x101e, /* Added 1.8 */ + TimeDate = 0x1004, + + SupportedCaps = 0x1005, + ExtendedCaps = 0x1006, + AutoFeed = 0x1007, + ClearPage = 0x1008, + FeedPage = 0x1009, + RewindPage = 0x100a, + Indicators = 0x100b, /* Added 1.1 */ + SupportedCapsExt = 0x100c, /* Added 1.6 */ + PaperDetectable = 0x100d, /* Added 1.6 */ + UIControllable = 0x100e, /* Added 1.6 */ + DeviceOnline = 0x100f, /* Added 1.6 */ + AutoScan = 0x1010, /* Added 1.6 */ + ThumbnailsEnabled = 0x1011, /* Added 1.7 */ + Duplex = 0x1012, /* Added 1.7 */ + DuplexEnabled = 0x1013, /* Added 1.7 */ + EnableDSUIOnly = 0x1014, /* Added 1.7 */ + CustomDSData = 0x1015, /* Added 1.7 */ + Endorser = 0x1016, /* Added 1.7 */ + JobControl = 0x1017, /* Added 1.7 */ + Alarms = 0x1018, /* Added 1.8 */ + AlarmVolume = 0x1019, /* Added 1.8 */ + AutomaticCapture = 0x101a, /* Added 1.8 */ + TimeBeforeFirstCapture = 0x101b, /* Added 1.8 */ + TimeBetweenCaptures = 0x101c, /* Added 1.8 */ + ClearBuffers = 0x101d, /* Added 1.8 */ + MaxBatchBuffers = 0x101e, /* Added 1.8 */ [TwType(TwType.Str32)] - DeviceTimeDate=0x101f, /* Added 1.8 */ + DeviceTimeDate = 0x101f, /* Added 1.8 */ - PowerSupply=0x1020, /* Added 1.8 */ - CameraPreviewUI=0x1021, /* Added 1.8 */ - DeviceEvent=0x1022, /* Added 1.8 */ + PowerSupply = 0x1020, /* Added 1.8 */ + CameraPreviewUI = 0x1021, /* Added 1.8 */ + DeviceEvent = 0x1022, /* Added 1.8 */ [TwType(TwType.Str255)] - SerialNumber=0x1024, /* Added 1.8 */ + SerialNumber = 0x1024, /* Added 1.8 */ + + Printer = 0x1026, /* Added 1.8 */ + PrinterEnabled = 0x1027, /* Added 1.8 */ + PrinterIndex = 0x1028, /* Added 1.8 */ + PrinterMode = 0x1029, /* Added 1.8 */ - Printer=0x1026, /* Added 1.8 */ - PrinterEnabled=0x1027, /* Added 1.8 */ - PrinterIndex=0x1028, /* Added 1.8 */ - PrinterMode=0x1029, /* Added 1.8 */ - [TwType(TwType.Str255)] - PrinterString=0x102a, /* Added 1.8 */ + PrinterString = 0x102a, /* Added 1.8 */ [TwType(TwType.Str255)] - PrinterSuffix=0x102b, /* Added 1.8 */ - - Language=0x102c, /* Added 1.8 */ - FeederAlignment=0x102d, /* Added 1.8 */ - FeederOrder=0x102e, /* Added 1.8 */ - ReacquireAllowed=0x1030, /* Added 1.8 */ - BatteryMinutes=0x1032, /* Added 1.8 */ - BatteryPercentage=0x1033, /* Added 1.8 */ - CameraSide=0x1034, - Segmented=0x1035, - CameraEnabled=0x1036, - CameraOrder=0x1037, - MicrEnabled=0x1038, - FeederPrep=0x1039, - FeederPocket=0x103a, - AutomaticSenseMedium=0x103b, - + PrinterSuffix = 0x102b, /* Added 1.8 */ + + Language = 0x102c, /* Added 1.8 */ + FeederAlignment = 0x102d, /* Added 1.8 */ + FeederOrder = 0x102e, /* Added 1.8 */ + ReacquireAllowed = 0x1030, /* Added 1.8 */ + BatteryMinutes = 0x1032, /* Added 1.8 */ + BatteryPercentage = 0x1033, /* Added 1.8 */ + CameraSide = 0x1034, + Segmented = 0x1035, + CameraEnabled = 0x1036, + CameraOrder = 0x1037, + MicrEnabled = 0x1038, + FeederPrep = 0x1039, + FeederPocket = 0x103a, + AutomaticSenseMedium = 0x103b, + [TwType(TwType.Str255)] - CustomInterfaceGuid=0x103c, - - SupportedCapsSegmentUnique=0x103d, - SupportedDats=0x103e, - DoubleFeedDetection=0x103f, - DoubleFeedDetectionLength=0x1040, - DoubleFeedDetectionSensitivity=0x1041, - DoubleFeedDetectionResponse=0x1042, - PaperHandling=0x1043, - IndicatorsMode=0x1044, - PrinterVerticalOffset=0x1045, - PowerSaveTime=0x1046, - PrinterCharRotation=0x1047, - PrinterFontStyle=0x1048, - PrinterIndexLeadChar=0x1049, - PrinterIndexMaxValue=0x104A, - PrinterIndexNumDigits=0x104B, - PrinterIndexStep=0x104C, - PrinterIndexTrigger=0x104D, - PrinterStringPreview=0x104E -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + CustomInterfaceGuid = 0x103c, + + SupportedCapsSegmentUnique = 0x103d, + SupportedDats = 0x103e, + DoubleFeedDetection = 0x103f, + DoubleFeedDetectionLength = 0x1040, + DoubleFeedDetectionSensitivity = 0x1041, + DoubleFeedDetectionResponse = 0x1042, + PaperHandling = 0x1043, + IndicatorsMode = 0x1044, + PrinterVerticalOffset = 0x1045, + PowerSaveTime = 0x1046, + PrinterCharRotation = 0x1047, + PrinterFontStyle = 0x1048, + PrinterIndexLeadChar = 0x1049, + PrinterIndexMaxValue = 0x104A, + PrinterIndexNumDigits = 0x104B, + PrinterIndexStep = 0x104C, + PrinterIndexTrigger = 0x104D, + PrinterStringPreview = 0x104E, + SheetCount = 0x104F // Controls the number of sheets scanned (compare to CAP_XFERCOUNT that controls images) +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Bit patterns: for query the operation that are supported by the data source on a capability. /// [Flags] - public enum TwQC:ushort { //TWQC_... + public enum TwQC : ushort + { //TWQC_... /// /// Returns the Current, Default and Available settings for a capability. @@ -1034,1305 +1080,1365 @@ public enum TwQC:ushort { //TWQC_... /// SetConstraint = 0x0020, -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - ConstrainAble=0x0040, - GetHelp=0x0100, - GetLabel=0x0200, - GetLabelEnum=0x0400 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + ConstrainAble = 0x0040, + GetHelp = 0x0100, + GetLabel = 0x0200, + GetLabelEnum = 0x0400 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Language Constants /// - public enum TwLanguage:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - DANISH=0, /* Danish */ - DUTCH=1, /* Dutch */ - ENGLISH=2, /* International English */ - FRENCH_CANADIAN=3, /* French Canadian */ - FINNISH=4, /* Finnish */ - FRENCH=5, /* French */ - GERMAN=6, /* German */ - ICELANDIC=7, /* Icelandic */ - ITALIAN=8, /* Italian */ - NORWEGIAN=9, /* Norwegian */ - PORTUGUESE=10, /* Portuguese */ - SPANISH=11, /* Spanish */ - SWEDISH=12, /* Swedish */ - ENGLISH_USA=13, /* U.S. English */ - AFRIKAANS=14, - ALBANIA=15, - ARABIC=16, - ARABIC_ALGERIA=17, - ARABIC_BAHRAIN=18, - ARABIC_EGYPT=19, - ARABIC_IRAQ=20, - ARABIC_JORDAN=21, - ARABIC_KUWAIT=22, - ARABIC_LEBANON=23, - ARABIC_LIBYA=24, - ARABIC_MOROCCO=25, - ARABIC_OMAN=26, - ARABIC_QATAR=27, - ARABIC_SAUDIARABIA=28, - ARABIC_SYRIA=29, - ARABIC_TUNISIA=30, - ARABIC_UAE=31, /* United Arabic Emirates */ - ARABIC_YEMEN=32, - BASQUE=33, - BYELORUSSIAN=34, - BULGARIAN=35, - CATALAN=36, - CHINESE=37, - CHINESE_HONGKONG=38, - CHINESE_PRC=39, /* People's Republic of China */ - CHINESE_SINGAPORE=40, - CHINESE_SIMPLIFIED=41, - CHINESE_TAIWAN=42, - CHINESE_TRADITIONAL=43, - CROATIA=44, - CZECH=45, - DUTCH_BELGIAN=46, - ENGLISH_AUSTRALIAN=47, - ENGLISH_CANADIAN=48, - ENGLISH_IRELAND=49, - ENGLISH_NEWZEALAND=50, - ENGLISH_SOUTHAFRICA=51, - ENGLISH_UK=52, - ESTONIAN=53, - FAEROESE=54, - FARSI=55, - FRENCH_BELGIAN=56, - FRENCH_LUXEMBOURG=57, - FRENCH_SWISS=58, - GERMAN_AUSTRIAN=59, - GERMAN_LUXEMBOURG=60, - GERMAN_LIECHTENSTEIN=61, - GERMAN_SWISS=62, - GREEK=63, - HEBREW=64, - HUNGARIAN=65, - INDONESIAN=66, - ITALIAN_SWISS=67, - JAPANESE=68, - KOREAN=69, - KOREAN_JOHAB=70, - LATVIAN=71, - LITHUANIAN=72, - NORWEGIAN_BOKMAL=73, - NORWEGIAN_NYNORSK=74, - POLISH=75, - PORTUGUESE_BRAZIL=76, - ROMANIAN=77, - RUSSIAN=78, - SERBIAN_LATIN=79, - SLOVAK=80, - SLOVENIAN=81, - SPANISH_MEXICAN=82, - SPANISH_MODERN=83, - THAI=84, - TURKISH=85, - UKRANIAN=86, + public enum TwLanguage : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + DANISH = 0, /* Danish */ + DUTCH = 1, /* Dutch */ + ENGLISH = 2, /* International English */ + FRENCH_CANADIAN = 3, /* French Canadian */ + FINNISH = 4, /* Finnish */ + FRENCH = 5, /* French */ + GERMAN = 6, /* German */ + ICELANDIC = 7, /* Icelandic */ + ITALIAN = 8, /* Italian */ + NORWEGIAN = 9, /* Norwegian */ + PORTUGUESE = 10, /* Portuguese */ + SPANISH = 11, /* Spanish */ + SWEDISH = 12, /* Swedish */ + ENGLISH_USA = 13, /* U.S. English */ + AFRIKAANS = 14, + ALBANIA = 15, + ARABIC = 16, + ARABIC_ALGERIA = 17, + ARABIC_BAHRAIN = 18, + ARABIC_EGYPT = 19, + ARABIC_IRAQ = 20, + ARABIC_JORDAN = 21, + ARABIC_KUWAIT = 22, + ARABIC_LEBANON = 23, + ARABIC_LIBYA = 24, + ARABIC_MOROCCO = 25, + ARABIC_OMAN = 26, + ARABIC_QATAR = 27, + ARABIC_SAUDIARABIA = 28, + ARABIC_SYRIA = 29, + ARABIC_TUNISIA = 30, + ARABIC_UAE = 31, /* United Arabic Emirates */ + ARABIC_YEMEN = 32, + BASQUE = 33, + BYELORUSSIAN = 34, + BULGARIAN = 35, + CATALAN = 36, + CHINESE = 37, + CHINESE_HONGKONG = 38, + CHINESE_PRC = 39, /* People's Republic of China */ + CHINESE_SINGAPORE = 40, + CHINESE_SIMPLIFIED = 41, + CHINESE_TAIWAN = 42, + CHINESE_TRADITIONAL = 43, + CROATIA = 44, + CZECH = 45, + DUTCH_BELGIAN = 46, + ENGLISH_AUSTRALIAN = 47, + ENGLISH_CANADIAN = 48, + ENGLISH_IRELAND = 49, + ENGLISH_NEWZEALAND = 50, + ENGLISH_SOUTHAFRICA = 51, + ENGLISH_UK = 52, + ESTONIAN = 53, + FAEROESE = 54, + FARSI = 55, + FRENCH_BELGIAN = 56, + FRENCH_LUXEMBOURG = 57, + FRENCH_SWISS = 58, + GERMAN_AUSTRIAN = 59, + GERMAN_LUXEMBOURG = 60, + GERMAN_LIECHTENSTEIN = 61, + GERMAN_SWISS = 62, + GREEK = 63, + HEBREW = 64, + HUNGARIAN = 65, + INDONESIAN = 66, + ITALIAN_SWISS = 67, + JAPANESE = 68, + KOREAN = 69, + KOREAN_JOHAB = 70, + LATVIAN = 71, + LITHUANIAN = 72, + NORWEGIAN_BOKMAL = 73, + NORWEGIAN_NYNORSK = 74, + POLISH = 75, + PORTUGUESE_BRAZIL = 76, + ROMANIAN = 77, + RUSSIAN = 78, + SERBIAN_LATIN = 79, + SLOVAK = 80, + SLOVENIAN = 81, + SPANISH_MEXICAN = 82, + SPANISH_MODERN = 83, + THAI = 84, + TURKISH = 85, + UKRANIAN = 86, /* More stuff added for 1.8 */ - ASSAMESE=87, - BENGALI=88, - BIHARI=89, - BODO=90, - DOGRI=91, - GUJARATI=92, - HARYANVI=93, - HINDI=94, - KANNADA=95, - KASHMIRI=96, - MALAYALAM=97, - MARATHI=98, - MARWARI=99, - MEGHALAYAN=100, - MIZO=101, - NAGA=102, - ORISSI=103, - PUNJABI=104, - PUSHTU=105, - SERBIAN_CYRILLIC=106, - SIKKIMI=107, - SWEDISH_FINLAND=108, - TAMIL=109, - TELUGU=110, - TRIPURI=111, - URDU=112, - VIETNAMESE=113 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + ASSAMESE = 87, + BENGALI = 88, + BIHARI = 89, + BODO = 90, + DOGRI = 91, + GUJARATI = 92, + HARYANVI = 93, + HINDI = 94, + KANNADA = 95, + KASHMIRI = 96, + MALAYALAM = 97, + MARATHI = 98, + MARWARI = 99, + MEGHALAYAN = 100, + MIZO = 101, + NAGA = 102, + ORISSI = 103, + PUNJABI = 104, + PUSHTU = 105, + SERBIAN_CYRILLIC = 106, + SIKKIMI = 107, + SWEDISH_FINLAND = 108, + TAMIL = 109, + TELUGU = 110, + TRIPURI = 111, + URDU = 112, + VIETNAMESE = 113 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Country Constantsz /// - public enum TwCountry:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - AFGHANISTAN=1001, - ALGERIA=213, - AMERICANSAMOA=684, - ANDORRA=033, - ANGOLA=1002, - ANGUILLA=8090, - ANTIGUA=8091, - ARGENTINA=54, - ARUBA=297, - ASCENSIONI=247, - AUSTRALIA=61, - AUSTRIA=43, - BAHAMAS=8092, - BAHRAIN=973, - BANGLADESH=880, - BARBADOS=8093, - BELGIUM=32, - BELIZE=501, - BENIN=229, - BERMUDA=8094, - BHUTAN=1003, - BOLIVIA=591, - BOTSWANA=267, - BRITAIN=6, - BRITVIRGINIS=8095, - BRAZIL=55, - BRUNEI=673, - BULGARIA=359, - BURKINAFASO=1004, - BURMA=1005, - BURUNDI=1006, - CAMAROON=237, - CANADA=2, - CAPEVERDEIS=238, - CAYMANIS=8096, - CENTRALAFREP=1007, - CHAD=1008, - CHILE=56, - CHINA=86, - CHRISTMASIS=1009, - COCOSIS=1009, - COLOMBIA=57, - COMOROS=1010, - CONGO=1011, - COOKIS=1012, - COSTARICA=506, - CUBA=005, - CYPRUS=357, - CZECHOSLOVAKIA=42, - DENMARK=45, - DJIBOUTI=1013, - DOMINICA=8097, - DOMINCANREP=8098, - EASTERIS=1014, - ECUADOR=593, - EGYPT=20, - ELSALVADOR=503, - EQGUINEA=1015, - ETHIOPIA=251, - FALKLANDIS=1016, - FAEROEIS=298, - FIJIISLANDS=679, - FINLAND=358, - FRANCE=33, - FRANTILLES=596, - FRGUIANA=594, - FRPOLYNEISA=689, - FUTANAIS=1043, - GABON=241, - GAMBIA=220, - GERMANY=49, - GHANA=233, - GIBRALTER=350, - GREECE=30, - GREENLAND=299, - GRENADA=8099, - GRENEDINES=8015, - GUADELOUPE=590, - GUAM=671, - GUANTANAMOBAY=5399, - GUATEMALA=502, - GUINEA=224, - GUINEABISSAU=1017, - GUYANA=592, - HAITI=509, - HONDURAS=504, - HONGKONG=852, - HUNGARY=36, - ICELAND=354, - INDIA=91, - INDONESIA=62, - IRAN=98, - IRAQ=964, - IRELAND=353, - ISRAEL=972, - ITALY=39, - IVORYCOAST=225, - JAMAICA=8010, - JAPAN=81, - JORDAN=962, - KENYA=254, - KIRIBATI=1018, - KOREA=82, - KUWAIT=965, - LAOS=1019, - LEBANON=1020, - LIBERIA=231, - LIBYA=218, - LIECHTENSTEIN=41, - LUXENBOURG=352, - MACAO=853, - MADAGASCAR=1021, - MALAWI=265, - MALAYSIA=60, - MALDIVES=960, - MALI=1022, - MALTA=356, - MARSHALLIS=692, - MAURITANIA=1023, - MAURITIUS=230, - MEXICO=3, - MICRONESIA=691, - MIQUELON=508, - MONACO=33, - MONGOLIA=1024, - MONTSERRAT=8011, - MOROCCO=212, - MOZAMBIQUE=1025, - NAMIBIA=264, - NAURU=1026, - NEPAL=977, - NETHERLANDS=31, - NETHANTILLES=599, - NEVIS=8012, - NEWCALEDONIA=687, - NEWZEALAND=64, - NICARAGUA=505, - NIGER=227, - NIGERIA=234, - NIUE=1027, - NORFOLKI=1028, - NORWAY=47, - OMAN=968, - PAKISTAN=92, - PALAU=1029, - PANAMA=507, - PARAGUAY=595, - PERU=51, - PHILLIPPINES=63, - PITCAIRNIS=1030, - PNEWGUINEA=675, - POLAND=48, - PORTUGAL=351, - QATAR=974, - REUNIONI=1031, - ROMANIA=40, - RWANDA=250, - SAIPAN=670, - SANMARINO=39, - SAOTOME=1033, - SAUDIARABIA=966, - SENEGAL=221, - SEYCHELLESIS=1034, - SIERRALEONE=1035, - SINGAPORE=65, - SOLOMONIS=1036, - SOMALI=1037, - SOUTHAFRICA=27, - SPAIN=34, - SRILANKA=94, - STHELENA=1032, - STKITTS=8013, - STLUCIA=8014, - STPIERRE=508, - STVINCENT=8015, - SUDAN=1038, - SURINAME=597, - SWAZILAND=268, - SWEDEN=46, - SWITZERLAND=41, - SYRIA=1039, - TAIWAN=886, - TANZANIA=255, - THAILAND=66, - TOBAGO=8016, - TOGO=228, - TONGAIS=676, - TRINIDAD=8016, - TUNISIA=216, - TURKEY=90, - TURKSCAICOS=8017, - TUVALU=1040, - UGANDA=256, - USSR=7, - UAEMIRATES=971, - UNITEDKINGDOM=44, - USA=1, - URUGUAY=598, - VANUATU=1041, - VATICANCITY=39, - VENEZUELA=58, - WAKE=1042, - WALLISIS=1043, - WESTERNSAHARA=1044, - WESTERNSAMOA=1045, - YEMEN=1046, - YUGOSLAVIA=38, - ZAIRE=243, - ZAMBIA=260, - ZIMBABWE=263, + public enum TwCountry : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + AFGHANISTAN = 1001, + ALGERIA = 213, + AMERICANSAMOA = 684, + ANDORRA = 033, + ANGOLA = 1002, + ANGUILLA = 8090, + ANTIGUA = 8091, + ARGENTINA = 54, + ARUBA = 297, + ASCENSIONI = 247, + AUSTRALIA = 61, + AUSTRIA = 43, + BAHAMAS = 8092, + BAHRAIN = 973, + BANGLADESH = 880, + BARBADOS = 8093, + BELGIUM = 32, + BELIZE = 501, + BENIN = 229, + BERMUDA = 8094, + BHUTAN = 1003, + BOLIVIA = 591, + BOTSWANA = 267, + BRITAIN = 6, + BRITVIRGINIS = 8095, + BRAZIL = 55, + BRUNEI = 673, + BULGARIA = 359, + BURKINAFASO = 1004, + BURMA = 1005, + BURUNDI = 1006, + CAMAROON = 237, + CANADA = 2, + CAPEVERDEIS = 238, + CAYMANIS = 8096, + CENTRALAFREP = 1007, + CHAD = 1008, + CHILE = 56, + CHINA = 86, + CHRISTMASIS = 1009, + COCOSIS = 1009, + COLOMBIA = 57, + COMOROS = 1010, + CONGO = 1011, + COOKIS = 1012, + COSTARICA = 506, + CUBA = 005, + CYPRUS = 357, + CZECHOSLOVAKIA = 42, + DENMARK = 45, + DJIBOUTI = 1013, + DOMINICA = 8097, + DOMINCANREP = 8098, + EASTERIS = 1014, + ECUADOR = 593, + EGYPT = 20, + ELSALVADOR = 503, + EQGUINEA = 1015, + ETHIOPIA = 251, + FALKLANDIS = 1016, + FAEROEIS = 298, + FIJIISLANDS = 679, + FINLAND = 358, + FRANCE = 33, + FRANTILLES = 596, + FRGUIANA = 594, + FRPOLYNEISA = 689, + FUTANAIS = 1043, + GABON = 241, + GAMBIA = 220, + GERMANY = 49, + GHANA = 233, + GIBRALTER = 350, + GREECE = 30, + GREENLAND = 299, + GRENADA = 8099, + GRENEDINES = 8015, + GUADELOUPE = 590, + GUAM = 671, + GUANTANAMOBAY = 5399, + GUATEMALA = 502, + GUINEA = 224, + GUINEABISSAU = 1017, + GUYANA = 592, + HAITI = 509, + HONDURAS = 504, + HONGKONG = 852, + HUNGARY = 36, + ICELAND = 354, + INDIA = 91, + INDONESIA = 62, + IRAN = 98, + IRAQ = 964, + IRELAND = 353, + ISRAEL = 972, + ITALY = 39, + IVORYCOAST = 225, + JAMAICA = 8010, + JAPAN = 81, + JORDAN = 962, + KENYA = 254, + KIRIBATI = 1018, + KOREA = 82, + KUWAIT = 965, + LAOS = 1019, + LEBANON = 1020, + LIBERIA = 231, + LIBYA = 218, + LIECHTENSTEIN = 41, + LUXENBOURG = 352, + MACAO = 853, + MADAGASCAR = 1021, + MALAWI = 265, + MALAYSIA = 60, + MALDIVES = 960, + MALI = 1022, + MALTA = 356, + MARSHALLIS = 692, + MAURITANIA = 1023, + MAURITIUS = 230, + MEXICO = 3, + MICRONESIA = 691, + MIQUELON = 508, + MONACO = 33, + MONGOLIA = 1024, + MONTSERRAT = 8011, + MOROCCO = 212, + MOZAMBIQUE = 1025, + NAMIBIA = 264, + NAURU = 1026, + NEPAL = 977, + NETHERLANDS = 31, + NETHANTILLES = 599, + NEVIS = 8012, + NEWCALEDONIA = 687, + NEWZEALAND = 64, + NICARAGUA = 505, + NIGER = 227, + NIGERIA = 234, + NIUE = 1027, + NORFOLKI = 1028, + NORWAY = 47, + OMAN = 968, + PAKISTAN = 92, + PALAU = 1029, + PANAMA = 507, + PARAGUAY = 595, + PERU = 51, + PHILLIPPINES = 63, + PITCAIRNIS = 1030, + PNEWGUINEA = 675, + POLAND = 48, + PORTUGAL = 351, + QATAR = 974, + REUNIONI = 1031, + ROMANIA = 40, + RWANDA = 250, + SAIPAN = 670, + SANMARINO = 39, + SAOTOME = 1033, + SAUDIARABIA = 966, + SENEGAL = 221, + SEYCHELLESIS = 1034, + SIERRALEONE = 1035, + SINGAPORE = 65, + SOLOMONIS = 1036, + SOMALI = 1037, + SOUTHAFRICA = 27, + SPAIN = 34, + SRILANKA = 94, + STHELENA = 1032, + STKITTS = 8013, + STLUCIA = 8014, + STPIERRE = 508, + STVINCENT = 8015, + SUDAN = 1038, + SURINAME = 597, + SWAZILAND = 268, + SWEDEN = 46, + SWITZERLAND = 41, + SYRIA = 1039, + TAIWAN = 886, + TANZANIA = 255, + THAILAND = 66, + TOBAGO = 8016, + TOGO = 228, + TONGAIS = 676, + TRINIDAD = 8016, + TUNISIA = 216, + TURKEY = 90, + TURKSCAICOS = 8017, + TUVALU = 1040, + UGANDA = 256, + USSR = 7, + UAEMIRATES = 971, + UNITEDKINGDOM = 44, + USA = 1, + URUGUAY = 598, + VANUATU = 1041, + VATICANCITY = 39, + VENEZUELA = 58, + WAKE = 1042, + WALLISIS = 1043, + WESTERNSAHARA = 1044, + WESTERNSAMOA = 1045, + YEMEN = 1046, + YUGOSLAVIA = 38, + ZAIRE = 243, + ZAMBIA = 260, + ZIMBABWE = 263, /* Added for 1.8 */ - ALBANIA=355, - ARMENIA=374, - AZERBAIJAN=994, - BELARUS=375, - BOSNIAHERZGO=387, - CAMBODIA=855, - CROATIA=385, - CZECHREPUBLIC=420, - DIEGOGARCIA=246, - ERITREA=291, - ESTONIA=372, - GEORGIA=995, - LATVIA=371, - LESOTHO=266, - LITHUANIA=370, - MACEDONIA=389, - MAYOTTEIS=269, - MOLDOVA=373, - MYANMAR=95, - NORTHKOREA=850, - PUERTORICO=787, - RUSSIA=7, - SERBIA=381, - SLOVAKIA=421, - SLOVENIA=386, - SOUTHKOREA=82, - UKRAINE=380, - USVIRGINIS=340, - VIETNAM=84 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + ALBANIA = 355, + ARMENIA = 374, + AZERBAIJAN = 994, + BELARUS = 375, + BOSNIAHERZGO = 387, + CAMBODIA = 855, + CROATIA = 385, + CZECHREPUBLIC = 420, + DIEGOGARCIA = 246, + ERITREA = 291, + ESTONIA = 372, + GEORGIA = 995, + LATVIA = 371, + LESOTHO = 266, + LITHUANIA = 370, + MACEDONIA = 389, + MAYOTTEIS = 269, + MOLDOVA = 373, + MYANMAR = 95, + NORTHKOREA = 850, + PUERTORICO = 787, + RUSSIA = 7, + SERBIA = 381, + SLOVAKIA = 421, + SLOVENIA = 386, + SOUTHKOREA = 82, + UKRAINE = 380, + USVIRGINIS = 340, + VIETNAM = 84 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Unit of measure /// - public enum TwUnits:ushort { //ICAP_UNITS values (UN_ means UNits) -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Inches=0, - Centimeters=1, - Picas=2, - Points=3, - Twips=4, - Pixels=5, - Millimeters=6 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwUnits : ushort + { //ICAP_UNITS values (UN_ means UNits) +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Inches = 0, + Centimeters = 1, + Picas = 2, + Points = 3, + Twips = 4, + Pixels = 5, + Millimeters = 6 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Pixel types /// - public enum TwPixelType:ushort { //ICAP_PIXELTYPE values (PT_ means Pixel Type) + public enum TwPixelType : ushort + { //ICAP_PIXELTYPE values (PT_ means Pixel Type) /// /// Black and white /// - BW=0, /* Black and White */ -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Gray=1, - RGB=2, - Palette=3, - CMY=4, - CMYK=5, - YUV=6, - YUVK=7, - CIEXYZ=8, - LAB=9, - SRGB=10, - SCRGB=11, - INFRARED=16 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + BW = 0, /* Black and White */ +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Gray = 1, + RGB = 2, + Palette = 3, + CMY = 4, + CMYK = 5, + YUV = 6, + YUVK = 7, + CIEXYZ = 8, + LAB = 9, + SRGB = 10, + SCRGB = 11, + INFRARED = 16 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Compression values /// - public enum TwCompression:ushort { //ICAP_COMPRESSION values (CP_ means ComPression ) -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - PackBits=1, + public enum TwCompression : ushort + { //ICAP_COMPRESSION values (CP_ means ComPression ) +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + PackBits = 1, /// /// Follows CCITT spec (no End Of Line) /// - Group31D=2, + Group31D = 2, /// /// Follows CCITT spec (has End Of Line) /// - Group31Deol=3, + Group31Deol = 3, /// /// Follows CCITT spec (use cap for K Factor) /// - Group32D=4, + Group32D = 4, /// /// Follows CCITT spec /// - Group4=5, + Group4 = 5, /// /// Use capability for more info /// - Jpeg=6, + Jpeg = 6, /// /// Must license from Unisys and IBM to use /// - Lzw=7, + Lzw = 7, /// /// For Bitonal images -- Added 1.7 KHL /// - Jbig=8, + Jbig = 8, /* Added 1.8 */ - Png=9, - Rle4=10, - Rle8=11, - BitFields=12, - Zip=13, - Jpeg2000=14 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + Png = 9, + Rle4 = 10, + Rle8 = 11, + BitFields = 12, + Zip = 13, + Jpeg2000 = 14 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Extended Image Info Attributes. /// - public enum TwEI:ushort { //TWEI_xxxx -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - BarCodeX=0x1200, - BarCodeY=0x1201, - BarCodeText=0x1202, - BarCodeType=0x1203, - DeshadeTop=0x1204, - DeshadeLeft=0x1205, - DeshadeHeight=0x1206, - DeshadeWidth=0x1207, - DeshadeSize=0x1208, - SpecklesRemoved=0x1209, - HorzLineXCoord=0x120A, - HorzLineYCoord=0x120B, - HorzLineLength=0x120C, - HorzLineThickness=0x120D, - VertLineXCoord=0x120E, - VertLinEYCoord=0x120F, - VertLineLength=0x1210, - VertLineThickness=0x1211, - PatchCode=0x1212, - EndOrSedText=0x1213, - FormConfidence=0x1214, - FormTemplateMatch=0x1215, - FormTemplatePageMatch=0x1216, - FormHorzDocOffset=0x1217, - FormVertDocOffset=0x1218, - BarCodeCount=0x1219, - BarCodeConfidence=0x121A, - BarCodeRotation=0x121B, - BarCodeTextLength=0x121C, - DeshadeCount=0x121D, - DeshadeBlackCountOld=0x121E, - DeshadeBlackCountNew=0x121F, - DeshadeBlackRLMin=0x1220, - DeshadeBlackRLMax=0x1221, - DeshadeWhiteCountOld=0x1222, - DeshadeWhiteCountNew=0x1223, - DeshadeWhiteRLMin=0x1224, - DeshadeWhiteRLAve=0x1225, - DeshadeWhiteRLMax=0x1226, - BlackSpecklesRemoved=0x1227, - WhiteSpecklesRemoved=0x1228, - HorzLineCount=0x1229, - VertLineCount=0x122A, - DeskewStatus=0x122B, - SkewOriginalAngle=0x122C, - SkewFinalAngle=0x122D, - SkewConfidence=0x122E, - SkewWindowX1=0x122F, - SkewWindowY1=0x1230, - SkewWindowX2=0x1231, - SkewWindowY2=0x1232, - SkewWindowX3=0x1233, - SkewWindowY3=0x1234, - SkewWindowX4=0x1235, - SkewWindowY4=0x1236, - BookName=0x1238, /* added 1.9 */ - ChapterNumber=0x1239, /* added 1.9 */ - DocumentNumber=0x123A, /* added 1.9 */ - PageNumber=0x123B, /* added 1.9 */ - Camera=0x123C, /* added 1.9 */ - FrameNumber=0x123D, /* added 1.9 */ - Frame=0x123E, /* added 1.9 */ - PixelFlavor=0x123F, /* added 1.9 */ - IccProFile=0x1240, /* added 1.91 */ - LastSegment=0x1241, /* added 1.91 */ - SegmentNumber=0x1242, /* added 1.91 */ - MagData=0x1243, /* added 2.0 */ - MagType=0x1244, /* added 2.0 */ - PageSide=0x1245, - FileSystemSource=0x1246, - ImageMerged=0x1247, - MagDataLength=0x1248, - PaperCount=0x1249, - PrinterText=0x124A -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwEI : ushort + { //TWEI_xxxx +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + BarCodeX = 0x1200, + BarCodeY = 0x1201, + BarCodeText = 0x1202, + BarCodeType = 0x1203, + DeshadeTop = 0x1204, + DeshadeLeft = 0x1205, + DeshadeHeight = 0x1206, + DeshadeWidth = 0x1207, + DeshadeSize = 0x1208, + SpecklesRemoved = 0x1209, + HorzLineXCoord = 0x120A, + HorzLineYCoord = 0x120B, + HorzLineLength = 0x120C, + HorzLineThickness = 0x120D, + VertLineXCoord = 0x120E, + VertLinEYCoord = 0x120F, + VertLineLength = 0x1210, + VertLineThickness = 0x1211, + PatchCode = 0x1212, + EndOrSedText = 0x1213, + FormConfidence = 0x1214, + FormTemplateMatch = 0x1215, + FormTemplatePageMatch = 0x1216, + FormHorzDocOffset = 0x1217, + FormVertDocOffset = 0x1218, + BarCodeCount = 0x1219, + BarCodeConfidence = 0x121A, + BarCodeRotation = 0x121B, + BarCodeTextLength = 0x121C, + DeshadeCount = 0x121D, + DeshadeBlackCountOld = 0x121E, + DeshadeBlackCountNew = 0x121F, + DeshadeBlackRLMin = 0x1220, + DeshadeBlackRLMax = 0x1221, + DeshadeWhiteCountOld = 0x1222, + DeshadeWhiteCountNew = 0x1223, + DeshadeWhiteRLMin = 0x1224, + DeshadeWhiteRLAve = 0x1225, + DeshadeWhiteRLMax = 0x1226, + BlackSpecklesRemoved = 0x1227, + WhiteSpecklesRemoved = 0x1228, + HorzLineCount = 0x1229, + VertLineCount = 0x122A, + DeskewStatus = 0x122B, + SkewOriginalAngle = 0x122C, + SkewFinalAngle = 0x122D, + SkewConfidence = 0x122E, + SkewWindowX1 = 0x122F, + SkewWindowY1 = 0x1230, + SkewWindowX2 = 0x1231, + SkewWindowY2 = 0x1232, + SkewWindowX3 = 0x1233, + SkewWindowY3 = 0x1234, + SkewWindowX4 = 0x1235, + SkewWindowY4 = 0x1236, + BookName = 0x1238, /* added 1.9 */ + ChapterNumber = 0x1239, /* added 1.9 */ + DocumentNumber = 0x123A, /* added 1.9 */ + PageNumber = 0x123B, /* added 1.9 */ + Camera = 0x123C, /* added 1.9 */ + FrameNumber = 0x123D, /* added 1.9 */ + Frame = 0x123E, /* added 1.9 */ + PixelFlavor = 0x123F, /* added 1.9 */ + IccProFile = 0x1240, /* added 1.91 */ + LastSegment = 0x1241, /* added 1.91 */ + SegmentNumber = 0x1242, /* added 1.91 */ + MagData = 0x1243, /* added 2.0 */ + MagType = 0x1244, /* added 2.0 */ + PageSide = 0x1245, + FileSystemSource = 0x1246, + ImageMerged = 0x1247, + MagDataLength = 0x1248, + PaperCount = 0x1249, + PrinterText = 0x124A, + TwainDirectMetadata = 0x124B // Metadata returned in TWAIN Direct JSON format +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_XFERMECH values (SX_ means Setup XFer) /// - public enum TwSX:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Native=0, - File=1, - Memory=2, - MemFile=4 /* added 1.91 */ -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwSX : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Native = 0, + File = 1, + Memory = 2, + MemFile = 4 /* added 1.91 */ +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Flags used in TW_MEMORY structure. /// [Flags] - internal enum TwMF:uint { - AppOwns=0x1, - DsmOwns=0x2, - DSOwns=0x4, - Pointer=0x8, - Handle=0x10 + internal enum TwMF : uint + { + AppOwns = 0x1, + DsmOwns = 0x2, + DSOwns = 0x4, + Pointer = 0x8, + Handle = 0x10 } /// /// ICAP_SUPPORTEDSIZES values (SS_ means Supported Sizes). /// - public enum TwSS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - A4Letter=1, - B5Letter=2, - USLetter=3, - USLegal=4, + public enum TwSS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + A4Letter = 1, + B5Letter = 2, + USLetter = 3, + USLegal = 4, /* Added 1.5 */ - A5=5, - B4=6, - B6=7, + A5 = 5, + B4 = 6, + B6 = 7, /* Added 1.7 */ - USLedger=9, - USExecutive=10, - A3=11, - B3=12, - A6=13, - C4=14, - C5=15, - C6=16, + USLedger = 9, + USExecutive = 10, + A3 = 11, + B3 = 12, + A6 = 13, + C4 = 14, + C5 = 15, + C6 = 16, /* Added 1.8 */ - _4A0=17, - _2A0=18, - A0=19, - A1=20, - A2=21, - A4=A4Letter, - A7=22, - A8=23, - A9=24, - A10=25, - ISOB0=26, - ISOB1=27, - ISOB2=28, - ISOB3=B3, - ISOB4=B4, - ISOB5=29, - ISOB6=B6, - ISOB7=30, - ISOB8=31, - ISOB9=32, - ISOB10=33, - JISB0=34, - JISB1=35, - JISB2=36, - JISB3=37, - JISB4=38, - JISB5=B5Letter, - JISB6=39, - JISB7=40, - JISB8=41, - JISB9=42, - JISB10=43, - C0=44, - C1=45, - C2=46, - C3=47, - C7=48, - C8=49, - C9=50, - C10=51, - USStatement=52, - BusinessCard=53 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + _4A0 = 17, + _2A0 = 18, + A0 = 19, + A1 = 20, + A2 = 21, + A4 = A4Letter, + A7 = 22, + A8 = 23, + A9 = 24, + A10 = 25, + ISOB0 = 26, + ISOB1 = 27, + ISOB2 = 28, + ISOB3 = B3, + ISOB4 = B4, + ISOB5 = 29, + ISOB6 = B6, + ISOB7 = 30, + ISOB8 = 31, + ISOB9 = 32, + ISOB10 = 33, + JISB0 = 34, + JISB1 = 35, + JISB2 = 36, + JISB3 = 37, + JISB4 = 38, + JISB5 = B5Letter, + JISB6 = 39, + JISB7 = 40, + JISB8 = 41, + JISB9 = 42, + JISB10 = 43, + C0 = 44, + C1 = 45, + C2 = 46, + C3 = 47, + C7 = 48, + C8 = 49, + C9 = 50, + C10 = 51, + USStatement = 52, + BusinessCard = 53 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_IMAGEFILEFORMAT values (FF_means File Format). /// - public enum TwFF:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFF : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена /// /// Tagged Image File Format. /// - Tiff=0, + Tiff = 0, /// /// Macintosh PICT. /// - Pict=1, + Pict = 1, /// /// Windows Bitmap. /// - Bmp=2, + Bmp = 2, /// /// X-Windows Bitmap. /// - Xbm=3, + Xbm = 3, /// /// Jpeg File Interchange Format. /// - Jfif=4, + Jfif = 4, /// /// Flash Pix. /// - Fpx=5, + Fpx = 5, /// /// Multi-page tiff file. /// - TiffMulti=6, + TiffMulti = 6, - Png=7, - Spiff=8, - Exif=9, + Png = 7, + Spiff = 8, + Exif = 9, /// /// 1.91 NB: this is not PDF/A /// - Pdf=10, + Pdf = 10, /// /// 1.91 /// - Jp2=11, + Jp2 = 11, /// /// 1.91 /// - Jpx=13, + Jpx = 13, /// /// 1.91 /// - Dejavu=14, + Dejavu = 14, /// /// 2.0 Adobe PDF/A, Version 1. /// - PdfA=15, + PdfA = 15, /// /// 2.1 Adobe PDF/A, Version. /// - PdfA2=16 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + PdfA2 = 16, + + /// + /// PDF/raster. + /// + PdfRaster = 17 // Added support for PDF/raster +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// Palette types for TW_PALETTE8. /// - public enum TwPA:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - RGB=0, - Gray=1, - CMY=2 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwPA : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + RGB = 0, + Gray = 1, + CMY = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// CAP_DEVICEEVENT values (DE_ means device event). /// - public enum TwDE:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - CustomEvents=0x8000, - CheckAutomaticCapture=0, - CheckBattery=1, - CheckDeviceOnline=2, - CheckFlash=3, - CheckPowerSupply=4, - CheckResolution=5, - DeviceAdded=6, - DeviceOffline=7, - DeviceReady=8, - DeviceRemoved=9, - ImageCaptured=10, - ImageDeleted=11, - PaperDoubleFeed=12, - PaperJam=13, - LampFailure=14, - PowerSave=15, - PowerSaveNotify=16 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwDE : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + CustomEvents = 0x8000, + CheckAutomaticCapture = 0, + CheckBattery = 1, + CheckDeviceOnline = 2, + CheckFlash = 3, + CheckPowerSupply = 4, + CheckResolution = 5, + DeviceAdded = 6, + DeviceOffline = 7, + DeviceReady = 8, + DeviceRemoved = 9, + ImageCaptured = 10, + ImageDeleted = 11, + PaperDoubleFeed = 12, + PaperJam = 13, + LampFailure = 14, + PowerSave = 15, + PowerSaveNotify = 16 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_DUPLEX values. /// - public enum TwDX:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, // TWDX_NONE - OnePassDuplex=1, // TWDX_1PASSDUPLEX - TwoPassDuplex=2 // TWDX_2PASSDUPLEX -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwDX : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, // TWDX_NONE + OnePassDuplex = 1, // TWDX_1PASSDUPLEX + TwoPassDuplex = 2 // TWDX_2PASSDUPLEX +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_AUTODISCARDBLANKPAGES values. /// - public enum TwBP:int { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Disable=-2, // TWBP_DISABLE - Auto=-1 // TWBP_AUTO -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwBP : int + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Disable = -2, // TWBP_DISABLE + Auto = -1 // TWBP_AUTO +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_AUTOSIZE values. /// - public enum TwAS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Auto=1, - Current=2 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwAS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Auto = 1, + Current = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_FLIPROTATION values (FR_ means flip rotation). /// - public enum TwFR:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Book=0, - Fanfold=1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFR : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Book = 0, + Fanfold = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_IMAGEMERGE values. /// - public enum TwIM:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - FrontOnTop=1, - FrontOnBottom=2, - FrontOnLeft=3, - FrontOnRight=4 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwIM : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + FrontOnTop = 1, + FrontOnBottom = 2, + FrontOnLeft = 3, + FrontOnRight = 4 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_CAMERASIDE and TWEI_PAGESIDE values. /// - public enum TwCS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Both=0, - Top=1, - Bottom=2 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwCS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Both = 0, + Top = 1, + Bottom = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// CAP_CLEARBUFFERS values. /// - public enum TwCB:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Auto=0, - Clear=1, - NoClear=2 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwCB : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Auto = 0, + Clear = 1, + NoClear = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_SUPPORTEDBARCODETYPES and TWEI_BARCODETYPE values. /// - public enum TwBT:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Code3Of9=0, - Code2Of5Interleaved=1, - Code2Of5NonInterleaved=2, - Code93=3, - Code128=4, - Ucc128=5, - CodaBar=6, - Upca=7, - Upce=8, - Ean8=9, - Ean13=10, - PostNet=11, - Pdf417=12, - Code2Of5Industrial=13, - Code2Of5Matrix=14, - Code2Of5DataLogic=15, - Code2Of5Iata=16, - Code3Of9FullAscii=17, - CodaBarWithStartStop=18, - MaxiCode=19, - QRCode=20 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwBT : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Code3Of9 = 0, + Code2Of5Interleaved = 1, + Code2Of5NonInterleaved = 2, + Code93 = 3, + Code128 = 4, + Ucc128 = 5, + CodaBar = 6, + Upca = 7, + Upce = 8, + Ean8 = 9, + Ean13 = 10, + PostNet = 11, + Pdf417 = 12, + Code2Of5Industrial = 13, + Code2Of5Matrix = 14, + Code2Of5DataLogic = 15, + Code2Of5Iata = 16, + Code3Of9FullAscii = 17, + CodaBarWithStartStop = 18, + MaxiCode = 19, + QRCode = 20 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_BARCODESEARCHMODE values. /// - public enum TwBD:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Horz=0, - Vert=1, - HorzVert=2, - VertHorz=3 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwBD : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Horz = 0, + Vert = 1, + HorzVert = 2, + VertHorz = 3 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_FILTER values. /// - public enum TwFT:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Red=0, - Green=1, - Blue=2, - None=3, - White=4, - Cyan=5, - Magenta=6, - Yellow=7, - Black=8 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFT : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Red = 0, + Green = 1, + Blue = 2, + None = 3, + White = 4, + Cyan = 5, + Magenta = 6, + Yellow = 7, + Black = 8 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_ICCPROFILE values. /// - public enum TwIC:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Link=1, - Embed=2 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwIC : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Link = 1, + Embed = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_PLANARCHUNKY values. /// - public enum TwPC:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Chunky=0, - Planar=1 - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwPC : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Chunky = 0, + Planar = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_BITORDER values. /// - public enum TwBO:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - LsbFirst=0, - MsbFirst=1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwBO : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + LsbFirst = 0, + MsbFirst = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_JPEGQUALITY values. /// - public enum TwJQ:short { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Unknown=-4, - Low=-3, - Medium=-2, - High=-1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwJQ : short + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Unknown = -4, + Low = -3, + Medium = -2, + High = -1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_JPEGSUBSAMPLING values. /// - public enum TwJS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - _444Ycbcr=0, - _444Rgb=1, - _422=2, - _421=3, - _411=4, - _420=5, - _410=6, - _311=7 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwJS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + _444Ycbcr = 0, + _444Rgb = 1, + _422 = 2, + _421 = 3, + _411 = 4, + _420 = 5, + _410 = 6, + _311 = 7 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_PIXELFLAVOR values. /// - public enum TwPF:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Chocolate=0, - Vanilla=1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwPF : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Chocolate = 0, + Vanilla = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_FLASHUSED2 values. /// - public enum TwFL:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Off=1, - On=2, - Auto=3, - RedEye=4 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFL : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Off = 1, + On = 2, + Auto = 3, + RedEye = 4 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_IMAGEFILTER values. /// - public enum TwIF:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Auto=1, - LowPass=2, - BandPass=3, - HighPass=4, - Text=BandPass, - FineLine=HighPass - #pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwIF : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Auto = 1, + LowPass = 2, + BandPass = 3, + HighPass = 4, + Text = BandPass, + FineLine = HighPass +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_LIGHTPATH values. /// - public enum TwLP:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Reflective=0, - Transmissive=1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - } + public enum TwLP : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Reflective = 0, + Transmissive = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + } /// /// ICAP_LIGHTSOURCE values. /// - public enum TwLS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Red=0, - Green=1, - Blue=2, - None=3, - White=4, - UV=5, - IR=6 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwLS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Red = 0, + Green = 1, + Blue = 2, + None = 3, + White = 4, + UV = 5, + IR = 6 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_NOISEFILTER values. /// - public enum TwNF:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Auto=1, - LonePixel=2, - MajorityRule=3 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwNF : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Auto = 1, + LonePixel = 2, + MajorityRule = 3 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_OVERSCAN values. /// - public enum TwOV:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Auto=1, - TopBottom=2, - LeftRight=3, - All=4 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwOV : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Auto = 1, + TopBottom = 2, + LeftRight = 3, + All = 4 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_DOUBLEFEEDDETECTION. /// - public enum TwDF:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Ultrasonic=0, - ByLength=1, - Infrared=2 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwDF : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Ultrasonic = 0, + ByLength = 1, + Infrared = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_DOUBLEFEEDDETECTIONSENSITIVITY. /// - public enum TwUS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Low=0, - Medium=1, - High=2 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwUS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Low = 0, + Medium = 1, + High = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_DOUBLEFEEDDETECTIONRESPONSE. /// - public enum TwDP:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Stop=0, - StopAndWait=1, - Sound=2, - DoNotImprint=3 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwDP : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Stop = 0, + StopAndWait = 1, + Sound = 2, + DoNotImprint = 3 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_PRINTER values. /// - public enum TwPR:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - ImprinterTopBefore=0, - ImprinterTopAfter=1, - ImprinterBottomBefore=2, - ImprinterBottomAfter=3, - EndorserTopBefore=4, - EndorserTopAfter=5, - EndorserBottomBefore=6, - EndorserBottomAfter=7 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwPR : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + ImprinterTopBefore = 0, + ImprinterTopAfter = 1, + ImprinterBottomBefore = 2, + ImprinterBottomAfter = 3, + EndorserTopBefore = 4, + EndorserTopAfter = 5, + EndorserBottomBefore = 6, + EndorserBottomAfter = 7 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_PRINTERMODE values. /// - public enum TwPM:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - SingleString=0, - MultiString=1, - CompoundString=2 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwPM : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + SingleString = 0, + MultiString = 1, + CompoundString = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_ORIENTATION values. /// - public enum TwOR:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Rot0=0, - Rot90=1, - Rot180=2, - Rot270=3, - Portrait=Rot0, - Landscape=Rot270, - Auto=4, - AutoText=5, - AutoPicture=6 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwOR : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Rot0 = 0, + Rot90 = 1, + Rot180 = 2, + Rot270 = 3, + Portrait = Rot0, + Landscape = Rot270, + Auto = 4, + AutoText = 5, + AutoPicture = 6 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_BITDEPTHREDUCTION values. /// - public enum TwBR:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Threshold=0, - Halftone=1, - CustHalftone=2, - Diffusion=3, - DynamicThreshold=4 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwBR : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Threshold = 0, + Halftone = 1, + CustHalftone = 2, + Diffusion = 3, + DynamicThreshold = 4 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_SEGMENTED values. /// - public enum TwSG:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Auto=1, - Manual=2 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwSG : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Auto = 1, + Manual = 2 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_FEEDERALIGNMENT values. /// - public enum TwFA:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Left=1, - Center=2, - Right=3 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFA : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Left = 1, + Center = 2, + Right = 3 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_FEEDERORDER values. /// - public enum TwFO:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - FirstPageFirst=0, - LastPageFirst=1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFO : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + FirstPageFirst = 0, + LastPageFirst = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_FEEDERPOCKET values. /// - public enum TwFP:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - PocketError=0, - Pocket1=1, - Pocket2=2, - Pocket3=3, - Pocket4=4, - Pocket5=5, - Pocket6=6, - Pocket7=7, - Pocket8=8, - Pocket9=9, - Pocket10=10, - Pocket11=11, - Pocket12=12, - Pocket13=13, - Pocket14=14, - Pocket15=15, - Pocket16=16 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFP : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + PocketError = 0, + Pocket1 = 1, + Pocket2 = 2, + Pocket3 = 3, + Pocket4 = 4, + Pocket5 = 5, + Pocket6 = 6, + Pocket7 = 7, + Pocket8 = 8, + Pocket9 = 9, + Pocket10 = 10, + Pocket11 = 11, + Pocket12 = 12, + Pocket13 = 13, + Pocket14 = 14, + Pocket15 = 15, + Pocket16 = 16 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_PAPERHANDLING values. /// - public enum TwPH:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Normal=0, - Fragile=1, - Thick=2, - Trifold=3, - Photograph=4 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwPH : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Normal = 0, + Fragile = 1, + Thick = 2, + Trifold = 3, + Photograph = 4 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// ICAP_FEEDERTYPE values. /// - public enum TwFE:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - General=0, - Photo=1, -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwFE : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + General = 0, + Photo = 1, +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// TWEI_PATCHCODE values. /// - public enum TwPch:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Patch1=0, - Patch2=1, - Patch3=2, - Patch4=3, - Patch6=4, - PatchT=5 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwPch : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Patch1 = 0, + Patch2 = 1, + Patch3 = 2, + Patch4 = 3, + Patch6 = 4, + PatchT = 5 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_BATTERYMINUTES values. /// - public enum TwBM1:int { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Infinite=-2, - CannotReport=-1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwBM1 : int + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Infinite = -2, + CannotReport = -1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_BATTERYPERCENTAGE values. /// - public enum TwBM2:short { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Infinite=-2, - CannotReport=-1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwBM2 : short + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Infinite = -2, + CannotReport = -1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_POWERSUPPLY values. /// - public enum TwPS:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - External=0, - Battery=1 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwPS : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + External = 0, + Battery = 1 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_JOBCONTROL values. /// - public enum TwJC:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - None=0, - Jsic=1, - Jsis=2, - Jsxc=3, - Jsxs=4 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwJC : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + None = 0, + Jsic = 1, + Jsis = 2, + Jsxc = 3, + Jsxs = 4 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_INDICATORSMODE values. /// - public enum TwCI:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Info=0, - Warning=1, - Error=2, - WarmUp=3 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwCI : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Info = 0, + Warning = 1, + Error = 2, + WarmUp = 3 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } /// /// CAP_ALARMS values. /// - public enum TwAL:ushort { -#pragma warning disable CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена - Alarm=0, - FeederError=1, - FeederWarning=2, - BarCode=3, - DoubleFeed=4, - Jam=5, - PatchCode=6, - Power=7, - Skew=8 -#pragma warning restore CS1591 // Отсутствует комментарий XML для открытого видимого типа или члена + public enum TwAL : ushort + { +#pragma warning disable CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена + Alarm = 0, + FeederError = 1, + FeederWarning = 2, + BarCode = 3, + DoubleFeed = 4, + Jam = 5, + PatchCode = 6, + Power = 7, + Skew = 8 +#pragma warning restore CS1591 // Missing XML comment for public visible type or member / Отсутствует комментарий XML для открытого видимого типа или члена } #endregion @@ -2340,151 +2446,187 @@ public enum TwAL:ushort { #region Type Definitions /// - /// Строка фиксированной длинны 32 символа. + /// A string of fixed length 32 characters. + /// Строка фиксированной длинны 32 символа. /// [DebuggerDisplay("{Value}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal sealed class TwStr32 { + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal sealed class TwStr32 + { - [MarshalAs(UnmanagedType.ByValTStr,SizeConst=34)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 34)] public string Value; - public override string ToString() { + public override string ToString() + { return this.Value; } - public static implicit operator string(TwStr32 value) { - return value!=null?value.Value:null; + public static implicit operator string(TwStr32 value) + { + return value != null ? value.Value : null; } - public static implicit operator TwStr32(string value) { - return new TwStr32 { - Value=value + public static implicit operator TwStr32(string value) + { + return new TwStr32 + { + Value = value }; } } /// - /// Строка фиксированной длинны 64 символа. + /// A fixed-length string of 64 characters. + /// Строка фиксированной длинны 64 символа. /// [DebuggerDisplay("{Value}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal sealed class TwStr64 { + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal sealed class TwStr64 + { - [MarshalAs(UnmanagedType.ByValTStr,SizeConst=66)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 66)] public string Value; - public override string ToString() { + public override string ToString() + { return this.Value; } - public static implicit operator string(TwStr64 value) { - return value!=null?value.Value:null; + public static implicit operator string(TwStr64 value) + { + return value != null ? value.Value : null; } - public static implicit operator TwStr64(string value) { - return new TwStr64 { - Value=value + public static implicit operator TwStr64(string value) + { + return new TwStr64 + { + Value = value }; } } /// - /// Строка фиксированной длинны 128 символов. + /// A string of fixed length 128 characters. + /// Строка фиксированной длинны 128 символов. /// [DebuggerDisplay("{Value}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal sealed class TwStr128 { + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal sealed class TwStr128 + { - [MarshalAs(UnmanagedType.ByValTStr,SizeConst=130)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 130)] public string Value; - public override string ToString() { + public override string ToString() + { return this.Value; } - public static implicit operator string(TwStr128 value) { - return value!=null?value.Value:null; + public static implicit operator string(TwStr128 value) + { + return value != null ? value.Value : null; } - public static implicit operator TwStr128(string value) { - return new TwStr128 { - Value=value + public static implicit operator TwStr128(string value) + { + return new TwStr128 + { + Value = value }; } } /// - /// Строка фиксированной длинны 255 символов. + /// A string of fixed length 255 characters. + /// Строка фиксированной длинны 255 символов. /// [DebuggerDisplay("{Value}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal sealed class TwStr255 { + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal sealed class TwStr255 + { - [MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string Value; - public override string ToString() { + public override string ToString() + { return this.Value; } - public static implicit operator string(TwStr255 value) { - return value!=null?value.Value:null; + public static implicit operator string(TwStr255 value) + { + return value != null ? value.Value : null; } - public static implicit operator TwStr255(string value) { - return new TwStr255 { - Value=value + public static implicit operator TwStr255(string value) + { + return new TwStr255 + { + Value = value }; } } /// - /// Строка юникода фиксированной длинны 512 символов. + /// A Unicode string of fixed length 512 characters. + /// Строка юникода фиксированной длинны 512 символов. /// [DebuggerDisplay("{Value}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Unicode)] - internal sealed class TwUni512 { + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Unicode)] + internal sealed class TwUni512 + { - [MarshalAs(UnmanagedType.ByValTStr,SizeConst=512)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)] public string Value; - public override string ToString() { + public override string ToString() + { return this.Value; } - public static implicit operator string(TwUni512 value) { - return value!=null?value.Value:null; + public static implicit operator string(TwUni512 value) + { + return value != null ? value.Value : null; } - public static implicit operator TwUni512(string value) { - return new TwUni512 { - Value=value + public static implicit operator TwUni512(string value) + { + return new TwUni512 + { + Value = value }; } } /// - /// Строка фиксированной длинны 1024 символов. + /// A fixed-length string of 1024 characters. + /// Строка фиксированной длинны 1024 символов. /// [DebuggerDisplay("{Value}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal sealed class TwStr1024 { + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal sealed class TwStr1024 + { - [MarshalAs(UnmanagedType.ByValTStr,SizeConst=1026)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1026)] public string Value; - public override string ToString() { + public override string ToString() + { return this.Value; } - public static implicit operator string(TwStr1024 value) { - return value!=null?value.Value:null; + public static implicit operator string(TwStr1024 value) + { + return value != null ? value.Value : null; } - public static implicit operator TwStr1024(string value) { - return new TwStr1024 { - Value=value + public static implicit operator TwStr1024(string value) + { + return new TwStr1024 + { + Value = value }; } } @@ -2493,22 +2635,27 @@ public static implicit operator TwStr1024(string value) { /// Boolean value. /// [DebuggerDisplay("{ToBool()}")] - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal struct TwBool { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal struct TwBool + { public ushort Value; - private bool ToBool() { - return this.Value!=0; + private bool ToBool() + { + return this.Value != 0; } - public static implicit operator bool(TwBool value) { + public static implicit operator bool(TwBool value) + { return value.ToBool(); } - public static implicit operator TwBool(bool value) { - return new TwBool { - Value=(ushort)(value?1:0) + public static implicit operator TwBool(bool value) + { + return new TwBool + { + Value = (ushort)(value ? 1 : 0) }; } } @@ -2517,68 +2664,83 @@ public static implicit operator TwBool(bool value) { /// Fixed point structure type. /// [DebuggerDisplay("{ToFloat()}")] - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal struct TwFix32 { // TW_FIX32 + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal struct TwFix32 + { // TW_FIX32 /// - /// Целая часть. + /// The whole part. + /// Целая часть. /// public short Whole; /// - /// Дробная часть. + /// Fractional part. + /// Дробная часть. /// public ushort Frac; /// - /// Приводит тип к числу с плавающей запятой. + /// Coerces the type to a floating point number. + /// Приводит тип к числу с плавающей запятой. /// - /// Число с плавающей точкой. - private float ToFloat() { - return (float)this.Whole+((float)this.Frac/65536.0f); + /// Floating point number.Число с плавающей точкой. + private float ToFloat() + { + return (float)this.Whole + ((float)this.Frac / 65536.0f); } /// - /// Создает экземпляр TwFix32 из числа с плавающей точкой. + /// Creates an instance of TwFix32 from a floating-point number. + /// Создает экземпляр TwFix32 из числа с плавающей точкой. /// - /// Число с плавающей точкой. - /// Экземпляр TwFix32. - public static implicit operator TwFix32(float f) { - int i=(int)((f*65536.0f)+0.5f); - return new TwFix32() { - Whole=(short)(i>>16), - Frac=(ushort)(i&0x0000ffff) + /// Floating point number.Число с плавающей точкой. + /// Instance of TwFix32.Экземпляр TwFix32. + public static implicit operator TwFix32(float f) + { + int i = (int)((f * 65536.0f) + 0.5f); + return new TwFix32() + { + Whole = (short)(i >> 16), + Frac = (ushort)(i & 0x0000ffff) }; } /// - /// Создает экземпляр TwFix32 из целого числа. + /// Creates an instance of TwFix32 from an integer. + /// Создает экземпляр TwFix32 из целого числа. /// - /// Целое число. - /// Экземпляр TwFix32. - public static explicit operator TwFix32(uint value) { - return new TwFix32() { - Whole=(short)(value&0x0000ffff), - Frac=(ushort)(value>>16) + /// Integer.Целое число. + /// Instance of TwFix32.Экземпляр TwFix32. + public static explicit operator TwFix32(uint value) + { + return new TwFix32() + { + Whole = (short)(value & 0x0000ffff), + Frac = (ushort)(value >> 16) }; } /// - /// Приводит тип к числу с плавающей запятой. + /// Coerces the type to a floating point number. + /// Приводит тип к числу с плавающей запятой. /// - /// Экземпляр TwFix32. - /// Число с плавающей точкой. - public static implicit operator float(TwFix32 value) { + /// Instance of TwFix32.Экземпляр TwFix32. + /// Floating point number.Число с плавающей точкой. + public static implicit operator float(TwFix32 value) + { return value.ToFloat(); } /// - /// Приводит тип к целому числу. + /// Converts a type to an integer. + /// Приводит тип к целому числу. /// - /// Экземпляр TwFix32. - /// Целое число. - public static explicit operator uint(TwFix32 value) { - return (uint)(ushort)value.Whole+((uint)value.Frac<<16); + /// Instance of TwFix32.Экземпляр TwFix32. + /// Integer.Целое число. + public static explicit operator uint(TwFix32 value) + { + return (uint)(ushort)value.Whole + ((uint)value.Frac << 16); } } @@ -2586,8 +2748,9 @@ public static explicit operator uint(TwFix32 value) { /// Defines a frame rectangle in ICAP_UNITS coordinates. /// [DebuggerDisplay("{ToRectangle()}")] - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal struct TwFrame { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal struct TwFrame + { /// /// Gets or sets the x-coordinate of the left edge. @@ -2609,24 +2772,28 @@ internal struct TwFrame { /// public TwFix32 Bottom; - private RectangleF ToRectangle() { + private RectangleF ToRectangle() + { return new RectangleF( this.Left, this.Top, - this.Right-this.Left, - this.Bottom-this.Top); + this.Right - this.Left, + this.Bottom - this.Top); } - public static implicit operator RectangleF(TwFrame value) { + public static implicit operator RectangleF(TwFrame value) + { return value.ToRectangle(); } - public static implicit operator TwFrame(RectangleF value) { - return new TwFrame() { - Left=value.Left, - Top=value.Top, - Right=value.Right, - Bottom=value.Bottom + public static implicit operator TwFrame(RectangleF value) + { + return new TwFrame() + { + Left = value.Left, + Top = value.Top, + Right = value.Right, + Bottom = value.Bottom }; } } @@ -2639,8 +2806,9 @@ public static implicit operator TwFrame(RectangleF value) { /// Identifies the program/library/code resource. /// [DebuggerDisplay("{ProductName}, Version = {Version.Info}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal class TwIdentity { // TW_IDENTITY + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal class TwIdentity + { // TW_IDENTITY /// /// Unique number. In Windows, application hWnd. @@ -2683,14 +2851,17 @@ internal class TwIdentity { // TW_IDENTITY /// public TwStr32 ProductName; - public override bool Equals(object obj) { - if(obj!=null&&obj is TwIdentity) { - return ((TwIdentity)obj).Id==this.Id; + public override bool Equals(object obj) + { + if (obj != null && obj is TwIdentity) + { + return ((TwIdentity)obj).Id == this.Id; } return false; } - public override int GetHashCode() { + public override int GetHashCode() + { return this.Id.GetHashCode(); } } @@ -2699,8 +2870,9 @@ public override int GetHashCode() { /// Describes version of software currently running. /// [DebuggerDisplay("{Info}")] - [StructLayout(LayoutKind.Sequential,Pack=2,CharSet=CharSet.Ansi)] - internal struct TwVersion { // TW_VERSION + [StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi)] + internal struct TwVersion + { // TW_VERSION /// /// Major revision number of the software. @@ -2733,8 +2905,9 @@ internal struct TwVersion { // TW_VERSION /// /// Coordinates UI between application and data source. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwUserInterface { // TW_USERINTERFACE + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwUserInterface + { // TW_USERINTERFACE /// /// TRUE if DS should bring up its UI @@ -2755,8 +2928,9 @@ internal class TwUserInterface { // TW_USERINTERFACE /// /// Application gets detailed status info from a data source with this. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwStatus { // TW_STATUS + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwStatus + { // TW_STATUS /// /// Any TwCC constant @@ -2773,8 +2947,9 @@ internal class TwStatus { // TW_STATUS /// /// For passing events down from the application to the DS. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwEvent { // TW_EVENT + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwEvent + { // TW_EVENT /// /// Windows pMSG or Mac pEvent. @@ -2791,8 +2966,9 @@ internal class TwEvent { // TW_EVENT /// /// Application gets detailed image info from DS with this. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwImageInfo { // TW_IMAGEINFO + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwImageInfo + { // TW_IMAGEINFO /// /// Resolution in the horizontal @@ -2822,7 +2998,7 @@ internal class TwImageInfo { // TW_IMAGEINFO /// /// Number of bits for each sample /// - [MarshalAs(UnmanagedType.ByValArray,SizeConst=8)] + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public short[] BitsPerSample; /// @@ -2852,8 +3028,9 @@ internal class TwImageInfo { // TW_IMAGEINFO /// This structure is used to pass specific information between the data source and the application. /// [DebuggerDisplay("InfoId = {InfoId}, ItemType = {ItemType}, ReturnCode = {ReturnCode}")] - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwInfo:IDisposable { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwInfo : IDisposable + { /// /// Tag identifying an information. @@ -2884,48 +3061,66 @@ internal class TwInfo:IDisposable { public IntPtr Item; /// - /// Возвращает true, если значение элемента является дескриптором неуправляемой памяти; иначе, false. + /// Returns true if the element value is an unmanaged memory descriptor; otherwise false. + /// Возвращает true, если значение элемента является дескриптором неуправляемой памяти; иначе, false. /// - private bool _IsValue { - get { - return this.ItemType!=TwType.Handle&&TwTypeHelper.SizeOf(this.ItemType)*this.NumItems<=TwTypeHelper.SizeOf(TwType.Handle); + private bool _IsValue + { + get + { + return this.ItemType != TwType.Handle && TwTypeHelper.SizeOf(this.ItemType) * this.NumItems <= TwTypeHelper.SizeOf(TwType.Handle); } } /// - /// Возвращает значение элемента. + /// Returns the value of an element. + /// Возвращает значение элемента. /// - /// Значение элемента. - public object GetValue() { - var _result=new object[this.NumItems]; - if(this._IsValue) { - for(long i=0,_data=this.Item.ToInt64(),_mask=((1L<>=TwTypeHelper.SizeOf(this.ItemType)*8) { - _result[i]=TwTypeHelper.CastToCommon(this.ItemType,TwTypeHelper.ValueToTw(this.ItemType,_data&_mask)); + /// The value of the item.Значение элемента. + public object GetValue() + { + var _result = new object[this.NumItems]; + if (this._IsValue) + { + for (long i = 0, _data = this.Item.ToInt64(), _mask = ((1L << TwTypeHelper.SizeOf(this.ItemType) * 7) << TwTypeHelper.SizeOf(this.ItemType)) - 1; i < this.NumItems; i++, _data >>= TwTypeHelper.SizeOf(this.ItemType) * 8) + { + _result[i] = TwTypeHelper.CastToCommon(this.ItemType, TwTypeHelper.ValueToTw(this.ItemType, _data & _mask)); } - } else { - IntPtr _data=Twain32._Memory.Lock(this.Item); - try { - for(int i=0; i /// This structure is used to pass extended image information from the Data Source to the Application at the end of State 7. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwExtImageInfo { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwExtImageInfo + { /// - /// Количество элементов расширенного описания изображения. + /// The number of elements in the extended image description. + /// Количество элементов расширенного описания изображения. /// public uint NumInfos; @@ -2947,17 +3144,20 @@ internal class TwExtImageInfo { //public TwInfo[] Info; /// - /// Выполняет преображование в неуправляемый блок памяти. - /// - /// Набор элементов расширенного описания изображения. - /// Указатель на блок неуправляемой памяти. - public static IntPtr ToPtr(TwInfo[] info) { - var _twExtImageInfoSize=Marshal.SizeOf(typeof(TwExtImageInfo)); - var _twInfoSize=Marshal.SizeOf(typeof(TwInfo)); - var _data=Marshal.AllocHGlobal(_twExtImageInfoSize+(_twInfoSize*info.Length)); - Marshal.StructureToPtr(new TwExtImageInfo {NumInfos=(uint)info.Length},_data,true); - for(int i=0; iВыполняет преображование в неуправляемый блок памяти. + /// + /// A set of elements for an extended image description.Набор элементов расширенного описания изображения. + /// Pointer to an unmanaged memory block.Указатель на блок неуправляемой памяти. + public static IntPtr ToPtr(TwInfo[] info) + { + var _twExtImageInfoSize = Marshal.SizeOf(typeof(TwExtImageInfo)); + var _twInfoSize = Marshal.SizeOf(typeof(TwInfo)); + var _data = Marshal.AllocHGlobal(_twExtImageInfoSize + (_twInfoSize * info.Length)); + Marshal.StructureToPtr(new TwExtImageInfo { NumInfos = (uint)info.Length }, _data, true); + for (int i = 0; i < info.Length; i++) + { + Marshal.StructureToPtr(info[i], (IntPtr)(_data.ToInt64() + _twExtImageInfoSize + (_twInfoSize * i)), true); } return _data; } @@ -2966,8 +3166,9 @@ public static IntPtr ToPtr(TwInfo[] info) { /// /// Provides image layout information in current units. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwImageLayout { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwImageLayout + { /// /// Frame coords within larger document. @@ -2975,17 +3176,20 @@ internal class TwImageLayout { public TwFrame Frame; /// - /// Номер документа. + /// Document Number. + /// Номер документа. /// public uint DocumentNumber; /// - /// Номер страницы. + /// Page number. + /// Номер страницы. /// public uint PageNumber; //Reset when you go to next document /// - /// Номер кадра. + /// Frame number. + /// Номер кадра. /// public uint FrameNumber; //Reset when you go to next page } @@ -2993,8 +3197,9 @@ internal class TwImageLayout { /// /// Used with TwMSG.EndXfer to indicate additional data. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwPendingXfers { // TW_PENDINGXFERS + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwPendingXfers + { // TW_PENDINGXFERS public ushort Count; public uint EOJ; } @@ -3002,8 +3207,9 @@ internal class TwPendingXfers { // TW_PENDINGXFERS /// /// Used by application to get/set capability from/in a data source. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwCapability:IDisposable { // TW_CAPABILITY + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwCapability : IDisposable + { // TW_CAPABILITY /// /// Id of capability to set or get, e.g. TwCap.Brightness @@ -3022,16 +3228,18 @@ internal class TwCapability:IDisposable { // TW_CAPABILITY /// public IntPtr Handle; - private TwCapability() { + private TwCapability() + { } /// /// Initializes a new instance of the class. /// /// The cap. - public TwCapability(TwCap cap) { - this.Cap=cap; - this.ConType=TwOn.DontCare; + public TwCapability(TwCap cap) + { + this.Cap = cap; + this.ConType = TwOn.DontCare; } /// @@ -3040,12 +3248,14 @@ public TwCapability(TwCap cap) { /// The cap. /// The value. /// The type. - public TwCapability(TwCap cap,uint value,TwType type) { - this.Cap=cap; - this.ConType=TwOn.One; - this._SetValue(new TwOneValue() { - ItemType=type, - Item=value + public TwCapability(TwCap cap, uint value, TwType type) + { + this.Cap = cap; + this.ConType = TwOn.One; + this._SetValue(new TwOneValue() + { + ItemType = type, + Item = value }); } @@ -3055,16 +3265,20 @@ public TwCapability(TwCap cap,uint value,TwType type) { /// The cap. /// The value. /// The type. - public TwCapability(TwCap cap,string value,TwType type) { - this.Cap=cap; - this.ConType=TwOn.One; - int _twOneCustumValueSize=Marshal.SizeOf(typeof(TwOneCustumValue)); - this.Handle=Twain32._Memory.Alloc(_twOneCustumValueSize+Marshal.SizeOf(TwTypeHelper.TypeOf(type))); - IntPtr _ptr=Twain32._Memory.Lock(this.Handle); - try { - Marshal.StructureToPtr(new TwOneCustumValue {ItemType=type},_ptr,true); - Marshal.StructureToPtr(TwTypeHelper.CastToTw(type,value),(IntPtr)(_ptr.ToInt64()+_twOneCustumValueSize),true); - } finally { + public TwCapability(TwCap cap, string value, TwType type) + { + this.Cap = cap; + this.ConType = TwOn.One; + int _twOneCustumValueSize = Marshal.SizeOf(typeof(TwOneCustumValue)); + this.Handle = Twain32._Memory.Alloc(_twOneCustumValueSize + Marshal.SizeOf(TwTypeHelper.TypeOf(type))); + IntPtr _ptr = Twain32._Memory.Lock(this.Handle); + try + { + Marshal.StructureToPtr(new TwOneCustumValue { ItemType = type }, _ptr, true); + Marshal.StructureToPtr(TwTypeHelper.CastToTw(type, value), (IntPtr)(_ptr.ToInt64() + _twOneCustumValueSize), true); + } + finally + { Twain32._Memory.Unlock(this.Handle); } } @@ -3074,9 +3288,10 @@ public TwCapability(TwCap cap,string value,TwType type) { /// /// The cap. /// The range. - public TwCapability(TwCap cap,TwRange range) { - this.Cap=cap; - this.ConType=TwOn.Range; + public TwCapability(TwCap cap, TwRange range) + { + this.Cap = cap; + this.ConType = TwOn.Range; this._SetValue(range); } @@ -3086,19 +3301,24 @@ public TwCapability(TwCap cap,TwRange range) { /// The cap. /// The array. /// The array value. - public TwCapability(TwCap cap,TwArray array,object[] arrayValue) { - this.Cap=cap; - this.ConType=TwOn.Array; - int _twArraySize=Marshal.SizeOf(typeof(TwArray)); - int _twItemSize=Marshal.SizeOf(TwTypeHelper.TypeOf(array.ItemType)); - this.Handle=Twain32._Memory.Alloc(_twArraySize+(_twItemSize*arrayValue.Length)); - IntPtr _pTwArray=Twain32._Memory.Lock(this.Handle); - try { - Marshal.StructureToPtr(array,_pTwArray,true); - for(long i=0,_ptr=_pTwArray.ToInt64()+_twArraySize; iThe cap. /// The enumeration. /// The enumeration value. - public TwCapability(TwCap cap,TwEnumeration enumeration,object[] enumerationValue) { - this.Cap=cap; - this.ConType=TwOn.Enum; - int _twEnumerationSize=Marshal.SizeOf(typeof(TwEnumeration)); - int _twItemSize=Marshal.SizeOf(TwTypeHelper.TypeOf(enumeration.ItemType)); - this.Handle=Twain32._Memory.Alloc(_twEnumerationSize+(_twItemSize*enumerationValue.Length)); - IntPtr _pTwEnumeration=Twain32._Memory.Lock(this.Handle); - try { - Marshal.StructureToPtr(enumeration,_pTwEnumeration,true); - for(long i=0,_ptr=_pTwEnumeration.ToInt64()+_twEnumerationSize; i - /// Возвращает результат для указаной возможности. + /// Returns the result for the specified feature. + /// Возвращает результат для указаной возможности. /// - /// Экземпляр TwArray, TwEnumeration, _TwRange или _TwOneValue. - public object GetValue() { - IntPtr _ptr=Twain32._Memory.Lock(this.Handle); - try { - switch(this.ConType) { + /// Instance TwArray, TwEnumeration, _TwRange or _TwOneValue.Экземпляр TwArray, TwEnumeration, _TwRange или _TwOneValue. + public object GetValue() + { + IntPtr _ptr = Twain32._Memory.Lock(this.Handle); + try + { + switch (this.ConType) + { case TwOn.Array: - return new __TwArray((TwArray)Marshal.PtrToStructure(_ptr,typeof(TwArray)),(IntPtr)(_ptr.ToInt64()+Marshal.SizeOf(typeof(TwArray)))); + return new __TwArray((TwArray)Marshal.PtrToStructure(_ptr, typeof(TwArray)), (IntPtr)(_ptr.ToInt64() + Marshal.SizeOf(typeof(TwArray)))); case TwOn.Enum: - return new __TwEnumeration((TwEnumeration)Marshal.PtrToStructure(_ptr,typeof(TwEnumeration)),(IntPtr)(_ptr.ToInt64()+Marshal.SizeOf(typeof(TwEnumeration)))); + return new __TwEnumeration((TwEnumeration)Marshal.PtrToStructure(_ptr, typeof(TwEnumeration)), (IntPtr)(_ptr.ToInt64() + Marshal.SizeOf(typeof(TwEnumeration)))); case TwOn.Range: - return Marshal.PtrToStructure(_ptr,typeof(TwRange)); + return Marshal.PtrToStructure(_ptr, typeof(TwRange)); case TwOn.One: - TwOneCustumValue _value=Marshal.PtrToStructure(_ptr,typeof(TwOneCustumValue)) as TwOneCustumValue; - switch(_value.ItemType) { + TwOneCustumValue _value = Marshal.PtrToStructure(_ptr, typeof(TwOneCustumValue)) as TwOneCustumValue; + switch (_value.ItemType) + { case TwType.Str32: case TwType.Str64: case TwType.Str128: case TwType.Str255: case TwType.Str1024: case TwType.Uni512: - return Marshal.PtrToStructure((IntPtr)(_ptr.ToInt64()+Marshal.SizeOf(typeof(TwOneCustumValue))),TwTypeHelper.TypeOf(_value.ItemType)).ToString(); + return Marshal.PtrToStructure((IntPtr)(_ptr.ToInt64() + Marshal.SizeOf(typeof(TwOneCustumValue))), TwTypeHelper.TypeOf(_value.ItemType)).ToString(); default: - return Marshal.PtrToStructure(_ptr,typeof(TwOneValue)); + return Marshal.PtrToStructure(_ptr, typeof(TwOneValue)); } } return null; - } finally { + } + finally + { Twain32._Memory.Unlock(this.Handle); } } @@ -3165,34 +3397,43 @@ public object GetValue() { /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// - public void Dispose() { - if(this.Handle!=IntPtr.Zero) { + public void Dispose() + { + if (this.Handle != IntPtr.Zero) + { Twain32._Memory.Free(this.Handle); - this.Handle=IntPtr.Zero; + this.Handle = IntPtr.Zero; } } #endregion - private void _SetValue(T value) { - this.Handle=Twain32._Memory.Alloc(Marshal.SizeOf(typeof(T))); - IntPtr _ptr=Twain32._Memory.Lock(this.Handle); - try { - Marshal.StructureToPtr(value,_ptr,true); - } finally { + private void _SetValue(T value) + { + this.Handle = Twain32._Memory.Alloc(Marshal.SizeOf(typeof(T))); + IntPtr _ptr = Twain32._Memory.Lock(this.Handle); + try + { + Marshal.StructureToPtr(value, _ptr, true); + } + finally + { Twain32._Memory.Unlock(this.Handle); } } } - internal interface ITwArray { + internal interface ITwArray + { - TwType ItemType { + TwType ItemType + { get; set; } - uint NumItems { + uint NumItems + { get; set; } @@ -3201,29 +3442,36 @@ uint NumItems { /// /// Container for array of values. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwArray:ITwArray { //TWON_ARRAY. Container for array of values (a simplified TW_ENUMERATION) + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwArray : ITwArray + { //TWON_ARRAY. Container for array of values (a simplified TW_ENUMERATION) [MarshalAs(UnmanagedType.U2)] private TwType _itemType; private uint _numItems; /* How many items in ItemList */ //[MarshalAs(UnmanagedType.ByValArray,SizeConst=1)] //public byte[] ItemList; /* Array of ItemType values starts here */ - public TwType ItemType { - get { + public TwType ItemType + { + get + { return this._itemType; } - set { - this._itemType=value; + set + { + this._itemType = value; } } - public uint NumItems { - get { + public uint NumItems + { + get + { return this._numItems; } - set { - this._numItems=value; + set + { + this._numItems = value; } } } @@ -3231,8 +3479,9 @@ public uint NumItems { /// /// Container for a collection of values. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwEnumeration:ITwArray { //TWON_ENUMERATION. Container for a collection of values. + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwEnumeration : ITwArray + { //TWON_ENUMERATION. Container for a collection of values. [MarshalAs(UnmanagedType.U2)] private TwType _ItemType; private uint _numItems; /* How many items in ItemList */ @@ -3241,39 +3490,51 @@ public uint NumItems { //[MarshalAs(UnmanagedType.ByValArray,SizeConst=1)] //public byte[] ItemList; /* Array of ItemType values starts here */ - public TwType ItemType { - get { + public TwType ItemType + { + get + { return this._ItemType; } - set { - this._ItemType=value; + set + { + this._ItemType = value; } } - public uint NumItems { - get { + public uint NumItems + { + get + { return this._numItems; } - set { - this._numItems=value; + set + { + this._numItems = value; } } - public uint CurrentIndex { - get { + public uint CurrentIndex + { + get + { return this._currentIndex; } - set { - this._currentIndex=value; + set + { + this._currentIndex = value; } } - public uint DefaultIndex { - get { + public uint DefaultIndex + { + get + { return this._defaultIndex; } - set { - this._defaultIndex=value; + set + { + this._defaultIndex = value; } } } @@ -3281,8 +3542,9 @@ public uint DefaultIndex { /// /// Container for one value. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwOneValue { //TW_ONEVALUE. Container for one value. + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwOneValue + { //TW_ONEVALUE. Container for one value. [MarshalAs(UnmanagedType.U2)] public TwType ItemType; public uint Item; @@ -3291,8 +3553,9 @@ public uint DefaultIndex { /// /// Container for one custom value. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwOneCustumValue { //TW_ONEVALUE. Container for one value. + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwOneCustumValue + { //TW_ONEVALUE. Container for one value. [MarshalAs(UnmanagedType.U2)] public TwType ItemType; } @@ -3300,8 +3563,9 @@ public uint DefaultIndex { /// /// Container for a range of values. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwRange { //TWON_RANGE. Container for a range of values. + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwRange + { //TWON_RANGE. Container for a range of values. [MarshalAs(UnmanagedType.U2)] public TwType ItemType; public uint MinValue; /* Starting value in the range. */ @@ -3314,8 +3578,9 @@ public uint DefaultIndex { /// /// Sets up DS to application data transfer via a memory buffer. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwSetupMemXfer { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwSetupMemXfer + { /// /// Minimum buffer size in bytes @@ -3336,12 +3601,14 @@ internal class TwSetupMemXfer { /// /// Used to pass image data (e.g. in strips) from DS to application. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwImageMemXfer { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwImageMemXfer + { - public TwImageMemXfer() { - this.Compression=(TwCompression)ushort.MaxValue; - this.BytesPerRow=this.BytesWritten=this.Columns=this.Rows=this.XOffset=this.YOffset=uint.MaxValue; + public TwImageMemXfer() + { + this.Compression = (TwCompression)ushort.MaxValue; + this.BytesPerRow = this.BytesWritten = this.Columns = this.Rows = this.XOffset = this.YOffset = uint.MaxValue; } /// @@ -3389,8 +3656,9 @@ public TwImageMemXfer() { /// /// Used to manage memory buffers. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwMemory { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwMemory + { /// /// Any combination of the TWMF_ constants. @@ -3412,8 +3680,9 @@ internal class TwMemory { /// /// Sets up DS to application data transfer via a file. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwSetupFileXfer { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwSetupFileXfer + { /// /// File to contain data. @@ -3435,8 +3704,9 @@ internal class TwSetupFileXfer { /// /// DAT_PALETTE8. Color palette when TWPT_PALETTE pixels xfer'd in mem buf. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwPalette8 { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwPalette8 + { /// /// Number of colors in the color table. @@ -3452,21 +3722,25 @@ internal class TwPalette8 { /// /// Array of palette values starts here. /// - [MarshalAs(UnmanagedType.ByValArray,SizeConst=256)] + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public TwElement8[] Colors; - public static implicit operator Twain32.ColorPalette(TwPalette8 palette) { + public static implicit operator Twain32.ColorPalette(TwPalette8 palette) + { return Twain32.ColorPalette.Create(palette); } - public static implicit operator TwPalette8(Twain32.ColorPalette palette) { - TwPalette8 _result=new TwPalette8 { - PaletteType=palette.PaletteType, - NumColors=(ushort)palette.Colors.Length, - Colors=new TwElement8[256] + public static implicit operator TwPalette8(Twain32.ColorPalette palette) + { + TwPalette8 _result = new TwPalette8 + { + PaletteType = palette.PaletteType, + NumColors = (ushort)palette.Colors.Length, + Colors = new TwElement8[256] }; - for(int i=0; i [DebuggerDisplay("RGB=({Channel1},{Channel2},{Channel3}), Index={Index}")] - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal struct TwElement8 { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal struct TwElement8 + { /// /// Value used to index into the color table. @@ -3499,15 +3774,18 @@ internal struct TwElement8 { /// public byte Channel3; - public static implicit operator Color(TwElement8 element) { - return Color.FromArgb(element.Channel1,element.Channel2,element.Channel3); + public static implicit operator Color(TwElement8 element) + { + return Color.FromArgb(element.Channel1, element.Channel2, element.Channel3); } - public static implicit operator TwElement8(Color color) { - return new TwElement8 { - Channel1=color.R, - Channel2=color.G, - Channel3=color.B + public static implicit operator TwElement8(Color color) + { + return new TwElement8 + { + Channel1 = color.R, + Channel2 = color.G, + Channel3 = color.B }; } } @@ -3515,8 +3793,9 @@ public static implicit operator TwElement8(Color color) { /// /// DAT_DEVICEEVENT, information about events. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwDeviceEvent { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwDeviceEvent + { /// /// One of the TWDE_xxxx values. @@ -3580,8 +3859,9 @@ internal class TwDeviceEvent { /// /// Used to register callbacks. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwCallback { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwCallback + { [MarshalAs(UnmanagedType.FunctionPtr)] public CallBackProc CallBackProc; @@ -3594,8 +3874,9 @@ internal class TwCallback { /// /// Used to register callbacks. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwCallback2 { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwCallback2 + { [MarshalAs(UnmanagedType.FunctionPtr)] public CallBackProc CallBackProc; @@ -3605,35 +3886,55 @@ internal class TwCallback2 { public short Message; } + /// + /// Allows for a data source and application to pass custom data to each other. + /// + /// TW_CUSTOMDSDATA + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwCustomDSData + { + + public uint InfoLength; + + public IntPtr hData; + } + [return: MarshalAs(UnmanagedType.U2)] - internal delegate TwRC CallBackProc(TwIdentity srcId,TwIdentity appId,[MarshalAs(UnmanagedType.U4)]TwDG dg,[MarshalAs(UnmanagedType.U2)]TwDAT dat,[MarshalAs(UnmanagedType.U2)]TwMSG msg,IntPtr data); + internal delegate TwRC CallBackProc(TwIdentity srcId, TwIdentity appId, [MarshalAs(UnmanagedType.U4)] TwDG dg, [MarshalAs(UnmanagedType.U2)] TwDAT dat, [MarshalAs(UnmanagedType.U2)] TwMSG msg, IntPtr data); #endregion #region Internal Type Definitions - internal interface __ITwArray { - - TwType ItemType { + internal interface __ITwArray + { + + TwType ItemType + { get; } - uint NumItems { + uint NumItems + { get; } - object[] Items { + object[] Items + { get; } } - internal interface __ITwEnumeration:__ITwArray { + internal interface __ITwEnumeration : __ITwArray + { - int CurrentIndex { + int CurrentIndex + { get; } - int DefaultIndex { + int DefaultIndex + { get; } } @@ -3641,32 +3942,41 @@ int DefaultIndex { /// /// Container for array of values. /// - internal class __TwArray:__ITwArray { + internal class __TwArray : __ITwArray + { private ITwArray _data; private object[] _items; - internal __TwArray(ITwArray data,IntPtr items) { - this._data=data; - this._items=new object[this._data.NumItems]; - for(long i=0,_offset=0,_sizeof=TwTypeHelper.SizeOf(this._data.ItemType); i /// Container for a collection of values. /// - internal class __TwEnumeration:__TwArray,__ITwEnumeration { + internal class __TwEnumeration : __TwArray, __ITwEnumeration + { private TwEnumeration _data; - internal __TwEnumeration(TwEnumeration data,IntPtr items):base(data,items) { - this._data=data; + internal __TwEnumeration(TwEnumeration data, IntPtr items) : base(data, items) + { + this._data = data; } - public int CurrentIndex { - get { + public int CurrentIndex + { + get + { return (int)this._data.CurrentIndex; } } - public int DefaultIndex { - get { + public int DefaultIndex + { + get + { return (int)this._data.DefaultIndex; } } @@ -3702,11 +4018,13 @@ public int DefaultIndex { /// /// DAT_ENTRYPOINT. returns essential entry points. /// - [StructLayout(LayoutKind.Sequential,Pack=2)] - internal class TwEntryPoint { + [StructLayout(LayoutKind.Sequential, Pack = 2)] + internal class TwEntryPoint + { - public TwEntryPoint() { - this.Size=Marshal.SizeOf(this); + public TwEntryPoint() + { + this.Size = Marshal.SizeOf(this); } /// @@ -3754,6 +4072,6 @@ public TwEntryPoint() { internal delegate IntPtr DSM_MemoryLock(IntPtr handle); internal delegate void DSM_MemoryUnlock(IntPtr handle); - + #endregion -} +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/TwainException.cs b/TownSuite.TwainScanner/TwainException.cs index b5b0a5a..8944c88 100644 --- a/TownSuite.TwainScanner/TwainException.cs +++ b/TownSuite.TwainScanner/TwainException.cs @@ -39,27 +39,56 @@ namespace TownSuite.TwainScanner { /// - /// Класс исключения + /// Exception class + /// Класс исключения /// [Serializable] [DebuggerDisplay("{Message}; ReturnCode = {ReturnCode}; ConditionCode = {ConditionCode}")] - public sealed class TwainException:Exception { + public sealed class TwainException : Exception + { + private readonly static Dictionary _twcc = new Dictionary { + {TwCC.Success, "It worked!"}, + {TwCC.Bummer, "Failure due to unknown causes."}, + {TwCC.LowMemory, "Not enough memory to perform operation."}, + {TwCC.NoDS, "No Data Source."}, + {TwCC.MaxConnections, "DS is connected to max possible applications."}, + {TwCC.OperationError, "DS or DSM reported error, application shouldn't."}, + {TwCC.BadCap, "Unknown capability."}, + {TwCC.BadProtocol, "Unrecognized MSG DG DAT combination."}, + {TwCC.BadValue, "Data parameter out of range."}, + {TwCC.SeqError, "DG DAT MSG out of expected sequence."}, + {TwCC.BadDest, "Unknown destination Application/Source in DSM_Entry."}, + {TwCC.CapUnsupported, "Capability not supported by source."}, + {TwCC.CapBadOperation, "Operation not supported by capability."}, + {TwCC.CapSeqError, "Capability has dependancy on other capability."}, + /* Added 1.8 */ + {TwCC.Denied, "File System operation is denied (file is protected)."}, + {TwCC.FileExists, "Operation failed because file already exists."}, + {TwCC.FileNotFound, "File not found."}, + {TwCC.NotEmpty, "Operation failed because directory is not empty."}, + {TwCC.PaperJam, "The feeder is jammed."}, + {TwCC.PaperDoubleFeed, "The feeder detected multiple pages."}, + {TwCC.FileWriteError, "Error writing the file (meant for things like disk full conditions)."}, + {TwCC.CheckDeviceOnline, "The device went offline prior to or during this operation."} + }; /// /// Initializes a new instance of the class. /// /// The condition code. /// The return code. - internal TwainException(TwCC cc,TwRC rc):this(TwainException._CodeToMessage(cc)) { - this.ConditionCode=cc; - this.ReturnCode=rc; + internal TwainException(TwCC cc, TwRC rc) : this(TwainException._CC2Message(cc)) + { + this.ConditionCode = cc; + this.ReturnCode = rc; } /// /// Initializes a new instance of the class. /// /// The message. - internal TwainException(string message) : base(message) { + internal TwainException(string message) : base(message) + { } /// @@ -67,101 +96,57 @@ internal TwainException(string message) : base(message) { /// /// The message. /// Inner exception. - internal TwainException(string message,Exception innerException):base(message,innerException) { + internal TwainException(string message, Exception innerException) : base(message, innerException) + { } /// /// Initializes a new instance of the class. /// - /// Объект , содержащий сериализованные данные объекта о выбрасываемом исключении. - /// Объект , содержащий контекстные сведения об источнике или назначении. - internal TwainException(SerializationInfo info,StreamingContext context) : base(info,context) { - this.ConditionCode=(TwCC)info.GetValue("ConditionCode",typeof(TwCC)); - this.ReturnCode=(TwRC)info.GetValue("ReturnCode",typeof(TwRC)); + /// An object , containing serialized object data about the thrown exception.Объект , содержащий сериализованные данные объекта о выбрасываемом исключении. + /// An object , containing contextual information about the source or destination.Объект , содержащий контекстные сведения об источнике или назначении. + internal TwainException(SerializationInfo info, StreamingContext context) : base(info, context) + { + this.ConditionCode = (TwCC)info.GetValue("ConditionCode", typeof(TwCC)); + this.ReturnCode = (TwRC)info.GetValue("ReturnCode", typeof(TwRC)); } /// - /// При переопределении в производном классе задает сведения об исключении для . + /// When overridden in a derived class, sets the exception information for . + /// При переопределении в производном классе задает сведения об исключении для . /// - /// Объект , содержащий сериализованные данные объекта о выбрасываемом исключении. - /// Объект , содержащий контекстные сведения об источнике или назначении. + /// An object , containing serialized object data about the thrown exception.Объект , содержащий сериализованные данные объекта о выбрасываемом исключении. + /// An object , containing contextual information about the source or destination.Объект , содержащий контекстные сведения об источнике или назначении. /// /// /// /// - [SecurityPermission(SecurityAction.Demand,SerializationFormatter = true)] - public override void GetObjectData(SerializationInfo info,StreamingContext context) { - base.GetObjectData(info,context); - info.AddValue("ConditionCode",this.ConditionCode); - info.AddValue("ReturnCode",this.ReturnCode); + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("ConditionCode", this.ConditionCode); + info.AddValue("ReturnCode", this.ReturnCode); } /// - /// Возвращает код состояния операции. Get condition code. + /// Returns the operation status code. + /// Возвращает код состояния операции. /// - public TwCC ConditionCode { - get; - private set; - } + public TwCC ConditionCode { get; private set; } /// - /// Возвращает код результата операции. Get return code. + /// Returns the result code of the operation. + /// Возвращает код результата операции. /// - public TwRC ReturnCode { - get; - private set; - } + public TwRC ReturnCode { get; private set; } - private static string _CodeToMessage(TwCC code) { - switch(code) { - case TwCC.Success: - return "It worked!"; - case TwCC.Bummer: - return "Failure due to unknown causes."; - case TwCC.LowMemory: - return "Not enough memory to perform operation."; - case TwCC.NoDS: - return "No Data Source."; - case TwCC.MaxConnections: - return "DS is connected to max possible applications."; - case TwCC.OperationError: - return "DS or DSM reported error, application shouldn't."; - case TwCC.BadCap: - return "Unknown capability."; - case TwCC.BadProtocol: - return "Unrecognized MSG DG DAT combination."; - case TwCC.BadValue: - return "Data parameter out of range."; - case TwCC.SeqError: - return "DG DAT MSG out of expected sequence."; - case TwCC.BadDest: - return "Unknown destination Application/Source in DSM_Entry."; - case TwCC.CapUnsupported: - return "Capability not supported by source."; - case TwCC.CapBadOperation: - return "Operation not supported by capability."; - case TwCC.CapSeqError: - return "Capability has dependancy on other capability."; - /* Added 1.8 */ - case TwCC.Denied: - return "File System operation is denied (file is protected)."; - case TwCC.FileExists: - return "Operation failed because file already exists."; - case TwCC.FileNotFound: - return "File not found."; - case TwCC.NotEmpty: - return "Operation failed because directory is not empty."; - case TwCC.PaperJam: - return "The feeder is jammed."; - case TwCC.PaperDoubleFeed: - return "The feeder detected multiple pages."; - case TwCC.FileWriteError: - return "Error writing the file (meant for things like disk full conditions)."; - case TwCC.CheckDeviceOnline: - return "The device went offline prior to or during this operation."; - default: - return "Unknown error."; + private static string _CC2Message(TwCC code) + { + if (TwainException._twcc.TryGetValue(code, out var _result)) + { + return _result; } + return "Unknown error."; } } -} +} \ No newline at end of file diff --git a/TownSuite.TwainScanner/_ImageHandler.cs b/TownSuite.TwainScanner/_ImageHandler.cs new file mode 100644 index 0000000..dbb3050 --- /dev/null +++ b/TownSuite.TwainScanner/_ImageHandler.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; + +namespace TownSuite.TwainScanner +{ + + /// + /// Base class to processing of a acquired image. + /// + /// + internal abstract class _ImageHandler : IImageHandler + { + private Dictionary _state = null; + private const string _ImagePointer = "ImagePointer"; + + #region IImageHandler + + /// + /// Convert a block of unmanaged memory to stream. + /// + /// The pointer to block of unmanaged memory. + /// The provider of a streams. + /// + /// Stream that contains data of a image. + /// + public Stream PtrToStream(IntPtr ptr, IStreamProvider provider) + { + this._state = new Dictionary { + {_ImageHandler._ImagePointer, ptr} + }; + + Stream _stream = provider != null ? provider.GetStream() : new MemoryStream(); + this.PtrToStreamCore(ptr, _stream); + return _stream; + } + + #endregion + + /// + /// Convert a block of unmanaged memory to stream. + /// + /// The pointer to block of unmanaged memory. + /// The provider of a streams. + protected virtual void PtrToStreamCore(IntPtr ptr, Stream stream) + { + BinaryWriter _writer = new BinaryWriter(stream); + + int _size = this.GetSize(); + byte[] _buffer = new byte[this.BufferSize]; + + for (int _offset = 0, _len = 0; _offset < _size; _offset += _len) + { + _len = Math.Min(this.BufferSize, _size - _offset); + Marshal.Copy((IntPtr)(ptr.ToInt64() + _offset), _buffer, 0, _len); + _writer.Write(_buffer, 0, _len); + } + } + + /// + /// Gets the size of a image data. + /// + /// Size of a image data. + protected abstract int GetSize(); + + /// + /// Gets the size of the buffer. + /// + /// + /// The size of the buffer. + /// + protected abstract int BufferSize { get; } + + /// + /// Gets the state of the handler. + /// + /// + /// The state of the handler. + /// + protected Dictionary HandlerState => this._state; + + /// + /// Gets the pointer to unmanaged memory that contain image data. + /// + /// + /// The image pointer. + /// + protected IntPtr ImagePointer => (IntPtr)this.HandlerState[_ImageHandler._ImagePointer]; + } + + /// + /// Provides processing of a acquired image. + /// + public interface IImageHandler + { + + /// + /// Convert a block of unmanaged memory to stream. + /// + /// The pointer to block of unmanaged memory. + /// The provider of a streams. + /// Stream that contains data of a image. + Stream PtrToStream(IntPtr ptr, IStreamProvider provider); + } + + /// + /// Provides instances of the for data writing. + /// + public interface IStreamProvider + { + + /// + /// Gets the stream. + /// + /// The stream. + Stream GetStream(); + } + + /// + /// Provides image factory. + /// + /// Type of image + public interface IImageFactory + { + + /// + /// Create and return instance of image. + /// + /// Image data. + /// Image. + T Create(Stream stream); + } +} \ No newline at end of file