VintaSoft Twain .NET SDK v10.2
Acquire images from scanner asynchronously

VintaSoft Twain .NET SDK allows to acquire images from a scanner asynchronously.

Here is to do list for acquiring images asynchronously:

  1. Open TWAIN device manager.
  2. Select TWAIN device.
  3. Subscribe to the events of TWAIN device: Device.ImageAcquired, Device.ScanFinished, etc.
  4. Open TWAIN device.
  5. Set the scanning settings.
  6. Start the asynchronous acquisition process.
  7. Retrieve acquired image one by one while the Device.ImageAcquired event fires.
  8. Stop image acquisition process when the Device.ScanCompleted event fires.

Example: Here is an example that shows how to scan images asynchronously using scanner's user interface and save scanned images into multipage TIFF file:
Imports System.IO
Imports System.Windows.Forms
Imports Vintasoft.Twain

Partial Public Class ScanAsynchronouslyDemoForm
    Inherits Form

#Region "Fields"

    ''' <summary>
    ''' TWAIN device manager.
    ''' </summary>
    Private _deviceManager As DeviceManager

#End Region



#Region "Constructors"

    Public Sub New()
        InitializeComponent()

        ' create and open device manager
        _deviceManager = New DeviceManager(Me)
        _deviceManager.Open()
    End Sub

#End Region



#Region "Methods"

    ''' <summary>
    ''' Starts the image acquisition from scanner.
    ''' </summary>
    Private Sub startImageAcquisitionButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim device As Device = Nothing
        Try
            ' select the default device
            _deviceManager.ShowDefaultDeviceSelectionDialog()

            ' get reference to the default device
            device = _deviceManager.DefaultDevice
            ' if device is not found
            If device Is Nothing Then
                Exit Sub
            End If

            ' subscribe to the device events
            SubscribeToDeviceEvents(device)

            ' set Memory transfer mode
            device.TransferMode = TransferMode.Memory
            ' enable UI
            device.ShowUI = True

            ' open the device
            device.Open()
            ' specify that black-white images must be acquired
            device.PixelType = PixelType.BW
            ' specify the threshold for acquired images
            device.Threshold = 128
            ' set the inches as unit of measure
            device.UnitOfMeasure = UnitOfMeasure.Inches
            device.Resolution = New Resolution(300.0F, 300.0F)

            ' acquire images asynchronously
            device.Acquire()
        Catch ex As TwainException
            ' if device is found
            If device IsNot Nothing Then
                ' if device is opened
                If device.State >= DeviceState.Opened Then
                    ' close the device
                    device.Close()
                End If

                ' unsubscribe from device events
                UnsubscribeFromDeviceEvents(device)
            End If

            MsgBox(ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' Image acquisition is in progress.
    ''' </summary>
    Private Sub device_ImageAcquiringProgress(ByVal sender As Object, ByVal e As Vintasoft.Twain.ImageAcquiringProgressEventArgs)
        ' update progress bar
        progressBar1.Value = e.Progress
    End Sub

    ''' <summary>
    ''' Image is acquired.
    ''' </summary>
    Private Sub device_ImageAcquired(ByVal sender As Object, ByVal e As Vintasoft.Twain.ImageAcquiredEventArgs)
        ' dispose image stored in the picture box
        If pictureBox1.Image IsNot Nothing Then
            pictureBox1.Image.Dispose()
            pictureBox1.Image = Nothing
        End If

        ' show acquired image in the picture box
        pictureBox1.Image = e.Image.GetAsBitmap(True)

        ' add the acquired image to a TIFF file
        e.Image.Save(Path.Combine(Directory.GetCurrentDirectory(), "multipage.tif"))

        ' dispose the acquired image
        e.Image.Dispose()
    End Sub

    ''' <summary>
    ''' Scan is completed.
    ''' </summary>
    Private Sub device_ScanCompleted(ByVal sender As Object, ByVal e As EventArgs)
        MessageBox.Show("Scan is competed.")
    End Sub

    ''' <summary>
    ''' Scan is canceled.
    ''' </summary>
    Private Sub device_ScanCanceled(ByVal sender As Object, ByVal e As EventArgs)
        MessageBox.Show("Scan is canceled.")
    End Sub

    ''' <summary>
    ''' Scan is failed.
    ''' </summary>
    Private Sub device_ScanFailed(ByVal sender As Object, ByVal e As Vintasoft.Twain.ScanFailedEventArgs)
        MessageBox.Show(String.Format("Scan is failed: {0}", e.ErrorString))
    End Sub

    ''' <summary>
    ''' User interface of device is closed.
    ''' </summary>
    Private Sub device_UserInterfaceClosed(ByVal sender As Object, ByVal e As EventArgs)
        MessageBox.Show("User Interface is closed.")
    End Sub

    ''' <summary>
    ''' Scan is finished.
    ''' </summary>
    Private Sub device_ScanFinished(ByVal sender As Object, ByVal e As EventArgs)
        Dim device1 As Device = DirectCast(sender, Device)

        ' unsubscribe from device events
        UnsubscribeFromDeviceEvents(device1)

        ' if device is not closed
        If device1.State <> DeviceState.Closed Then
            ' close the device
            device1.Close()
        End If

        MessageBox.Show("Scan is finished.")
    End Sub

    ''' <summary>
    ''' Subscribes to the device events.
    ''' </summary>
    Private Sub SubscribeToDeviceEvents(ByVal device As Device)
        AddHandler device.ImageAcquiringProgress, New EventHandler(Of ImageAcquiringProgressEventArgs)(AddressOf device_ImageAcquiringProgress)
        AddHandler device.ImageAcquired, New EventHandler(Of ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
        AddHandler device.ScanCompleted, New EventHandler(AddressOf device_ScanCompleted)
        AddHandler device.ScanCanceled, New EventHandler(AddressOf device_ScanCanceled)
        AddHandler device.ScanFailed, New EventHandler(Of ScanFailedEventArgs)(AddressOf device_ScanFailed)
        AddHandler device.UserInterfaceClosed, New EventHandler(AddressOf device_UserInterfaceClosed)
        AddHandler device.ScanFinished, New EventHandler(AddressOf device_ScanFinished)
    End Sub

    ''' <summary>
    ''' Unsubscribes from the device events.
    ''' </summary>
    Private Sub UnsubscribeFromDeviceEvents(ByVal device As Device)
        RemoveHandler device.ImageAcquiringProgress, New EventHandler(Of ImageAcquiringProgressEventArgs)(AddressOf device_ImageAcquiringProgress)
        RemoveHandler device.ImageAcquired, New EventHandler(Of ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
        RemoveHandler device.ScanCompleted, New EventHandler(AddressOf device_ScanCompleted)
        RemoveHandler device.ScanCanceled, New EventHandler(AddressOf device_ScanCanceled)
        RemoveHandler device.ScanFailed, New EventHandler(Of ScanFailedEventArgs)(AddressOf device_ScanFailed)
        RemoveHandler device.UserInterfaceClosed, New EventHandler(AddressOf device_UserInterfaceClosed)
        RemoveHandler device.ScanFinished, New EventHandler(AddressOf device_ScanFinished)
    End Sub

#End Region

End Class
              
using System;
using System.IO;
using System.Windows.Forms;
using Vintasoft.Twain;

namespace TwainExamples_CSharp
{
    public partial class ScanAsynchronouslyDemoForm : Form
    {

        #region Fields

        /// <summary>
        /// TWAIN device manager.
        /// </summary>
        DeviceManager _deviceManager;

        #endregion



        #region Constructors

        public ScanAsynchronouslyDemoForm()
        {
            InitializeComponent();

            // create and open device manager
            _deviceManager = new DeviceManager(this);
            _deviceManager.Open();
        }

        #endregion



        #region Methods

        /// <summary>
        /// Starts the image acquisition from scanner.
        /// </summary>
        private void startImageAcquisitionButton_Click(object sender, EventArgs e)
        {
            Device device = null;
            try
            {
                // select the default device
                _deviceManager.ShowDefaultDeviceSelectionDialog();

                // get reference to the default device
                device = _deviceManager.DefaultDevice;
                // if device is not found
                if (device == null)
                    return;

                // subscribe to the device events
                SubscribeToDeviceEvents(device);

                // set Memory transfer mode
                device.TransferMode = TransferMode.Memory;
                // enable UI
                device.ShowUI = true;

                // open the device
                device.Open();
                // specify that black-white images must be acquired
                device.PixelType = PixelType.BW;
                // specify the threshold for acquired images
                device.Threshold = 128;
                // set the inches as unit of measure
                device.UnitOfMeasure = UnitOfMeasure.Inches;
                device.Resolution = new Resolution(300f, 300f);

                // acquire images asynchronously
                device.Acquire();
            }
            catch (TwainException ex)
            {
                // if device is found
                if (device != null)
                {
                    // if device is opened
                    if (device.State >= DeviceState.Opened)
                        // close the device
                        device.Close();

                    // unsubscribe from device events
                    UnsubscribeFromDeviceEvents(device);
                }

                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Image acquisition is in progress.
        /// </summary>
        private void device_ImageAcquiringProgress(
            object sender,
            Vintasoft.Twain.ImageAcquiringProgressEventArgs e)
        {
            // update progress bar
            progressBar1.Value = e.Progress;
        }

        /// <summary>
        /// Image is acquired.
        /// </summary>
        private void device_ImageAcquired(object sender, Vintasoft.Twain.ImageAcquiredEventArgs e)
        {
            // dispose image stored in the picture box
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
                pictureBox1.Image = null;
            }

            // show acquired image in the picture box
            pictureBox1.Image = e.Image.GetAsBitmap(true);

            // add the acquired image to a TIFF file
            e.Image.Save(Path.Combine(Directory.GetCurrentDirectory(), "multipage.tif"));

            // dispose the acquired image
            e.Image.Dispose();
        }

        /// <summary>
        /// Scan is completed.
        /// </summary>
        private void device_ScanCompleted(object sender, EventArgs e)
        {
            MessageBox.Show("Scan is competed.");
        }

        /// <summary>
        /// Scan is canceled.
        /// </summary>
        private void device_ScanCanceled(object sender, EventArgs e)
        {
            MessageBox.Show("Scan is canceled.");
        }

        /// <summary>
        /// Scan is failed.
        /// </summary>
        private void device_ScanFailed(object sender, Vintasoft.Twain.ScanFailedEventArgs e)
        {
            MessageBox.Show(string.Format("Scan is failed: {0}", e.ErrorString));
        }

        /// <summary>
        /// User interface of device is closed.
        /// </summary>
        private void device_UserInterfaceClosed(object sender, EventArgs e)
        {
            MessageBox.Show("User Interface is closed.");
        }

        /// <summary>
        /// Scan is finished.
        /// </summary>
        private void device_ScanFinished(object sender, EventArgs e)
        {
            Device device = (Device)sender;

            // unsubscribe from device events
            UnsubscribeFromDeviceEvents(device);

            // if device is not closed
            if (device.State != DeviceState.Closed)
                // close the device
                device.Close();

            MessageBox.Show("Scan is finished.");
        }

        /// <summary>
        /// Subscribes to the device events.
        /// </summary>
        private void SubscribeToDeviceEvents(Device device)
        {
            device.ImageAcquiringProgress += new EventHandler(device_ImageAcquiringProgress);
            device.ImageAcquired += new EventHandler(device_ImageAcquired);
            device.ScanCompleted += new EventHandler(device_ScanCompleted);
            device.ScanCanceled += new EventHandler(device_ScanCanceled);
            device.ScanFailed += new EventHandler(device_ScanFailed);
            device.UserInterfaceClosed += new EventHandler(device_UserInterfaceClosed);
            device.ScanFinished += new EventHandler(device_ScanFinished);
        }

        /// <summary>
        /// Unsubscribes from the device events.
        /// </summary>
        private void UnsubscribeFromDeviceEvents(Device device)
        {
            device.ImageAcquiringProgress -= new EventHandler(device_ImageAcquiringProgress);
            device.ImageAcquired -= new EventHandler(device_ImageAcquired);
            device.ScanCompleted -= new EventHandler(device_ScanCompleted);
            device.ScanCanceled -= new EventHandler(device_ScanCanceled);
            device.ScanFailed -= new EventHandler(device_ScanFailed);
            device.UserInterfaceClosed -= new EventHandler(device_UserInterfaceClosed);
            device.ScanFinished -= new EventHandler(device_ScanFinished);
        }

        #endregion

    }
}