static void DoTwainWork() { Console.WriteLine("Getting ready to do twain stuff on thread {0}...", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(1000); var rc = twain.Open(); if (rc == ReturnCode.Success) { var hit = twain.FirstOrDefault(s => string.Equals(s.Name, SAMPLE_SOURCE)); if (hit == null) { Console.WriteLine("The sample source \"" + SAMPLE_SOURCE + "\" is not installed."); twain.Close(); } else { rc = hit.Open(); if (rc == ReturnCode.Success) { Console.WriteLine("Starting capture from the sample source..."); rc = hit.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero); } else { twain.Close(); } } } else { Console.WriteLine("Failed to open dsm with rc={0}!", rc); } }
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; } }
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); }
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(); } }
internal void CloseDown() { if (session.State == 4) { session.CurrentSource.Close(); } session.Close(); }
private void FormScan_FormClosing(object sender, FormClosingEventArgs e) { if (dataSource != null && dataSource.IsOpen) { dataSource.Close(); } if (session != null) { session.Close(); } }
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(); } }
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(); } }
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(); } }
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; }
private void CleanupTwain() { if (_twain.State == 4) { _twain.CurrentSource.Close(); } if (_twain.State == 3) { _twain.Close(); } if (_twain.State > 2) { // normal close down didn't work, do hard kill _twain.ForceStepDown(2); } }
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); }
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(); } }
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); } } }
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(); }
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); }
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); } }
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; }
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); }
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; }
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(); } }
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; }
void DoTwainWork() { try { eventLog1.WriteEntry("Getting ready to do twain stuff on thread " + Thread.CurrentThread.ManagedThreadId); //Thread.Sleep(1000); twain = new TwainSession(TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly())); twain.TransferReady += (s, e) => { eventLog1.WriteEntry("Got xfer ready on thread " + Thread.CurrentThread.ManagedThreadId); }; twain.DataTransferred += (s, e) => { if (e.NativeData != IntPtr.Zero) //else if (!string.IsNullOrWhiteSpace(e.FileDataPath)) { eventLog1.WriteEntry("SUCCESS! Got twain data on thread " + Thread.CurrentThread.ManagedThreadId); try { byte[] msg = EncodeOutgoingMessage(e.DataSource.Name); stream.Write(msg, 0, msg.Length); stream.Flush(); eventLog1.WriteEntry("Attempting to read the image"); Stream imgStr = e.GetNativeImageStream(); if (imgStr != null) { eventLog1.WriteEntry("Attempting to read the image 1, length:" + imgStr.Length); var imglen = EncodeOutgoingMessage("Img length:" + imgStr.Length.ToString()); stream.Write(imglen, 0, imglen.Length); stream.Flush(); using (var memoryStream = new MemoryStream()) { // !!! imgStr.CopyTo(memoryStream); var imgBytes = memoryStream.ToArray(); var b64img = Convert.ToBase64String(imgBytes); var preparedBytes = EncodeOutgoingMessage(b64img); stream.Write(preparedBytes, 0, preparedBytes.Length); stream.Flush(); eventLog1.WriteEntry("Attempting to read the image 2"); } } else { eventLog1.WriteEntry("Attempting to read the image 3"); byte[] msgNoImg = EncodeOutgoingMessage("No image!?"); stream.Write(msgNoImg, 0, msgNoImg.Length); stream.Flush(); } } catch (Exception ex) { eventLog1.WriteEntry("Error writing response! " + ex.Message + "\n" + ex.StackTrace); } } else { eventLog1.WriteEntry("BUMMER! No twain data on thread " + Thread.CurrentThread.ManagedThreadId); } }; twain.SourceDisabled += (s, e) => { eventLog1.WriteEntry("Source disabled on thread " + Thread.CurrentThread.ManagedThreadId); var rc = twain.CurrentSource.Close(); rc = twain.Close(); }; } catch (Exception ex) { eventLog1.WriteEntry("Error creating twain! " + ex.Message); } ///////////// try { var rc = twain.Open(); if (rc == ReturnCode.Success) { var hit = twain.FirstOrDefault(s => string.Equals(s.Name, SAMPLE_SOURCE)); if (hit == null) { eventLog1.WriteEntry("The sample source \"" + SAMPLE_SOURCE + "\" is not installed."); twain.Close(); } else { rc = hit.Open(); if (rc == ReturnCode.Success) { eventLog1.WriteEntry("Starting capture from the sample source..."); rc = hit.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero); } else { twain.Close(); } } } else { eventLog1.WriteEntry("Failed to open dsm with rc=" + rc); } } catch (Exception ex) { eventLog1.WriteEntry("Error opening twain: " + ex.Message); } }