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

    1. Вызовите метод Vintasoft.Twain.Device.CancelTransfer.
    2. Дождитесь события Vintasoft.Twain.Device.ScanCanceled, если вы получаете изображения асинхронно.
    3. Дождитесь когда метод Vintasoft.Twain.Device.AcquireModal вернет значение Vintasoft.Twain.AcquireModalState.ScanCanceled, если вы получаете изображения в модальном цикле.

    Некоторые высокоскоростные TWAIN сканеры имеют внутренний буфер, и TWAIN сканеры кэшируют отсканированные изображения в буфере, если TWAIN сканер быстрее приложения, которое обрабатывает отсканированные изображения. Изображения, которые кэшируются во внутреннем буфере, будут потеряны, если вы отмените процесс сканирования изображений. Вы можете приостановить сканирование изображений (вместо отмены сканирования изображений), если вам нужно сохранить все отсканированные изображения.


    Вот C#/VB.NET код, который демонстрирует, как отменить асинхронную передачу изображений от TWAIN сканера:
    static bool _isScanningFinished;
    static bool _isScanCanceled;
    
    
    /// <summary>
    /// Asynchronously acquires one image from TWAIN device and cancels image transfer.
    /// </summary>
    public static void AsynchronouslyAcquireImageFromTwainDeviceAndCancelImageTransfer()
    {
        _isScanningFinished = false;
        _isScanCanceled = 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
            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);
    
            // disable device UI
            device.ShowUI = false;
            // specify that device must be closed after scan
            device.DisableAfterAcquire = true;
    
            // open the device
            device.Open();
            // specify that 2 images must be acquired from scanner
            device.XferCount = 2;
    
            // run asynchronous image acqusition
            device.Acquire();
            // wait while scan will be finished
            while (!_isScanningFinished)
            {
                System.Windows.Forms.Application.DoEvents();
            }
    
            if (!_isScanCanceled)
                throw new System.ApplicationException("Scan is NOT canceled.");
    
            // unsubscribe from device events
            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);
    
            // close the device
            device.Close();
        }
    }
    
    static void device_ImageAcquired(object sender, Vintasoft.Twain.ImageAcquiredEventArgs e)
    {
        // get reference to the device
        Vintasoft.Twain.Device device = (Vintasoft.Twain.Device)sender;
        // cancel image scan
        device.CancelTransfer();
        System.Console.WriteLine("Feeder is stopped.");
    }
    
    static void device_ScanCompleted(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("Scan is completed.");
    }
    
    static void device_ScanCanceled(object sender, System.EventArgs e)
    {
        _isScanCanceled = true;
        System.Console.WriteLine("Scan is canceled.");
    }
    
    static void device_ScanFailed(object sender, Vintasoft.Twain.ScanFailedEventArgs e)
    {
        System.Console.WriteLine(string.Format("Scan is failed: {0}.", e.ErrorString));
    }
    
    static void device_ScanFinished(object sender, System.EventArgs e)
    {
        _isScanningFinished = true;
    }
    
    Shared _isScanningFinished As Boolean
    Shared _isScanCanceled As Boolean
    
    
    ''' <summary>
    ''' Asynchronously acquires one image from TWAIN device and cancels image transfer.
    ''' </summary>
    Public Shared Sub AsynchronouslyAcquireImageFromTwainDeviceAndCancelImageTransfer()
            _isScanningFinished = False
            _isScanCanceled = 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
                    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)
    
                    ' disable device UI
                    device.ShowUI = False
                    ' specify that device must be closed after scan
                    device.DisableAfterAcquire = True
    
                    ' open the device
                    device.Open()
                    ' specify that 2 images must be acquired from scanner
                    device.XferCount = 2
    
                    ' run asynchronous image acqusition
                    device.Acquire()
                    ' wait while scan will be finished
                    While Not _isScanningFinished
                            System.Windows.Forms.Application.DoEvents()
                    End While
    
                    If Not _isScanCanceled Then
                            Throw New System.ApplicationException("Scan is NOT canceled.")
                    End If
    
                    ' unsubscribe from device events
                    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)
    
                    ' close the device
                    device.Close()
            End Using
    End Sub
    
    Private Shared Sub device_ImageAcquired(sender As Object, e As Vintasoft.Twain.ImageAcquiredEventArgs)
            ' get reference to the device
            Dim device As Vintasoft.Twain.Device = DirectCast(sender, Vintasoft.Twain.Device)
            ' cancel image scan
            device.CancelTransfer()
            System.Console.WriteLine("Feeder is stopped.")
    End Sub
    
    Private Shared Sub device_ScanCompleted(sender As Object, e As System.EventArgs)
            System.Console.WriteLine("Scan is completed.")
    End Sub
    
    Private Shared Sub device_ScanCanceled(sender As Object, e As System.EventArgs)
            _isScanCanceled = True
            System.Console.WriteLine("Scan is canceled.")
    End Sub
    
    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
    
    Private Shared Sub device_ScanFinished(sender As Object, e As System.EventArgs)
            _isScanningFinished = True
    End Sub
    


    Вот C#/VB.NET код, который демонстрирует, как отменить синхронную передачу изображений от TWAIN сканера:
    /// <summary>
    /// Synchronously acquires one image from TWAIN device and cancels image transfer.
    /// </summary>
    public static void SynchronouslyAcquireImageFromTwainDeviceAndCancelImageTransfer()
    {
        bool isScanCanceled = 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));
    
            // disable device UI
            device.ShowUI = false;
            // specify that device must be closed after scan
            device.DisableAfterAcquire = true;
    
            // open the device
            device.Open();
            // specify that 2 images must be acquired from scanner
            device.XferCount = 2;
    
            // run asynchronous image acquisition
            Vintasoft.Twain.AcquireModalState acquireModalState = Vintasoft.Twain.AcquireModalState.None;
            do
            {
                acquireModalState = device.AcquireModal();
                switch (acquireModalState)
                {
                    case Vintasoft.Twain.AcquireModalState.ImageAcquired:
                        System.Console.WriteLine("Image is acquired.");
                        if (device.AcquiredImage != null)
                            device.AcquiredImage.Dispose();
    
                        // cancel image scan
                        device.CancelTransfer();
                        break;
    
                    case Vintasoft.Twain.AcquireModalState.ScanCompleted:
                        System.Console.WriteLine("Scan is completed.");
                        break;
    
                    case Vintasoft.Twain.AcquireModalState.ScanCanceled:
                        isScanCanceled = true;
                        System.Console.WriteLine("Scan is canceled.");
                        break;
    
                    case Vintasoft.Twain.AcquireModalState.ScanFailed:
                        System.Console.WriteLine(string.Format("Scan is failed: {0}.", device.ErrorString));
                        break;
                }
            }
            while (acquireModalState != Vintasoft.Twain.AcquireModalState.None);
    
            if (!isScanCanceled)
                throw new System.ApplicationException("Scan is NOT canceled.");
    
            // close the device
            device.Close();
        }
    }
    
    ''' <summary>
    ''' Synchronously acquires one image from TWAIN device and cancels image transfer.
    ''' </summary>
    Public Shared Sub SynchronouslyAcquireImageFromTwainDeviceAndCancelImageTransfer()
            Dim isScanCanceled As Boolean = 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
    
                    ' disable device UI
                    device.ShowUI = False
                    ' specify that device must be closed after scan
                    device.DisableAfterAcquire = True
    
                    ' open the device
                    device.Open()
                    ' specify that 2 images must be acquired from scanner
                    device.XferCount = 2
    
                    ' run asynchronous image acquisition
                    Dim acquireModalState As Vintasoft.Twain.AcquireModalState = Vintasoft.Twain.AcquireModalState.None
                    Do
                            acquireModalState = device.AcquireModal()
                            Select Case acquireModalState
                                    Case Vintasoft.Twain.AcquireModalState.ImageAcquired
                                            System.Console.WriteLine("Image is acquired.")
                                            If device.AcquiredImage IsNot Nothing Then
                                                    device.AcquiredImage.Dispose()
                                            End If
    
                                            ' cancel image scan
                                            device.CancelTransfer()
                                            Exit Select
    
                                    Case Vintasoft.Twain.AcquireModalState.ScanCompleted
                                            System.Console.WriteLine("Scan is completed.")
                                            Exit Select
    
                                    Case Vintasoft.Twain.AcquireModalState.ScanCanceled
                                            isScanCanceled = True
                                            System.Console.WriteLine("Scan is canceled.")
                                            Exit Select
    
                                    Case Vintasoft.Twain.AcquireModalState.ScanFailed
                                            System.Console.WriteLine(String.Format("Scan is failed: {0}.", device.ErrorString))
                                            Exit Select
                            End Select
                    Loop While acquireModalState <> Vintasoft.Twain.AcquireModalState.None
    
                    If Not isScanCanceled Then
                            Throw New System.ApplicationException("Scan is NOT canceled.")
                    End If
    
                    ' close the device
                    device.Close()
            End Using
    End Sub