Exemplo n.º 1
0
        private ScanForm()
        {
            InitializeComponent();
            appId   = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly());
            session = new TwainSession(appId);

            session.TransferReady   += new EventHandler <TransferReadyEventArgs>(session_TransferReady);
            session.DataTransferred += new EventHandler <DataTransferredEventArgs>(session_DataTransferred);

            session.Open();

            scanner = session.ShowSourceSelector();

            if (scanner == null)
            {
                this.DialogResult = DialogResult.Abort;
                session.Close();
                return;
            }

            ReturnCode rc = scanner.Open();

            if (rc != ReturnCode.Success)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                session.Close();
                return;
            }
        }
Exemplo n.º 2
0
        private void StartupTwain()
        {
            try
            {
                if (TwainSession.IsAvailable(this.Handle))
                {
                    _twainSession = new TwainSession();
                    _twainSession.Startup(this.Handle, "LEAD Technologies, Inc.", "LEAD Test Applications", "Version 1.0", "TWAIN Test Application", TwainStartupFlags.None);
                    _twainSession.AcquirePage += new EventHandler <TwainAcquirePageEventArgs>(twainSession_AcquirePage);
                }

                scanImageToolStripMenuItem.Enabled = _twainSession != null;
            }
            catch (TwainException ex)
            {
                if (ex.Code == TwainExceptionCode.InvalidDll)
                {
                    _twainSession = null;
                    Messager.ShowError(this, "You have an old version of TWAINDSM.DLL. Please download latest version of this DLL from www.twain.org");
                }
                else
                {
                    _twainSession = null;
                    Messager.ShowError(this, ex);
                }
            }
            catch (Exception ex)
            {
                Messager.ShowError(this, ex);
                _twainSession = null;
            }
        }
Exemplo n.º 3
0
        protected override ScanDevice PromptForDeviceInternal()
        {
            if (ScanProfile != null && ScanProfile.TwainImpl == TwainImpl.Legacy)
            {
                return Legacy.TwainApi.SelectDeviceUI();
            }

            var session = new TwainSession(TwainAppId);
            session.Open();
            try
            {
                var ds = session.ShowSourceSelector();
                if (ds == null)
                {
                    return null;
                }
                string deviceId = ds.Name;
                string deviceName = ds.Name;
                return new ScanDevice(deviceId, deviceName);
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 4
0
        private static TwainSession InitTwain()
        {
            var twain = new TwainSession(TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly()));

            twain.TransferReady += (s, e) =>
            {
                Console.WriteLine("Got xfer ready on thread {0}.", Thread.CurrentThread.ManagedThreadId);
            };
            twain.DataTransferred += (s, e) =>
            {
                if (e.NativeData != IntPtr.Zero)
                {
                    Console.WriteLine("SUCCESS! Got twain data on thread {0}.", Thread.CurrentThread.ManagedThreadId);
                }
                else
                {
                    Console.WriteLine("BUMMER! No twain data on thread {0}.", Thread.CurrentThread.ManagedThreadId);
                }
            };

            twain.SourceDisabled += (s, e) =>
            {
                Console.WriteLine("Source disabled on thread {0}.", Thread.CurrentThread.ManagedThreadId);
                var rc = twain.CurrentSource.Close();
                rc = twain.Close();
            };
            return(twain);
        }
Exemplo n.º 5
0
        public bool GetCap()
        {
            bool flag = true;

            if (capId == TwCap.ICAP_XRESOLUTION || capId == TwCap.ICAP_YRESOLUTION)
            {
                flag = SetInch();
            }
            //if (capId == TwCap.ICAP_THRESHOLD)
            //{
            //    flag = SetBitDepthReduction();
            //}
            if (flag)
            {
                if (capId == TwCap.ECAP_PAPERSOURCE)
                {
                    GetPaperSource();
                }
                else
                {
                    TwCapability cap = new TwCapability(capId);

                    if (twSession.GetCapability(ref cap))
                    {
                        IntPtr intPtr = cap.contentValuePtr;
                        switch (cap.contentType)
                        {
                        case TwOn.One:
                            GetCapFromOneValue(intPtr);
                            break;

                        case TwOn.Array:
                            GetCapFromArray(intPtr);
                            break;

                        case TwOn.Enum:
                            GetCapFromEnumeration(intPtr);
                            break;

                        case TwOn.Range:
                            GetCapFromRange(intPtr);
                            break;

                        default:
                        {
                            logger.Debug("the contentType in TwCapability is wrong");
                            flag = false;
                        }
                        break;
                        }
                    }
                    if (cap.contentValuePtr != null)
                    {
                        TwainSession.GlobalFree(cap.contentValuePtr);
                    }
                }
            }
            return(flag);
        }
Exemplo n.º 6
0
        public void VerifyState_No_Throws_When_State_Is_Not_Enforced()
        {
            ITwainSessionInternal session = new TwainSession(TWIdentity.Create(DataGroups.Image, new Version(1, 0), "test", "test", "test", "test"));

            session.EnforceState = false;
            session.ChangeState(4, false);

            session.VerifyState(6, 6, DataGroups.Image, DataArgumentType.ImageNativeXfer, Message.Get);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseTriplet" /> class.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        protected BaseTriplet(TwainSession session)
        {
            this.Session = session ?? throw new ArgumentNullException(nameof(session));

            Is32Bit = session.Config.Is32Bit;
            IsWin   = session.Config.Platform == System.PlatformID.Win32NT;
            IsLinux = session.Config.Platform == System.PlatformID.Unix;
            IsMac   = session.Config.Platform == System.PlatformID.MacOSX;
        }
Exemplo n.º 8
0
        public ProcessDialog(TwainSession twainSession, IOcrEngine ocrEngine, string documentFileName, DocumentFormat format)
        {
            InitializeComponent();

            _twainSession     = twainSession;
            _document         = ocrEngine.DocumentManager.CreateDocument();
            _documentFileName = documentFileName;
            _format           = format;
        }
Exemplo n.º 9
0
        /// <summary>
        /// アプリケーションの初期化処理を行います。
        /// </summary>
        private void InitClass()
        {
            // フォームのタイトルを設定します。
            this.Text = "TWAIN 取得 【振替伝票読み取り】";

            //自分自身のバージョン情報を取得する 2011/03/25
            //System.Diagnostics.FileVersionInfo ver =
            //    System.Diagnostics.FileVersionInfo.GetVersionInfo(
            //    System.Reflection.Assembly.GetExecutingAssembly().Location);

            //キャプションにバージョンを追加 2011/03/25
            //Messager.Caption += " ver " + ver.FileMajorPart.ToString() + "." + ver.FileMinorPart.ToString();

            //Text = Messager.Caption;

            // ロック解除状態を確認します。
            //Support.Unlock(false);

            // RasterImageViewerコントロールを初期化します。
            _viewer = new RasterImageViewer();
            //_viewer.Dock = DockStyle.Fill;
            _viewer.BackColor = Color.DarkGray;
            Controls.Add(_viewer);
            _viewer.BringToFront();
            _viewer.Visible = false;

            // コーデックパスを設定します。
            RasterCodecs.Startup();

            // RasterCodecsオブジェクトを初期化します。
            _codecs = new RasterCodecs();

            if (TwainSession.IsAvailable(this))
            {
                // TwainSessionオブジェクトを初期化します。
                _twainSession = new TwainSession();

                // TWAIN セッションを初期化します。
                _twainSession.Startup(this, "FKDL", "LEADTOOLS", "Ver16.5J", "OCR", TwainStartupFlags.None);
                //_twainSession.Startup2(this, "FKDL", "LEADTOOLS", "Ver16.5J", "OCR", TwainStartupFlags.None, TwainLanguage.LanguageJapanese, TwainCountry.CountryJapan);
            }
            else
            {
                //_miFileAcquire.Enabled = false;
                //_miFileSelectSource.Enabled = false;
            }

            // 各値を初期化します。
            _fileName    = string.Empty;
            _fileFormat  = RasterImageFormat.Tif;
            _pageNo      = 1;
            _sFileNumber = 0;

            //UpdateMyControls();
            UpdateStatusBarText();
        }
Exemplo n.º 10
0
        private static void TestThisSource(TwainSession session, DataSource source)
        {
            Console.WriteLine($"Testing data source {source}");
            Console.WriteLine();

            source.Open();

            var testStatus  = session.GetStatus();
            var testMessage = session.GetLocalizedStatus(ref testStatus);

            var rc = source.ShowUI(IntPtr.Zero);
        }
Exemplo n.º 11
0
 public List<ScanDevice> GetDeviceList()
 {
     var session = new TwainSession(TwainAppId);
     session.Open();
     try
     {
         return session.GetSources().Select(ds => new ScanDevice(ds.Name, ds.Name)).ToList();
     }
     finally
     {
         session.Close();
     }
 }
Exemplo n.º 12
0
 public List<ScanDevice> GetDeviceList(TwainImpl twainImpl)
 {
     PlatformInfo.Current.PreferNewDSM = twainImpl != TwainImpl.OldDsm;
     var session = new TwainSession(TwainAppId);
     session.Open();
     try
     {
         return session.GetSources().Select(ds => new ScanDevice(ds.Name, ds.Name)).ToList();
     }
     finally
     {
         session.Close();
     }
 }
Exemplo n.º 13
0
        public void Scan()
        {
            var applicationID = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly());

            Session = new TwainSession(applicationID);
            Session.TransferReady   += Session_TransferReady;
            Session.DataTransferred += Session_DataTransferred;
            Session.SourceDisabled  += Session_SourceDisabled;
            Session.Open();
            DataSource dataSource = Session.FirstOrDefault();

            dataSource.Open();
            dataSource.Enable(SourceEnableMode.NoUI, false, WindowHandle);
        }
Exemplo n.º 14
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                bool bTwainAvailable = TwainSession.IsAvailable(this.Handle);
                if (bTwainAvailable)
                {
                    //Initialize codecs object
                    _codecs = new RasterCodecs();

                    //Initialize the number of Files to be saved using Twain
                    _saveFilesCount = 0; //Variable

                    _twainSaveFilePath = Leadtools.Demos.DemosGlobal.ImagesFolder;
                    //Set the name of the first file to be saved using Twain
                    _twainSaveFileName = ChangeSaveFileName("");//variable

                    //Initialize the twnSession object
                    _twnSession = new TwainSession();

                    //For 32-bit driver support in 64-bit applications, use the following TWAIN initialization method instead:
                    //_twnSession.Startup(this.Handle, "LEADTOOLS", "LEADTOOLS for .NET", String.Empty, "TwainWithBarcodeSeparatorDemo", TwainStartupFlags.UseThunkServer);

                    //Start the twnSession object
                    _twnSession.Startup(this.Handle, "LEADTOOLS", "LEADTOOLS for .NET", String.Empty, "TwainWithBarcodeSeparatorDemo", TwainStartupFlags.None);
                    //handle the AcquirePage event
                    _twnSession.AcquirePage += new EventHandler <TwainAcquirePageEventArgs>(Twain_AcquirePage);

                    _seperatorStringDlg = new SeperatorStringDialog();

                    InitViewer();
                    UpdateControls();
                    UpdateStatusBarText();
                }
                EnableControls(bTwainAvailable);
            }
            catch (TwainException ex)
            {
                if (ex.Code == TwainExceptionCode.InvalidDll)
                {
                    Messager.ShowError(this, "You have an old version of TWAINDSM.DLL. Please download latest version of this DLL from www.twain.org");
                }
                else
                {
                    Messager.ShowError(this, ex);
                }

                EnableControls(false);
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="twSource">twSession</param>
 /// <param name="format">文件格式字符串表示</param>
 /// <param name="action">文件传输函数委托</param>
 public ScanImageViewer(TwainSession twainSession, Int32 maxImageSize, int blanklimit, int resolution, TwFileFormat fileformat)
 {
     InitializeComponent();
     twSession = twainSession;
     worker    = new BackgroundWorker();
     worker.WorkerReportsProgress      = true;
     worker.WorkerSupportsCancellation = true;
     cnt = 0;
     this.buttonControl.DataContext = "传输未开始";
     this.maxImageSize   = maxImageSize;
     this.blankSizeLimit = blanklimit;
     this.resolution     = resolution;
     fileType            = fileformat;
     Init();
 }
Exemplo n.º 16
0
        public TwainVM()
        {
            DataSources    = new ObservableCollection <DataSourceVM>();
            CapturedImages = new ObservableCollection <ImageSource>();

            //this.SynchronizationContext = SynchronizationContext.Current;
            var appId = TWIdentity.CreateFromAssembly(DataGroups.Image | DataGroups.Audio, Assembly.GetEntryAssembly());

            session = new TwainSession(appId);
            session.TransferError   += Session_TransferError;
            session.TransferReady   += Session_TransferReady;
            session.DataTransferred += Session_DataTransferred;
            session.SourceDisabled  += Session_SourceDisabled;
            session.StateChanged    += (s, e) => { RaisePropertyChanged(() => State); };
        }
Exemplo n.º 17
0
        public List <ScanDevice> GetDeviceList(TwainImpl twainImpl)
        {
            PlatformInfo.Current.PreferNewDSM = twainImpl != TwainImpl.OldDsm;
            var session = new TwainSession(TwainAppId);

            session.Open();
            try
            {
                return(session.GetSources().Select(ds => new ScanDevice(ds.Name, ds.Name)).ToList());
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 18
0
        private static TwainSession InitTwain()
        {
            var twain = new TwainSession(TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly()));
            twain.TransferReady += (s, e) =>
            {
                Console.WriteLine("Got xfer ready on thread {0}.", Thread.CurrentThread.ManagedThreadId);
            };

            twain.SourceDisabled += (s, e) =>
            {
                Console.WriteLine("Source disabled on thread {0}.", Thread.CurrentThread.ManagedThreadId);
                var rc = twain.CurrentSource.Close();
                rc = twain.Close();
            };
            return twain;
        }
Exemplo n.º 19
0
        private static TwainSession InitTwain()
        {
            var twain = new TwainSession(TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly()));

            twain.TransferReady += (s, e) =>
            {
                Console.WriteLine("Got xfer ready on thread {0}.", Thread.CurrentThread.ManagedThreadId);
            };

            twain.SourceDisabled += (s, e) =>
            {
                Console.WriteLine("Source disabled on thread {0}.", Thread.CurrentThread.ManagedThreadId);
                var rc = twain.CurrentSource.Close();
                rc = twain.Close();
            };
            return(twain);
        }
Exemplo n.º 20
0
        private void UpdateControls()
        {
            scanImageToolStripMenuItem.Enabled = twainSession != null && TwainSession.IsAvailable(this.Handle);
            EnableControls(true);
            dGV_Results.Rows.Clear();
            dGV_Errors.Rows.Clear();

            _tB_readonlyMRZCode.Lines = _reader.Lines;
            if (rasterImageViewer1.Image != null)
            {
                selectedRect = _reader.Bounds;
            }
            else
            {
                selectedRect = LeadRect.Empty;
            }
            closeToolStripMenuItem.Enabled = true;
            foreach (var item in _reader.Results)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dGV_Results, ToReadbleString(item.Key.ToString()), item.Value.ReadableValue, item.Value.MrzCharacters);
                row.Tag = item.Value;
                if (!item.Value.IsValid)
                {
                    row.DefaultCellStyle.BackColor = Color.Red;
                    DataGridViewRow errorRow = new DataGridViewRow();
                    errorRow.CreateCells(dGV_Errors, ToReadbleString(item.Key.ToString()) + " Is Invalid");
                    dGV_Errors.Rows.Add(errorRow);
                }
                dGV_Results.Rows.Add(row);
            }

            if (_reader.Errors != MRTDErrors.NoError)
            {
                foreach (var value in Enum.GetValues(typeof(MRTDErrors)))
                {
                    if ((_reader.Errors & (MRTDErrors)value) == (MRTDErrors)value && (MRTDErrors)value != MRTDErrors.NoError)
                    {
                        DataGridViewRow row = new DataGridViewRow();
                        row.CreateCells(dGV_Errors, ToReadbleString(((MRTDErrors)value).ToString()));
                        row.Tag = ((MRTDErrors)value);
                        dGV_Errors.Rows.Add(row);
                    }
                }
            }
        }
Exemplo n.º 21
0
        private void InitializeTwain()
        {
            // Determine whether a TWAIN source is installed
#if LEADTOOLS_V19_OR_LATER
            _twainAvailable = TwainSession.IsAvailable(this.Handle);
#else
            _twainAvailable = TwainSession.IsAvailable(this);
#endif // #if LEADTOOLS_V19_OR_LATER

            if (_twainAvailable)
            {
                // Construct a new TwainSession object with default values
                _twainSession = new TwainSession();
                // Initialize the TWAIN session
                // This method must be called before calling any other methods that require a TWAIN session
#if LEADTOOLS_V19_OR_LATER
                _twainSession.Startup(this.Handle, "LEAD Technologies, Inc.", "LEAD Test Applications", "Version 1.0", "TWAIN Test Application", TwainStartupFlags.None);
#else
                _twainSession.Startup(this, "LEAD Technologies, Inc.", "LEAD Test Applications", "Version 1.0", "TWAIN Test Application", TwainStartupFlags.None);
#endif // #if LEADTOOLS_V19_OR_LATER

                // Set the AcquirePage Event handler
                _twainSession.AcquirePage += new EventHandler <TwainAcquirePageEventArgs>(_twain_AcquirePage);
            }
            else
            {
                _miTwainSelectSource.Enabled  = false;
                _miTwainAcquire.Enabled       = false;
                _miTemplateLEAD.Enabled       = false;
                _miTemplateShowCaps.Enabled   = false;
                _miTemplateShowErrors.Enabled = false;
            }

            _twainerrorList = new ArrayList();

            if (_mySettings._settings.TwainSelectedDevice != null)
            {
                try
                {
                    _twainSession.SelectSource(_mySettings._settings.TwainSelectedDevice);
                }
                catch {}
            }
        }
Exemplo n.º 22
0
        private bool GetCapFromRange(IntPtr intPtr)
        {
            bool   bret    = true;
            IntPtr tempPtr = TwainSession.GlobalLock(intPtr);

            try
            {
                TwRangeIntegerOrBool range = (TwRangeIntegerOrBool)Marshal.PtrToStructure(tempPtr, typeof(TwRangeIntegerOrBool));
                ArrayList            list  = new ArrayList();

                //fix32类型
                if (range.ItemType == TwType.Fix32)
                {
                    TwRangeFix32 rangeFix32 = (TwRangeFix32)Marshal.PtrToStructure(tempPtr, typeof(TwRangeFix32));
                    // 特殊处理
                    if (rangeFix32.CurrentValue.Frac == 0 && rangeFix32.StepSize.Frac == 0)
                    {
                        rangeFix32.MinValue.Frac = 0;
                    }
                    for (long val = (long)rangeFix32.MinValue.ToFloat(); val <= (long)rangeFix32.MaxValue.ToFloat(); val += (long)rangeFix32.StepSize.ToFloat())
                    {
                        list.Add(val);
                    }
                }
                //UINT8 UINT16 UINT32 INT8 INT16 INT32类型
                else
                {
                    list = twSession.GetRangeDataList(range.ItemType, range.MinValue, range.MaxValue, range.StepSize); //对数据列表进行赋值
                }
                capType   = range.ItemType;
                valueList = list;
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                TwainSession.GlobalUnlock(tempPtr);
            }
            return(bret);
        }
Exemplo n.º 23
0
 protected override ScanDevice PromptForDeviceInternal()
 {
     var session = new TwainSession(TwainAppId);
     session.Open();
     try
     {
         var ds = session.ShowSourceSelector();
         if (ds == null)
         {
             return null;
         }
         string deviceId = ds.Name;
         string deviceName = ds.Name;
         return new ScanDevice(deviceId, deviceName);
     }
     finally
     {
         session.Close();
     }
 }
    void Scan()
    {
        var identity = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetEntryAssembly());
        var twain    = new TwainSession(identity);

        twain.Open();
        twain.DataTransferred += (s, e) =>
        {
            var stream = e.GetNativeImageStream();
            var image  = Image.FromStream(stream);
            // Do things with the image...
        };
        var source = twain.First();

        Console.WriteLine($"Scanning from {source.Name}...");
        var openCode = source.Open();

        Console.WriteLine($"Open: {openCode}");
        source.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero);
    }
Exemplo n.º 25
0
        protected override ScanDevice PromptForDeviceInternal()
        {
            var session = new TwainSession(TwainAppId);

            session.Open();
            try
            {
                var ds = session.ShowSourceSelector();
                if (ds == null)
                {
                    return(null);
                }
                string deviceId   = ds.Name;
                string deviceName = ds.Name;
                return(new ScanDevice(deviceId, deviceName));
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 26
0
        private void DispClear()
        {
            txtYear.Text    = string.Empty;
            txtMonth.Text   = string.Empty;
            txtScanner.Text = string.Empty;
            txtTif.Text     = string.Empty;
            txtDat.Text     = string.Empty;
            cmbBkdels.Text  = string.Empty;

            if (TwainSession.IsAvailable(this))
            {
                btnScanner.Enabled = true;
                txtScanner.Enabled = true;
                txtScanner.Text    = _twainSession.SelectedSourceName();
            }
            else
            {
                btnScanner.Enabled = false;
                txtScanner.Enabled = false;
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="twainSession">扫描管理对象</param>
        /// <param name="capList">能力列表</param>
        /// <returns></returns>
        public bool Init(TwainSession twainSession, TwCap[] capList)
        {
            twSession    = twainSession;
            this.capList = capList;
            // 连接数据源
            if (!twainSession.OpenDS())
            {
                return(false);
            }

            capToControl = new Hashtable();
            controlList  = new Control[] {
                ICAP_IXferMech,
                CAP_DUPLEXENABLED,
                ICAP_PixelType,

                ICAP_XRESOLUTION,
                ICAP_PIXELFLAVOR,
                ICAP_THRESHOLD,
                ICAP_IMAGEFILEFORMAT,
                ICAP_COMPRESSION,

                ICAP_BRIGHTNESS,
                ICAP_CONTRAST,
                ICAP_AUTOMATICBORDERDETECTION,
                ICAP_AUTOMATICDESKEW,
                ICAP_AUTODISCARDBLANKPAGES,

                ECAP_PAPERSOURCE
            };
            // 设置控件和能力的对应关系
            for (int i = 0; i < controlList.Length; i++)
            {
                capToControl.Add(capList[i], controlList[i]);
            }

            // 获取扫描仪能力并初始化
            InitConfigUi();
            return(true);
        }
Exemplo n.º 28
0
        private static List <ScanDevice> InternalGetDeviceList(TwainImpl twainImpl)
        {
            PlatformInfo.Current.PreferNewDSM = twainImpl != TwainImpl.OldDsm;
            var session = new TwainSession(TwainAppId);

            session.Open();
            try
            {
                return(session.GetSources().Select(ds => new ScanDevice(ds.Name, ds.Name)).ToList());
            }
            finally
            {
                try
                {
                    session.Close();
                }
                catch (Exception e)
                {
                    Log.ErrorException("Error closing TWAIN session", e);
                }
            }
        }
Exemplo n.º 29
0
        private bool GetCapFromOneValue(IntPtr intPtr)
        {
            bool   bret    = true;
            IntPtr tempPtr = TwainSession.GlobalLock(intPtr);

            try
            {
                TwOneValueIntegerOrBool one = (TwOneValueIntegerOrBool)Marshal.PtrToStructure(tempPtr, typeof(TwOneValueIntegerOrBool));
                IntPtr p = new IntPtr(tempPtr.ToInt32() + Marshal.SizeOf(one) - Marshal.SizeOf(one.Item));
                capType   = one.ItemType;
                valueList = twSession.GetDataListFromPointer(one.ItemType, p, 1);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                TwainSession.GlobalUnlock(tempPtr);
            }
            return(bret);
        }
Exemplo n.º 30
0
        private bool GetCapFromArray(IntPtr intPtr)
        {
            bool   bret    = true;
            IntPtr tempPtr = TwainSession.GlobalLock(intPtr);

            try
            {
                TwArray array = (TwArray)Marshal.PtrToStructure(tempPtr, typeof(TwArray));
                IntPtr  p     = new IntPtr(tempPtr.ToInt32() + Marshal.SizeOf(array) - Marshal.SizeOf(array.ItemList));
                capType   = array.ItemType;
                valueList = twSession.GetDataListFromPointer(array.ItemType, p, array.NumItems);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                TwainSession.GlobalUnlock(tempPtr);
            }
            return(bret);
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            if (PlatformInfo.Current.IsApp64Bit)
            {
                Console.WriteLine("Platform: 64 bit");
            }
            else
            {
                Console.WriteLine("Platform: 32 bit");
            }
            var twain = new TwainSession(TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly()));

            twain.Open();
            Console.WriteLine("Listing TWAIN devices...");
            foreach (var device in twain)
            {
                Console.WriteLine($"Device: {device.Name}");
                Console.WriteLine($"\tId: {device.Id}");
                Console.WriteLine($"\tManufacturer: {device.Manufacturer}");
                Console.WriteLine($"\tProductFamily: {device.ProductFamily}");
                Console.WriteLine($"\tProtocolVersion: {device.ProtocolVersion}");
            }
            twain.Close();
        }
Exemplo n.º 32
0
        private void FormScan_Load(object sender, EventArgs e)
        {
            var appId = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly());

            session = new TwainSession(appId);
            session.TransferReady   += Session_TransferReady;
            session.DataTransferred += Session_DataTransferred;
            session.TransferError   += Session_TransferError;
            session.SourceDisabled  += Session_SourceDisabled;
            session.Open();

            foreach (DataSource ds in session)
            {
                cboxScanner.Items.Add(ds.Name);
            }

            cboxScanner.Text  = mSettings.ScannerName;
            cbDuplex.Checked  = mSettings.ScannerDuplex;
            cboxFlipType.Text = mSettings.ScannerFlipType;
            // FIXME: Allow BW pixel type
            //cboxPixelType.Text = mSettings.ScannerPixelType;
            cboxPixelType.Text    = "Color";
            cboxPixelType.Enabled = false;
        }
Exemplo n.º 33
0
        /// <summary>
        /// Initialize the application
        /// </summary>
        private void InitClass( )
        {
            // setup our caption
            Messager.Caption = "LEADTOOLS for .NET C# Twain Multipage Demo";
            Text             = Messager.Caption;

            // initialize the _viewer object
            _viewer           = new ImageViewer();
            _viewer.Dock      = DockStyle.Fill;
            _viewer.BackColor = Color.DarkGray;
            Controls.Add(_viewer);
            _viewer.BringToFront();

            // initialize the codecs object
            _codecs = new RasterCodecs();

            if (TwainSession.IsAvailable(this.Handle))
            {
                try
                {
                    // setup the Twain session object
                    _twainSession = new TwainSession();

                    //For 32-bit driver support in 64-bit applications, use the following TWAIN initialization method instead:
                    //_twainSession.Startup(this.Handle, "LEAD Technologies, Inc.", "LEAD Twain .NET", "Version 14", "LEADTools Twain test sample", TwainStartupFlags.UseThunkServer);

                    // start up the Twain session
                    _twainSession.Startup(this.Handle, "LEAD Technologies, Inc.", "LEAD Twain .NET", "Version 14", "LEADTools Twain test sample", TwainStartupFlags.None);
                }
                catch (TwainException ex)
                {
                    if (ex.Code == TwainExceptionCode.InvalidDll)
                    {
                        _miFileAcquire.Enabled        = false;
                        _miFileAcquireCleanup.Enabled = false;
                        _miFileSelectSource.Enabled   = false;
                        Messager.ShowError(this, "You have an old version of TWAINDSM.DLL. Please download latest version of this DLL from www.twain.org");
                    }
                    else
                    {
                        _miFileAcquire.Enabled        = false;
                        _miFileAcquireCleanup.Enabled = false;
                        _miFileSelectSource.Enabled   = false;
                        Messager.ShowError(this, ex);
                    }
                }
                catch (Exception ex)
                {
                    Messager.ShowError(this, ex);
                    _miFileAcquire.Enabled        = false;
                    _miFileAcquireCleanup.Enabled = false;
                    _miFileSelectSource.Enabled   = false;
                }
            }
            else
            {
                _miFileAcquire.Enabled        = false;
                _miFileAcquireCleanup.Enabled = false;
                _miFileSelectSource.Enabled   = false;
            }

            // setup the other variables
            _fileName   = string.Empty;
            _fileFormat = RasterImageFormat.Tif;
            _pageNo     = 0;

            UpdateMyControls();
            UpdateStatusBarText();
        }
Exemplo n.º 34
0
        protected override IEnumerable<IScannedImage> ScanInternal()
        {
            var session = new TwainSession(TwainAppId);
            var twainForm = formFactory.Create<FTwainGui>();
            var images = new List<IScannedImage>();
            Exception error = null;
            bool cancel = false;
            DataSource ds = null;

            session.TransferReady += (sender, eventArgs) =>
            {
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                using (var output = Image.FromStream(eventArgs.GetNativeImageStream()))
                {
                    double scaleFactor = 1;
                    if (!ScanSettings.UseNativeUI)
                    {
                        scaleFactor = ScanSettings.AfterScanScale.ToIntScaleFactor();
                    }

                    using (var result = ImageScaleHelper.ScaleImage(output, scaleFactor))
                    {
                        var bitDepth = output.PixelFormat == PixelFormat.Format1bppIndexed
                            ? ScanBitDepth.BlackWhite
                            : ScanBitDepth.C24Bit;
                        images.Add(scannedImageFactory.Create(result, bitDepth, ScanSettings.MaxQuality));
                    }
                }
            };
            session.TransferError += (sender, eventArgs) =>
            {
                error = eventArgs.Exception;
                cancel = true;
                twainForm.Close();
            };
            session.SourceDisabled += (sender, eventArgs) => twainForm.Close();

            twainForm.Shown += (sender, eventArgs) =>
            {
                try
                {
                    ReturnCode rc = session.Open(new WindowsFormsMessageLoopHook(DialogParent.Handle));
                    if (rc != ReturnCode.Success)
                    {
                        twainForm.Close();
                        return;
                    }
                    ds = session.FirstOrDefault(x => x.Name == ScanDevice.ID);
                    if (ds == null)
                    {
                        throw new DeviceNotFoundException();
                    }
                    rc = ds.Open();
                    if (rc != ReturnCode.Success)
                    {
                        twainForm.Close();
                        return;
                    }
                    ConfigureDS(ds);
                    var ui = ScanSettings.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI;
                    rc = ds.Enable(ui, true, twainForm.Handle);
                    if (rc != ReturnCode.Success)
                    {
                        twainForm.Close();
                    }
                }
                catch (Exception ex)
                {
                    error = ex;
                    twainForm.Close();
                }
            };

            twainForm.ShowDialog(DialogParent);

            if (ds != null && session.IsSourceOpen)
            {
                ds.Close();
            }
            if (session.IsDsmOpen)
            {
                session.Close();
            }

            if (error != null)
            {
                if (error is ScanDriverException)
                {
                    throw error;
                }
                throw new ScanDriverUnknownException(error);
            }

            return images;
        }
Exemplo n.º 35
0
 internal AudioNativeXfer(TwainSession session) : base(session)
 {
 }
Exemplo n.º 36
0
 internal Metrics(TwainSession session) : base(session)
 {
 }
Exemplo n.º 37
0
        public List<ScannedImage> Scan(IWin32Window dialogParent, bool activate, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams)
        {
            if (scanProfile.TwainImpl == TwainImpl.Legacy)
            {
                return Legacy.TwainApi.Scan(scanProfile, scanDevice, dialogParent, formFactory);
            }

            var session = new TwainSession(TwainAppId);
            var twainForm = formFactory.Create<FTwainGui>();
            var images = new List<ScannedImage>();
            Exception error = null;
            bool cancel = false;
            DataSource ds = null;

            session.TransferReady += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferReady");
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - DataTransferred");
                using (var output = Image.FromStream(eventArgs.GetNativeImageStream()))
                {
                    using (var result = ScannedImageHelper.PostProcessStep1(output, scanProfile))
                    {
                        if (blankDetector.ExcludePage(result, scanProfile))
                        {
                            return;
                        }

                        var bitDepth = output.PixelFormat == PixelFormat.Format1bppIndexed
                            ? ScanBitDepth.BlackWhite
                            : ScanBitDepth.C24Bit;
                        var image = new ScannedImage(result, bitDepth, scanProfile.MaxQuality, scanProfile.Quality);
                        ScannedImageHelper.PostProcessStep2(image, scanProfile);
                        if (scanParams.DetectPatchCodes)
                        {
                            foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode))
                            {
                                if (patchCodeInfo.ReturnCode == ReturnCode.Success)
                                {
                                    image.PatchCode = GetPatchCode(patchCodeInfo);
                                }
                            }
                        }
                        images.Add(image);
                    }
                }
            };
            session.TransferError += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferError");
                if (eventArgs.Exception != null)
                {
                    error = eventArgs.Exception;
                }
                else if (eventArgs.SourceStatus != null)
                {
                    Log.Error("TWAIN Transfer Error. Return code = {0}; condition code = {1}; data = {2}.",
                        eventArgs.ReturnCode, eventArgs.SourceStatus.ConditionCode, eventArgs.SourceStatus.Data);
                }
                else
                {
                    Log.Error("TWAIN Transfer Error. Return code = {0}.", eventArgs.ReturnCode);
                }
                cancel = true;
                twainForm.Close();
            };
            session.SourceDisabled += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - SourceDisabled");
                twainForm.Close();
            };

            twainForm.Shown += (sender, eventArgs) =>
            {
                if (activate)
                {
                    // TODO: Set this flag based on whether NAPS2 already has focus
                    // http://stackoverflow.com/questions/7162834/determine-if-current-application-is-activated-has-focus
                    // Or maybe http://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus
                    twainForm.Activate();
                }
                Debug.WriteLine("NAPS2.TW - TwainForm.Shown");
                try
                {
                    ReturnCode rc = session.Open(new WindowsFormsMessageLoopHook(dialogParent.Handle));
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not open session - {0}", rc);
                        twainForm.Close();
                        return;
                    }
                    ds = session.FirstOrDefault(x => x.Name == scanDevice.ID);
                    if (ds == null)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not find DS - DS count = {0}", session.Count());
                        throw new DeviceNotFoundException();
                    }
                    rc = ds.Open();
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not open DS - {0}", rc);
                        twainForm.Close();
                        return;
                    }
                    ConfigureDS(ds, scanProfile, scanParams);
                    var ui = scanProfile.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI;
                    Debug.WriteLine("NAPS2.TW - Enabling DS");
                    rc = ds.Enable(ui, true, twainForm.Handle);
                    Debug.WriteLine("NAPS2.TW - Enable finished");
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Enable failed - {0}, rc");
                        twainForm.Close();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - Error");
                    error = ex;
                    twainForm.Close();
                }
            };

            Debug.WriteLine("NAPS2.TW - Showing TwainForm");
            twainForm.ShowDialog(dialogParent);
            Debug.WriteLine("NAPS2.TW - TwainForm closed");

            if (ds != null && session.IsSourceOpen)
            {
                Debug.WriteLine("NAPS2.TW - Closing DS");
                ds.Close();
            }
            if (session.IsDsmOpen)
            {
                Debug.WriteLine("NAPS2.TW - Closing session");
                session.Close();
            }

            if (error != null)
            {
                Debug.WriteLine("NAPS2.TW - Throwing error - {0}", error);
                if (error is ScanDriverException)
                {
                    throw error;
                }
                throw new ScanDriverUnknownException(error);
            }

            return images;
        }
Exemplo n.º 38
0
        protected override IEnumerable<IScannedImage> ScanInternal()
        {
            if (ScanProfile.TwainImpl == TwainImpl.Legacy)
            {
                return Legacy.TwainApi.Scan(ScanProfile, ScanDevice, DialogParent, formFactory, scannedImageFactory);
            }

            var session = new TwainSession(TwainAppId);
            var twainForm = formFactory.Create<FTwainGui>();
            var images = new List<IScannedImage>();
            Exception error = null;
            bool cancel = false;
            DataSource ds = null;

            session.TransferReady += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferReady");
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - DataTransferred");
                using (var output = Image.FromStream(eventArgs.GetNativeImageStream()))
                {
                    using (var result = ScannedImageHelper.PostProcessStep1(output, ScanProfile))
                    {
                        var bitDepth = output.PixelFormat == PixelFormat.Format1bppIndexed
                            ? ScanBitDepth.BlackWhite
                            : ScanBitDepth.C24Bit;
                        var image = scannedImageFactory.Create(result, bitDepth, ScanProfile.MaxQuality, ScanProfile.Quality);
                        ScannedImageHelper.PostProcessStep2(image, ScanProfile);
                        if (ScanParams.DetectPatchCodes)
                        {
                            foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode))
                            {
                                if (patchCodeInfo.ReturnCode == ReturnCode.Success)
                                {
                                    image.PatchCode = GetPatchCode(patchCodeInfo);
                                }
                            }
                        }
                        images.Add(image);
                    }
                }
            };
            session.TransferError += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferError");
                if (eventArgs.Exception != null)
                {
                    error = eventArgs.Exception;
                }
                else if (eventArgs.SourceStatus != null)
                {
                    Log.Error("TWAIN Transfer Error. Return code = {0}; condition code = {1}; data = {2}.",
                        eventArgs.ReturnCode, eventArgs.SourceStatus.ConditionCode, eventArgs.SourceStatus.Data);
                }
                else
                {
                    Log.Error("TWAIN Transfer Error. Return code = {0}.", eventArgs.ReturnCode);
                }
                cancel = true;
                twainForm.Close();
            };
            session.SourceDisabled += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - SourceDisabled");
                twainForm.Close();
            };

            twainForm.Shown += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TwainForm.Shown");
                try
                {
                    ReturnCode rc = session.Open(new WindowsFormsMessageLoopHook(DialogParent.Handle));
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not open session - {0}", rc);
                        twainForm.Close();
                        return;
                    }
                    ds = session.FirstOrDefault(x => x.Name == ScanDevice.ID);
                    if (ds == null)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not find DS - DS count = {0}", session.Count());
                        throw new DeviceNotFoundException();
                    }
                    rc = ds.Open();
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not open DS - {0}", rc);
                        twainForm.Close();
                        return;
                    }
                    ConfigureDS(ds);
                    var ui = ScanProfile.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI;
                    Debug.WriteLine("NAPS2.TW - Enabling DS");
                    rc = ds.Enable(ui, true, twainForm.Handle);
                    Debug.WriteLine("NAPS2.TW - Enable finished");
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Enable failed - {0}, rc");
                        twainForm.Close();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - Error");
                    error = ex;
                    twainForm.Close();
                }
            };

            Debug.WriteLine("NAPS2.TW - Showing TwainForm");
            twainForm.ShowDialog(DialogParent);
            Debug.WriteLine("NAPS2.TW - TwainForm closed");

            if (ds != null && session.IsSourceOpen)
            {
                Debug.WriteLine("NAPS2.TW - Closing DS");
                ds.Close();
            }
            if (session.IsDsmOpen)
            {
                Debug.WriteLine("NAPS2.TW - Closing session");
                session.Close();
            }

            if (error != null)
            {
                Debug.WriteLine("NAPS2.TW - Throwing error - {0}", error);
                if (error is ScanDriverException)
                {
                    throw error;
                }
                throw new ScanDriverUnknownException(error);
            }

            return images;
        }
Exemplo n.º 39
0
        public override List<Image> Scan()
        {
            Console.WriteLine("Scan Twain");
            lesImagesNum.Clear();
            // can use the utility method to create appId or make one yourself
            var appId = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly());

            // new it up and handle events
            session = new TwainSession(appId);

            session.TransferReady += session_TransferReady;
            session.DataTransferred += session_DataTransferred;
            session.SourceDisabled += session_SourceDisable;

            // finally open it
            session.Open();
            var t = session.GetEnumerator();

            Console.WriteLine(t.ToString());
            while (t.MoveNext())
            {
                Console.WriteLine(t.ConvertToString());
            }

            // choose and open the first source found
            // note that TwainSession implements IEnumerable<DataSource> so we can use this extension method.
            IEnumerable<DataSource> lesSources = session.GetSources();
            Console.WriteLine("Nb Source : " + session.Count());
            myDS = session.FirstOrDefault();
            myDS.Open();

            // All low-level triplet operations are defined through these properties.
            // If the operation you want is not available, that most likely means
            // it's not for consumer use or it's been abstracted away with an equivalent API in this lib.
            //myDS.DGControl;
            //myDS.DGImage.;

            // The wrapper has many methods that corresponds to the TWAIN capability triplet msgs like
            // GetValues(), GetCurrent(), GetDefault(), SetValue(), etc.
            // (see TWAIN spec for reference)

            // This example sets pixel type of scanned image to BW and
            // IPixelType is the wrapper property on the data source.
            // The name of the wrapper property is the same as the CapabilityId enum.
            PixelType typeCouleur = PixelType.Gray;

            if (myDS.Capabilities.ICapPixelType.CanSet &&
                myDS.Capabilities.ICapPixelType.GetValues().Contains(typeCouleur))
            {
                myDS.Capabilities.ICapPixelType.SetValue(typeCouleur);
            }

            //Même chose avec le DPI
            TWFix32 DPI = MainWindow.numerisationDPI;

            if(myDS.Capabilities.ICapXResolution.CanSet &&
                myDS.Capabilities.ICapXResolution.GetValues().Contains(DPI))
            {
                myDS.Capabilities.ICapXResolution.SetValue(DPI);
            }

            if (myDS.Capabilities.ICapYResolution.CanSet &&
                myDS.Capabilities.ICapYResolution.GetValues().Contains(DPI))
            {
                myDS.Capabilities.ICapYResolution.SetValue(DPI);
            }

            myDS.Enable(SourceEnableMode.ShowUI, false, System.IntPtr.Zero);

            EventWaitHandle session_SourceDisable_Wait = new EventWaitHandle(false, EventResetMode.AutoReset);
            session_SourceDisable_Wait.WaitOne();
            return lesImagesNum;
        }