private void _twain32_AcquireError(object sender, Twain32.AcquireErrorEventArgs e)
 {
     if (MessageBox.Show(e.Exception.Message, "Error!", MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes)
     {
         _twain32?.CloseDSM();
         _twain32?.CloseDataSource();
         _twain32.Dispose();
         Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_NOT_ENOUGH_MEMORY;
         this.Close();
     }
 }
        private void _scannersListPreview_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                _twain32?.Dispose();
                _twain32 = new Twain32
                {
                    ShowUI         = true,
                    IsTwain2Enable = true
                };

                _twain32.OpenDSM();
                _twain32.SourceIndex = Scanners.IndexOf(SelectedScanner);
                _twain32.OpenDataSource();

                _twain32.EndXfer          += _twain32_EndXfer;
                _twain32.AcquireCompleted += _twain32_AcquireCompleted;
                _twain32.AcquireError     += _twain32_AcquireError;
                _twain32.MemXferEvent     += _twain32_MemXferEvent;

                _twain32.Acquire();

                if (_scannedImage != null)
                {
                    SaveImage();
                }

                Environment.ExitCode = (int)ExitCodes.ExitCode.SUCCESS;

                CustomMessageBox.Show($"Save photo: {Path.GetFileName(_filePath)}\n{_destinationPath}", "Succes", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                var messagebox = CustomMessageBox.Show(ex.Message, "Scanner Error!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error);
                if (messagebox == System.Windows.Forms.DialogResult.Yes)
                {
                    Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_DEVICE_UNREACHABLE;
                }
            }
            finally
            {
                _twain32?.CloseDSM();
                _twain32?.CloseDataSource();
                _twain32.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                this.Close();
            }
        }
Beispiel #3
0
        private void cbxScanner_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _twain.CloseDataSource();
                _twain.SourceIndex = cbxScanner.SelectedIndex;
                _twain.OpenDataSource();
            }
            catch (TwainException ex)
            {
                LogFactory.CreateLog().LogError(ex);
                MessageBox.Show(ErrorMessages.ScannerCannotByActivate, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            DisplayColorFormats();
            DisplayResolutions();
        }
Beispiel #4
0
 private void _twain_TwainStateChanged(object sender, Twain32.TwainStateEventArgs e)
 {
     logger.Debug("Handle TwainState");
     if ((e.TwainState & Twain32.TwainStateFlag.DSEnabled) == 0 && this._isEnable)
     {
         this._isEnable = false;
         // <<< scaning finished (or closed)
         if (stream != null)
         {
             FinishImageTransfer();
         }
         logger.Debug("Сканирование закончено...");
         _twain32.CloseDataSource();
     }
     this._isEnable = (e.TwainState & Twain32.TwainStateFlag.DSEnabled) != 0;
     logger.Debug($"Handle TwainState end");
 }
        public IEnumerable <HWDeviceDesciption> GetDevices()
        {
            var twain       = new Twain32();
            var isDsmOpened = false;

            try
            {
                //twain.OpenDataSource();
                isDsmOpened = twain.OpenDSM();
                if (twain.IsTwain2Supported)
                {
                    twain.IsTwain2Enable = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            if (isDsmOpened)
            {
                for (int i = 0; i < twain.SourcesCount; i++)
                {
                    yield return(new HWDeviceDesciption
                    {
                        Device = DeviceType.Scanner,
                        Name = twain.GetSourceProductName(i),
                        DeviceId = i.ToString()
                    });
                }
            }

            if (twain != null)
            {
                twain.CloseDataSource();
                twain.CloseDSM();
                twain.Dispose();
            }

            yield break;
        }
        private void LoadParametes()
        {
            try
            {
                _twain32 = new Twain32
                {
                    ShowUI         = true,
                    IsTwain2Enable = true
                };
                _twain32.OpenDSM();

                #region GetScanners

                for (int i = 0; i < _twain32.SourcesCount; i++)
                {
                    _scanners.Add(_twain32.GetSourceProductName(i));
                }
                #endregion GetScanners

                if (Scanners.Count > 0)
                {
                    SelectedScanner = Scanners.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                var messagebox = CustomMessageBox.Show(ex.Message, "Error!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error);
                if (messagebox == System.Windows.Forms.DialogResult.Yes)
                {
                    _twain32?.CloseDSM();
                    _twain32?.CloseDataSource();
                    _twain32.Dispose();
                    Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_DEVICE_UNREACHABLE;
                    this.Close();
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// start scanning
        /// </summary>
        public void Start()
        {
            //logger.Debug("Start");
            try
            {
                if (!twain.OpenDSM())
                {
                    logger.Debug("Не могу найти сканер");
                    Error(this, new HWErrorEventArgs("Не могу найти сканер"));
                    return;
                }
                if (!twain.IsTwain2Supported)
                {
                    twain.CloseDSM();
                    twain.IsTwain2Enable = false;
                    twain.OpenDSM();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                //  TODO: add logging
                Error(this, new HWErrorEventArgs(ex.Message));
                return;
            }
            if (selectedScanner.DeviceId != "")
            {
                twain.SourceIndex = int.Parse(selectedScanner.DeviceId);
            }
            else
            {
                logger.Debug("selectedScanner.DeviceId == String.Empty ");
            }
            try
            {
                if (!twain.OpenDataSource())
                {
                    logger.Debug("Не могу установить соединение со сканером");
                    Error(this, new HWErrorEventArgs("Не могу установить соединение со сканером"));
                    return;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                //  TODO: add logging
                Error(this, new HWErrorEventArgs(ex.Message));
                return;
            }

            int dpiResolution = 200;

            if (System.Configuration.ConfigurationManager.AppSettings["ScannerDpi"] != null)
            {
                dpiResolution = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ScannerDpi"]);
            }



            setPixelType();
            float Height, Weight;
            int   X, Y;

            //ScanWidht
            try
            {
                Height = float.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanHeight"], System.Globalization.CultureInfo.InvariantCulture) / (float)2.54;
                Weight = float.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanWidht"], System.Globalization.CultureInfo.InvariantCulture) / (float)2.54;
                X      = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanStartPointX"]);
                Y      = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanStartPointY"]);
            }
            catch (Exception ex)
            {
                Height = 6.6462525f;
                Weight = 6.6462525f;
                X      = 0;
                Y      = 0;
                logger.Error(ex);
            }

            //задаем область сканирования в точке 0 и размером A6
            IsLayoutSet = SetImageLayOut(new RectangleF(new PointF(X, Y), new SizeF(Weight, Height)));
            //если не смогли задать область сканируем не выше 300 dpi
            if (IsLayoutSet)
            {
                SetResolutions(dpiResolution);
            }
            else
            {
                SetResolutions(300);
            }

            try
            {
                twain.Acquire();
            }
            catch (Exception ex)
            {
                twain.CloseDSM();
                twain.CloseDataSource();

                logger.Error(ex);
                //  TODO: add logging
                Error(this, new HWErrorEventArgs(ex.Message));
                return;
            }
        }
Beispiel #8
0
        private void scanCmb_SelectedIndexChanged(object sender, EventArgs e)
        {
            //读取扫描仪配置
            if (!string.IsNullOrEmpty(hand.ReadConfig("twName")))
            {
                string twname = hand.ReadConfig("twName");
                int    j      = -1;
                for (int i = 0; i < scanCmb.Items.Count; i++)
                {
                    if (scanCmb.Items[i].ToString().Equals(twname))
                    {
                        j = i;
                        break;
                    }
                }
                if (j < 0)
                {
                    MessageBox.Show("在本机没有找到对应的扫描仪信息,请重新设置扫描仪!");
                }
                else
                {
                    try
                    {
                        mTwain.SourceIndex = j;
                        mTwain.OpenDataSource();
                        var           _resolutions = mTwain.Capabilities.XResolution.Get();
                        List <string> dpilst       = new List <string>();
                        for (var i = 0; i < _resolutions.Count; i++)
                        {
                            dpilst.Add(_resolutions[i].ToString());
                        }
                        dpiCmb.DataSource = dpilst;
                        mTwain.CloseDataSource();

                        //读取扫描仪DPI配置
                        if (!string.IsNullOrEmpty(hand.ReadConfig("dpi")))
                        {
                            string dpi = hand.ReadConfig("dpi");
                            int    dj  = -1;
                            for (int di = 0; di < dpiCmb.Items.Count; di++)
                            {
                                if (dpiCmb.Items[di].ToString().Equals(dpi))
                                {
                                    dj = di;
                                    break;
                                }
                            }
                            if (dj < 0)
                            {
                                MessageBox.Show("在本机没有找到扫描仪预设的DPI值,请重新设置DPI值!");
                            }
                            else
                            {
                                this.dpiCmb.SelectedIndex = dj;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Logger.Error("读取扫描仪信息失败!");
                        MessageBox.Show("读取扫描仪信息失败!,请重新设置扫描仪!");
                    }
                }
            }
        }