public void AddItem(ScanDevice sd)
        {
            var pIns = liMain.Count;

            liMain.Add(sd);
            NotifyItemInserted(pIns);
        }
Exemple #2
0
        private void ChooseDevice(string driverName)
        {
            var driver = driverFactory.Create(driverName);

            try
            {
                driver.DialogParent = this;
                ScanDevice device = driver.PromptForDevice();
                if (device != null)
                {
                    if (string.IsNullOrEmpty(txtName.Text) ||
                        CurrentDevice != null && CurrentDevice.Name == txtName.Text)
                    {
                        txtName.Text = device.Name;
                    }
                    CurrentDevice = device;
                }
            }
            catch (ScanDriverException e)
            {
                if (e is ScanDriverUnknownException)
                {
                    Log.ErrorException(e.Message, e.InnerException);
                }
                errorOutput.DisplayError(e.Message);
            }
        }
Exemple #3
0
 private void txtDevice_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.Delete)
     {
         CurrentDevice = null;
     }
 }
Exemple #4
0
 private void rdWIA_CheckedChanged(object sender, EventArgs e)
 {
     if (!suppressChangeEvent)
     {
         ScanSettings.Device = null;
         CurrentDevice       = null;
         UpdateEnabledControls();
     }
 }
Exemple #5
0
        public WiaBackgroundEventLoop(ExtendedScanSettings settings, ScanDevice scanDevice)
        {
            this.settings   = settings;
            this.scanDevice = scanDevice;

            thread = new Thread(RunEventLoop);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            // Wait for the thread to initialize the background form and event loop
            initWaiter.WaitOne();
        }
Exemple #6
0
 private void btnSelect_Click(object sender, EventArgs e)
 {
     if (listboxDevices.SelectedItem == null)
     {
         listboxDevices.Focus();
         return;
     }
     DialogResult   = DialogResult.OK;
     SelectedDevice = ((ScanDevice)listboxDevices.SelectedItem);
     Close();
 }
        public WiaBackgroundEventLoop(ScanProfile profile, ScanDevice scanDevice, ThreadFactory threadFactory)
        {
            this.profile    = profile;
            this.scanDevice = scanDevice;

            thread = threadFactory.CreateThread(RunEventLoop);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            // Wait for the thread to initialize the background form and event loop
            initWaiter.WaitOne();
        }
Exemple #8
0
        public bool Start(ScanProfile scanProfile, ScanDevice scanDevice, ScanParams scanParams, IWin32Window dialogParent, ScannedImageSource.Concrete source)
        {
            ScanProfile   = scanProfile;
            ScanDevice    = scanDevice;
            ScanParams    = scanParams;
            DialogParent  = dialogParent;
            ProgressTitle = ScanDevice.Name;
            Status        = new OperationStatus
            {
                StatusText = ScanProfile.PaperSource == ScanSource.Glass
                    ? MiscResources.AcquiringData
                    : string.Format(MiscResources.ScanProgressPage, 1),
                MaxProgress  = 1000,
                ProgressType = OperationProgressType.BarOnly
            };

            // TODO: NoUI
            // TODO: Test native UI in console behaviour (versus older behaviour)
            // TODO: What happens if you close FDesktop while a batch scan is in progress?

            RunAsync(() =>
            {
                try
                {
                    try
                    {
                        smoothProgress.Reset();
                        Scan(source);
                    }
                    catch (WiaException e)
                    {
                        WiaScanErrors.ThrowDeviceError(e);
                    }

                    return(true);
                }
                catch (Exception e)
                {
                    // Don't call InvokeError; the driver will do the actual error handling
                    ScanException = e;
                    return(false);
                }
                finally
                {
                    smoothProgress.Reset();
                }
            });

            return(true);
        }
Exemple #9
0
        /// <summary>
        /// 初始扫码枪
        /// </summary>
        private void InitScanDevice()
        {
            string          strPath = AppDomain.CurrentDomain.BaseDirectory + "Data\\Scan.txt";
            List <string[]> lstScan = GetCSVData(strPath);

            if (lstScan.Count == 0)
            {
                return;
            }
            foreach (var scan in lstScan)
            {
                ScanDevice scanDevice = new ScanDevice(Convert.ToInt32(scan[0]), scan[1], scan[2], scan[3], Convert.ToInt32(scan[4]), 9004);
                ScanDevices.Add(scanDevice);
            }
        }
 public async Task TwainScan(ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams, IntPtr hwnd)
 {
     try
     {
         await Task.Factory.StartNew(() =>
         {
             var imagePathDict = new Dictionary <ScannedImage, string>();
             twainWrapper.Scan(hwnd == IntPtr.Zero ? null : new Win32Window(hwnd), scanDevice, scanProfile, scanParams, twainScanCts.Token,
                               new WorkerImageSource(Callback, imagePathDict), (img, _, path) => imagePathDict.Add(img, path));
         }, TaskCreationOptions.LongRunning);
     }
     catch (ScanDriverException e)
     {
         throw new FaultException <ScanDriverExceptionDetail>(new ScanDriverExceptionDetail(e));
     }
 }
Exemple #11
0
 public static List<ScannedImage> Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory)
 {
     var tw = new Twain();
     if (!tw.Init(pForm.Handle))
     {
         throw new DeviceNotFoundException();
     }
     if (!tw.SelectByName(device.ID))
     {
         throw new DeviceNotFoundException();
     }
     var form = formFactory.Create<FTwainGui>();
     var mf = new TwainMessageFilter(settings, tw, form);
     form.ShowDialog(pForm);
     return mf.Bitmaps;
 }
 public void UpdateItem(int i, ScanDevice sd)
 {
     if (sd.status != Constants.DEVICE_STAT_NONE)
     {
         if (i != lastItemExp && lastItemExp >= 0)
         {
             var a = liMain[lastItemExp];
             a.status            = Constants.DEVICE_STAT_NONE;
             liMain[lastItemExp] = a;
             NotifyItemChanged(lastItemExp);
         }
         lastItemExp = i;
     }
     liMain[i] = sd;
     NotifyItemChanged(i);
 }
Exemple #13
0
        public static List <ScannedImage> Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory)
        {
            var tw = new Twain();

            if (!tw.Init(pForm.Handle))
            {
                throw new DeviceNotFoundException();
            }
            if (!tw.SelectByName(device.ID))
            {
                throw new DeviceNotFoundException();
            }
            var form = formFactory.Create <FTwainGui>();
            var mf   = new TwainMessageFilter(settings, tw, form);

            form.ShowDialog(pForm);
            return(mf.Bitmaps);
        }
Exemple #14
0
 public static Device GetDevice(ScanDevice scanDevice)
 {
     DeviceManager manager = new DeviceManagerClass();
     foreach (DeviceInfo info in manager.DeviceInfos)
     {
         if (info.DeviceID == scanDevice.ID)
         {
             try
             {
                 return info.Connect();
             }
             catch (COMException e)
             {
                 ThrowDeviceError(e);
             }
         }
     }
     throw new DeviceNotFoundException();
 }
Exemple #15
0
 public static Device GetDevice(ScanDevice scanDevice)
 {
     DeviceManager manager = new DeviceManagerClass();
     foreach (DeviceInfo info in manager.DeviceInfos)
     {
         if (info.DeviceID == scanDevice.ID)
         {
             try
             {
                 return info.Connect();
             }
             catch (COMException e)
             {
                 ThrowDeviceError(e);
             }
         }
     }
     throw new DeviceNotFoundException();
 }
Exemple #16
0
        private void MiReScan_Click(object sender, RoutedEventArgs e)
        {
            MenuItem    mi       = sender as MenuItem;
            ContextMenu ctxMenu  = mi.Parent as ContextMenu;
            DataGrid    dataGrid = ctxMenu.PlacementTarget as DataGrid;

            if (dataGrid.SelectedItems != null && dataGrid.SelectedItems.Count > 0)
            {
                foreach (var item in dataGrid.SelectedItems)
                {
                    ScanDevice scan = item as ScanDevice;
                    var        stop = viewModel.Source.StopDevices.FirstOrDefault(p => p.Scan_Device_No == scan.NO && p.STATUS == 1);
                    if (stop == null || string.IsNullOrEmpty(stop.Scan_Device_No))
                    {
                        continue;
                    }
                    viewModel.TriggerScan(stop);
                }
            }
        }
Exemple #17
0
 public void Scan(IWin32Window dialogParent, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams,
                  CancellationToken cancelToken, ScannedImageSource.Concrete source, Action <ScannedImage, ScanParams, string> runBackgroundOcr)
 {
     try
     {
         InternalScan(scanProfile.TwainImpl, dialogParent, scanDevice, scanProfile, scanParams, cancelToken, source, runBackgroundOcr);
     }
     catch (DeviceNotFoundException)
     {
         if (scanProfile.TwainImpl == TwainImpl.Default)
         {
             // Fall back to OldDsm in case of no devices
             // This is primarily for Citrix support, which requires using twain_32.dll for TWAIN passthrough
             InternalScan(TwainImpl.OldDsm, dialogParent, scanDevice, scanProfile, scanParams, cancelToken, source, runBackgroundOcr);
         }
         else
         {
             throw;
         }
     }
 }
Exemple #18
0
        private void OnScanDeviceFound(Discover.DeviceInfo deviceinfo)
        {
            Application.SynchronizationContext.Post(_ =>
            {
                try
                {
                    var sd        = new ScanDevice();
                    sd.id         = ViewHelper.CurrentTimeMillis();
                    sd.title1     = deviceinfo.Model;
                    sd.title2     = deviceinfo.IpAddress;
                    sd.scanDevice = deviceinfo;

                    rvAdapter.AddItem(sd);

                    vfMain.DisplayedChild = 2;
                }
                catch (Exception e)
                {
                }
            }, null);
        }
Exemple #19
0
        public static void Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory, ScannedImageSource.Concrete source)
        {
            var tw = new Twain();

            if (!tw.Init(pForm.Handle))
            {
                throw new DeviceNotFoundException();
            }
            if (!tw.SelectByName(device.ID))
            {
                throw new DeviceNotFoundException();
            }
            var form = formFactory.Create <FTwainGui>();
            var mf   = new TwainMessageFilter(settings, tw, form);

            form.ShowDialog(pForm);
            foreach (var b in mf.Bitmaps)
            {
                source.Put(b);
            }
        }
Exemple #20
0
        public static void Scan(ScanProfile settings, ScanDevice device, IWin32Window pForm, IFormFactory formFactory, ScannedImageSource.Concrete source)
        {
            var tw           = new Twain();
            var windowHandle = (Invoker.Current as Form)?.Handle ?? pForm.Handle;

            if (!tw.Init(windowHandle))
            {
                throw new DeviceNotFoundException();
            }
            if (!tw.SelectByName(device.Id))
            {
                throw new DeviceNotFoundException();
            }
            var form = Invoker.Current.InvokeGet(formFactory.Create <FTwainGui>);
            var mf   = new TwainMessageFilter(settings, tw, form);

            Invoker.Current.Invoke(() => form.ShowDialog(pForm));
            foreach (var b in mf.Bitmaps)
            {
                source.Put(b);
            }
        }
Exemple #21
0
 public static Device GetDevice(ScanDevice scanDevice)
 {
     DeviceManager manager = new DeviceManagerClass();
     foreach (DeviceInfo info in manager.DeviceInfos)
     {
         if (info.DeviceID == scanDevice.ID)
         {
             try
             {
                 return info.Connect();
             }
             catch (COMException e)
             {
                 if ((uint)e.ErrorCode == Errors.OFFLINE)
                 {
                     throw new DeviceOfflineException();
                 }
                 throw new ScanDriverUnknownException(e);
             }
         }
     }
     throw new DeviceNotFoundException();
 }
Exemple #22
0
        public static Device GetDevice(ScanDevice scanDevice)
        {
            DeviceManager manager = new DeviceManagerClass();

            foreach (DeviceInfo info in manager.DeviceInfos)
            {
                if (info.DeviceID == scanDevice.ID)
                {
                    try
                    {
                        return(info.Connect());
                    }
                    catch (COMException e)
                    {
                        if ((uint)e.ErrorCode == Errors.OFFLINE)
                        {
                            throw new DeviceOfflineException();
                        }
                        throw new ScanDriverUnknownException(e);
                    }
                }
            }
            throw new DeviceNotFoundException();
        }
Exemple #23
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));
            }

            PlatformInfo.Current.PreferNewDSM = scanProfile.TwainImpl != TwainImpl.OldDsm;
            var        session   = new TwainSession(TwainAppId);
            var        twainForm = formFactory.Create <FTwainGui>();
            var        images    = new List <ScannedImage>();
            Exception  error     = null;
            bool       cancel    = false;
            DataSource ds        = null;

            int pageNumber = 0;

            session.TransferReady += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferReady");
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                try
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred");
                    pageNumber++;
                    using (var output = scanProfile.TwainImpl == TwainImpl.MemXfer
                                        ? GetBitmapFromMemXFer(eventArgs.MemoryData, eventArgs.ImageInfo)
                                        : 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);
                            image.SetThumbnail(thumbnailRenderer.RenderThumbnail(result));
                            if (scanParams.DetectPatchCodes)
                            {
                                foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode))
                                {
                                    if (patchCodeInfo.ReturnCode == ReturnCode.Success)
                                    {
                                        image.PatchCode = GetPatchCode(patchCodeInfo);
                                    }
                                }
                            }
                            scannedImageHelper.PostProcessStep2(image, result, scanProfile, scanParams, pageNumber);
                            images.Add(image);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred - Error");
                    error  = ex;
                    cancel = true;
                    twainForm.Close();
                }
            };
            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);
        }
Exemple #24
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;
        }
Exemple #25
0
 public List <RecoveryIndexImage> TwainScan(int recoveryFileNumber, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams)
 {
     RecoveryImage.RecoveryFileNumber = recoveryFileNumber;
     return(twainWrapper.Scan(ParentForm, true, scanDevice, scanProfile, scanParams).Select(x => x.RecoveryIndexImage).ToList());
 }
Exemple #26
0
        private void InternalScan(TwainImpl twainImpl, IWin32Window dialogParent, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams,
                                  CancellationToken cancelToken, ScannedImageSource.Concrete source, Action <ScannedImage, ScanParams, string> runBackgroundOcr)
        {
            if (dialogParent == null)
            {
                dialogParent = new BackgroundForm();
            }
            if (twainImpl == TwainImpl.Legacy)
            {
                Legacy.TwainApi.Scan(scanProfile, scanDevice, dialogParent, formFactory, source);
                return;
            }

            PlatformInfo.Current.PreferNewDSM = twainImpl != TwainImpl.OldDsm;
            var        session    = new TwainSession(TwainAppId);
            var        twainForm  = Invoker.Current.InvokeGet(() => scanParams.NoUI ? null : formFactory.Create <FTwainGui>());
            Exception  error      = null;
            bool       cancel     = false;
            DataSource ds         = null;
            var        waitHandle = new AutoResetEvent(false);

            int pageNumber = 0;

            session.TransferReady += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - TransferReady");
                if (cancel)
                {
                    eventArgs.CancelAll = true;
                }
            };
            session.DataTransferred += (sender, eventArgs) =>
            {
                try
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred");
                    pageNumber++;
                    using (var output = twainImpl == TwainImpl.MemXfer
                                        ? GetBitmapFromMemXFer(eventArgs.MemoryData, eventArgs.ImageInfo)
                                        : 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);
                            if (scanParams.DetectPatchCodes)
                            {
                                foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode))
                                {
                                    if (patchCodeInfo.ReturnCode == ReturnCode.Success)
                                    {
                                        image.PatchCode = GetPatchCode(patchCodeInfo);
                                    }
                                }
                            }
                            scannedImageHelper.PostProcessStep2(image, result, scanProfile, scanParams, pageNumber);
                            string tempPath = scannedImageHelper.SaveForBackgroundOcr(result, scanParams);
                            runBackgroundOcr(image, scanParams, tempPath);
                            source.Put(image);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - DataTransferred - Error");
                    error  = ex;
                    cancel = true;
                    StopTwain();
                }
            };
            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;
                StopTwain();
            };
            session.SourceDisabled += (sender, eventArgs) =>
            {
                Debug.WriteLine("NAPS2.TW - SourceDisabled");
                StopTwain();
            };

            void StopTwain()
            {
                waitHandle.Set();
                if (!scanParams.NoUI)
                {
                    Invoker.Current.Invoke(() => twainForm.Close());
                }
            }

            void InitTwain()
            {
                try
                {
                    var        windowHandle = (Invoker.Current as Form)?.Handle;
                    ReturnCode rc           = windowHandle != null?session.Open(new WindowsFormsMessageLoopHook(windowHandle.Value)) : session.Open();

                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Could not open session - {0}", rc);
                        StopTwain();
                        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);
                        StopTwain();
                        return;
                    }
                    ConfigureDS(ds, scanProfile, scanParams);
                    var ui = scanProfile.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI;
                    Debug.WriteLine("NAPS2.TW - Enabling DS");
                    rc = scanParams.NoUI ? ds.Enable(ui, true, windowHandle ?? IntPtr.Zero) : ds.Enable(ui, true, twainForm.Handle);
                    Debug.WriteLine("NAPS2.TW - Enable finished");
                    if (rc != ReturnCode.Success)
                    {
                        Debug.WriteLine("NAPS2.TW - Enable failed - {0}, rc");
                        StopTwain();
                    }
                    else
                    {
                        cancelToken.Register(() =>
                        {
                            Debug.WriteLine("NAPS2.TW - User Cancel");
                            cancel = true;
                            session.ForceStepDown(5);
                        });
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("NAPS2.TW - Error");
                    error = ex;
                    StopTwain();
                }
            }

            if (!scanParams.NoUI)
            {
                twainForm.Shown  += (sender, eventArgs) => { InitTwain(); };
                twainForm.Closed += (sender, args) => waitHandle.Set();
            }

            if (scanParams.NoUI)
            {
                Debug.WriteLine("NAPS2.TW - Init with no form");
                Invoker.Current.Invoke(InitTwain);
            }
            else if (!scanParams.Modal)
            {
                Debug.WriteLine("NAPS2.TW - Init with non-modal form");
                Invoker.Current.Invoke(() => twainForm.Show(dialogParent));
            }
            else
            {
                Debug.WriteLine("NAPS2.TW - Init with modal form");
                Invoker.Current.Invoke(() => twainForm.ShowDialog(dialogParent));
            }
            waitHandle.WaitOne();
            Debug.WriteLine("NAPS2.TW - Operation complete");

            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);
            }
        }
Exemple #27
0
 public static object GetDevice(ScanDevice scanDevice)
 {
     throw new NotImplementedException();
 }