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; }
///