VintaSoft Twain .NET SDK 14.1: Руководство для .NET разработчика
В этом разделе
    Асинхронное получение изображений от TWAIN сканера
    В этом разделе
    VintaSoft Twain .NET SDK позволяет получать изображения от TWAIN сканера асинхронно.


    Если необходимо получить изображения от TWAIN сканера асинхронно, то выполните следующие действия:
    1. Откройте менеджер TWAIN устройств.
    2. Выберите TWAIN устройство.
    3. Подпишитесь на события TWAIN устройства: Vintasoft.Twain.Device.ImageAcquired, Vintasoft.Twain.Device.ScanFinished, ...
    4. Откройте TWAIN устройство.
    5. Установите параметры сканирования изображений.
    6. Запустите асинхронный процесс получения изображений от TWAIN устройства.
    7. Получайте изображения по одному при наступлении события Vintasoft.Twain.Device.ImageAcquired.
    8. Остановите процесс получения изображений при возникновении события Vintasoft.Twain.Device.ScanCompleted.

    Вот C#/VB.NET код, который демонстрирует, как асинхронно сканировать изображения, используя пользовательский интерфейс TWAIN сканера, и сохранять отсканированные изображения в многостраничный файл TIFF:
    static bool _isScanningFinished;
    
    
    /// <summary>
    /// Asynchronously acquires images from TWAIN device.
    /// </summary>
    public static void AsynchronouslyAcquireImageFromTwainDevice()
    {
        _isScanningFinished = false;
    
        // create the device manager
        using (Vintasoft.Twain.DeviceManager deviceManager = new Vintasoft.Twain.DeviceManager())
        {
            deviceManager.IsTwain2Compatible = true;
            // open the device manager
            deviceManager.Open();
    
            // get the device
            string deviceName = "KODAK Scanner: i5000";
            Vintasoft.Twain.Device device = deviceManager.Devices.Find(deviceName);
            if (device == null)
                throw new System.ApplicationException(string.Format("Device '{0}' is not found.", deviceName));
    
            // subscribe to device events
            SubscribeToDeviceEvents(device);
    
            // disable device UI
            device.ShowUI = false;
            // set Memory transfer mode
            device.TransferMode = Vintasoft.Twain.TransferMode.Memory;
    
            // open the device
            device.Open();
    
            // specify that black-white images must be acquired
            device.PixelType = Vintasoft.Twain.PixelType.BW;
            // specify the threshold for acquired images
            device.Threshold = 128;
            // set the inches as unit of measure
            device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches;
            device.Resolution = new Vintasoft.Twain.Resolution(300f, 300f);
    
            // run asynchronous image acqusition
            device.Acquire();
    
            // wait while feeder will be stopped
            while (!_isScanningFinished)
            {
                System.Windows.Forms.Application.DoEvents();
            }
    
            // unsubscribe from device events
            UnsubscribeFromDeviceEvents(device);
    
            // close the device
            device.Close();
        }
    }
    
    /// <summary>
    /// Image acquisition is in progress.
    /// </summary>
    private static void device_ImageAcquiringProgress(object sender, Vintasoft.Twain.ImageAcquiringProgressEventArgs e)
    {
        // update progress bar
    }
    
    /// <summary>
    /// Image is acquired.
    /// </summary>
    private static void device_ImageAcquired(object sender, Vintasoft.Twain.ImageAcquiredEventArgs e)
    {
        // add the acquired image to a TIFF file
        e.Image.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "multipage.tif"));
    
        // dispose the acquired image
        e.Image.Dispose();
    }
    
    /// <summary>
    /// Scan is completed.
    /// </summary>
    private static void device_ScanCompleted(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("Scan is completed.");
    }
    
    /// <summary>
    /// Scan is canceled.
    /// </summary>
    private static void device_ScanCanceled(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("Scan is canceled.");
    }
    
    /// <summary>
    /// Scan is failed.
    /// </summary>
    private static void device_ScanFailed(object sender, Vintasoft.Twain.ScanFailedEventArgs e)
    {
        System.Console.WriteLine(string.Format("Scan is failed: {0}.", e.ErrorString));
    }
    
    /// <summary>
    /// Scan is finished.
    /// </summary>
    private static void device_ScanFinished(object sender, System.EventArgs e)
    {
        Vintasoft.Twain.Device device = (Vintasoft.Twain.Device)sender;
    
        // unsubscribe from device events
        UnsubscribeFromDeviceEvents(device);
    
        // if device is not closed
        if (device.State != Vintasoft.Twain.DeviceState.Closed)
            // close the device
            device.Close();
    
        System.Console.WriteLine("Scan is finished.");
    
        _isScanningFinished = true;
    }
    
    /// <summary>
    /// Subscribes to the device events.
    /// </summary>
    private static void SubscribeToDeviceEvents(Vintasoft.Twain.Device device)
    {
        device.ImageAcquiringProgress += new System.EventHandler<Vintasoft.Twain.ImageAcquiringProgressEventArgs>(device_ImageAcquiringProgress);
        device.ImageAcquired += new System.EventHandler<Vintasoft.Twain.ImageAcquiredEventArgs>(device_ImageAcquired);
        device.ScanCompleted += new System.EventHandler(device_ScanCompleted);
        device.ScanCanceled += new System.EventHandler(device_ScanCanceled);
        device.ScanFailed += new System.EventHandler<Vintasoft.Twain.ScanFailedEventArgs>(device_ScanFailed);
        device.ScanFinished += new System.EventHandler(device_ScanFinished);
    }
    
    /// <summary>
    /// Unsubscribes from the device events.
    /// </summary>
    private static void UnsubscribeFromDeviceEvents(Vintasoft.Twain.Device device)
    {
        device.ImageAcquiringProgress -= new System.EventHandler<Vintasoft.Twain.ImageAcquiringProgressEventArgs>(device_ImageAcquiringProgress);
        device.ImageAcquired -= new System.EventHandler<Vintasoft.Twain.ImageAcquiredEventArgs>(device_ImageAcquired);
        device.ScanCompleted -= new System.EventHandler(device_ScanCompleted);
        device.ScanCanceled -= new System.EventHandler(device_ScanCanceled);
        device.ScanFailed -= new System.EventHandler<Vintasoft.Twain.ScanFailedEventArgs>(device_ScanFailed);
        device.ScanFinished -= new System.EventHandler(device_ScanFinished);
    }
    
    Shared _isScanningFinished As Boolean
    
    
    ''' <summary>
    ''' Asynchronously acquires images from TWAIN device.
    ''' </summary>
    Public Shared Sub AsynchronouslyAcquireImageFromTwainDevice()
            _isScanningFinished = False
    
            ' create the device manager
            Using deviceManager As New Vintasoft.Twain.DeviceManager()
                    deviceManager.IsTwain2Compatible = True
                    ' open the device manager
                    deviceManager.Open()
    
                    ' get the device
                    Dim deviceName As String = "KODAK Scanner: i5000"
                    Dim device As Vintasoft.Twain.Device = deviceManager.Devices.Find(deviceName)
                    If device Is Nothing Then
                            Throw New System.ApplicationException(String.Format("Device '{0}' is not found.", deviceName))
                    End If
    
                    ' subscribe to device events
                    SubscribeToDeviceEvents(device)
    
                    ' disable device UI
                    device.ShowUI = False
                    ' set Memory transfer mode
                    device.TransferMode = Vintasoft.Twain.TransferMode.Memory
    
                    ' open the device
                    device.Open()
    
                    ' specify that black-white images must be acquired
                    device.PixelType = Vintasoft.Twain.PixelType.BW
                    ' specify the threshold for acquired images
                    device.Threshold = 128
                    ' set the inches as unit of measure
                    device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches
                    device.Resolution = New Vintasoft.Twain.Resolution(300F, 300F)
    
                    ' run asynchronous image acqusition
                    device.Acquire()
    
                    ' wait while feeder will be stopped
                    While Not _isScanningFinished
                            System.Windows.Forms.Application.DoEvents()
                    End While
    
                    ' unsubscribe from device events
                    UnsubscribeFromDeviceEvents(device)
    
                    ' close the device
                    device.Close()
            End Using
    End Sub
    
    ''' <summary>
    ''' Image acquisition is in progress.
    ''' </summary>
    Private Shared Sub device_ImageAcquiringProgress(sender As Object, e As Vintasoft.Twain.ImageAcquiringProgressEventArgs)
            ' update progress bar
    End Sub
    
    ''' <summary>
    ''' Image is acquired.
    ''' </summary>
    Private Shared Sub device_ImageAcquired(sender As Object, e As Vintasoft.Twain.ImageAcquiredEventArgs)
            ' add the acquired image to a TIFF file
            e.Image.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "multipage.tif"))
    
            ' dispose the acquired image
            e.Image.Dispose()
    End Sub
    
    ''' <summary>
    ''' Scan is completed.
    ''' </summary>
    Private Shared Sub device_ScanCompleted(sender As Object, e As System.EventArgs)
            System.Console.WriteLine("Scan is completed.")
    End Sub
    
    ''' <summary>
    ''' Scan is canceled.
    ''' </summary>
    Private Shared Sub device_ScanCanceled(sender As Object, e As System.EventArgs)
            System.Console.WriteLine("Scan is canceled.")
    End Sub
    
    ''' <summary>
    ''' Scan is failed.
    ''' </summary>
    Private Shared Sub device_ScanFailed(sender As Object, e As Vintasoft.Twain.ScanFailedEventArgs)
            System.Console.WriteLine(String.Format("Scan is failed: {0}.", e.ErrorString))
    End Sub
    
    ''' <summary>
    ''' Scan is finished.
    ''' </summary>
    Private Shared Sub device_ScanFinished(sender As Object, e As System.EventArgs)
            Dim device As Vintasoft.Twain.Device = DirectCast(sender, Vintasoft.Twain.Device)
    
            ' unsubscribe from device events
            UnsubscribeFromDeviceEvents(device)
    
            ' if device is not closed
            If device.State <> Vintasoft.Twain.DeviceState.Closed Then
                    ' close the device
                    device.Close()
            End If
    
            System.Console.WriteLine("Scan is finished.")
    
            _isScanningFinished = True
    End Sub
    
    ''' <summary>
    ''' Subscribes to the device events.
    ''' </summary>
    Private Shared Sub SubscribeToDeviceEvents(device As Vintasoft.Twain.Device)
            AddHandler device.ImageAcquiringProgress, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiringProgressEventArgs)(AddressOf device_ImageAcquiringProgress)
            AddHandler device.ImageAcquired, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
            AddHandler device.ScanCompleted, New System.EventHandler(AddressOf device_ScanCompleted)
            AddHandler device.ScanCanceled, New System.EventHandler(AddressOf device_ScanCanceled)
            AddHandler device.ScanFailed, New System.EventHandler(Of Vintasoft.Twain.ScanFailedEventArgs)(AddressOf device_ScanFailed)
            AddHandler device.ScanFinished, New System.EventHandler(AddressOf device_ScanFinished)
    End Sub
    
    ''' <summary>
    ''' Unsubscribes from the device events.
    ''' </summary>
    Private Shared Sub UnsubscribeFromDeviceEvents(device As Vintasoft.Twain.Device)
            RemoveHandler device.ImageAcquiringProgress, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiringProgressEventArgs)(AddressOf device_ImageAcquiringProgress)
            RemoveHandler device.ImageAcquired, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
            RemoveHandler device.ScanCompleted, New System.EventHandler(AddressOf device_ScanCompleted)
            RemoveHandler device.ScanCanceled, New System.EventHandler(AddressOf device_ScanCanceled)
            RemoveHandler device.ScanFailed, New System.EventHandler(Of Vintasoft.Twain.ScanFailedEventArgs)(AddressOf device_ScanFailed)
            RemoveHandler device.ScanFinished, New System.EventHandler(AddressOf device_ScanFinished)
    End Sub