View on GitHub

SARAFF SOFTWARE

All products / Saraff.TwainX.Extensions

Samples

The samples below assume a Windows environment with a TWAIN 2.x DSM and a DS2 data source. They are illustrative: production code should add logging, user feedback and cancellation where appropriate.

Enumerate sources

using System;
using System.Linq;
using Saraff.TwainX.Extensions;

using var dsm = XDsm.Create();

foreach (var source in dsm.DataSources)
{
    Console.WriteLine(
        $"[{source.Identity.Manufacturer}] {source.Identity.Name} " +
        $"v{source.Identity.Version} (TWAIN {source.Identity.ProtocolVersion}, " +
        $"default={source.IsDefault}, twain2={source.IsTwain2Compatible})");
}

DataSources opens the DSM but not a source. If the list is empty, install a DSM and check the process bitness.

Native transfer to a file

using System;
using System.IO;
using System.Linq;
using Saraff.TwainX;
using Saraff.TwainX.Extensions;

using var dsm = XDsm.Create(isShowUI: true);
var source = dsm.DataSources.First();

source
    .GetCapability<float>(TwCap.XResolution).Set(_ => 300f).DataSource
    .GetCapability<float>(TwCap.YResolution).Set(_ => 300f).DataSource
    .GetCapability<TwPixelType>(TwCap.IPixelType).Set(_ => TwPixelType.RGB).DataSource
    .NativeTransfer(
        e =>
        {
            using var stream = e.Stream;
            using var file = File.Create($"scan-{Guid.NewGuid():N}.png");
            stream.CopyTo(file);
        },
        errorCallback: e => Console.Error.WriteLine(e.Exception));

The EndXfer callback can be raised after the helper returns. Keep dsm and the destination state alive until completeCallback runs.

Memory transfer chunks

using Saraff.TwainX;
using Saraff.TwainX.Extensions;

source.MemoryTransfer(
    setup => Console.WriteLine(
        $"page {setup.ImageInfo.ImageWidth}x{setup.ImageInfo.ImageLength}, buffer={setup.BufferSize}"),
    chunk =>
    {
        var data = chunk.ImageMemXfer;
        // data.ImageData is valid only during this callback.
        // Copy it into application-owned storage if it must outlive the callback.
    },
    completeCallback: () => Console.WriteLine("Memory transfer complete."),
    errorCallback: e => Console.Error.WriteLine(e.Exception));

File transfer (TIFF)

using System;
using System.IO;
using Saraff.TwainX;
using Saraff.TwainX.Extensions;

source.GetCapability<TwFF>(TwCap.ImageFileFormat).Set(TwFF.Tiff);

source.FileTransfer(
    setup => setup.FileName = Path.Combine(Path.GetTempPath(), $"scan-{Guid.NewGuid():N}.tif"),
    result => Console.WriteLine($"Written {result.ImageFileXfer.FileName}"),
    errorCallback: e => Console.Error.WriteLine(e.Exception));

Asynchronous transfer with progress

using System;
using System.IO;
using System.Linq;
using System.Threading;
using Saraff.TwainX;
using Saraff.TwainX.Extensions;

async Task ScanAsync(CancellationToken cancellationToken)
{
    using var dsm = XDsm.Create();
    var source = dsm.DataSources.First();

    var options = new TwainXAcquireOptions
    {
        ShowUI = false,
        MaxImages = 3,
        Progress = new Progress<TwainXAcquisitionProgress>(p =>
            Console.WriteLine($"page {p.PageNumber}: {p.ImageInfo.ImageWidth}x{p.ImageInfo.ImageLength}"))
    };

    using var result = await source.AcquireAsync(
        options,
        session =>
        {
            session.GetCapability<float>(TwCap.XResolution).Set(300f);
            session.GetCapability<float>(TwCap.YResolution).Set(300f);
            session.GetCapability<TwPixelType>(TwCap.IPixelType).Set(TwPixelType.RGB);
        },
        cancellationToken);

    for (var i = 0; i < result.Streams.Count; i++)
    {
        using var file = File.Create($"scan-{i}.png");
        result.Streams[i].CopyTo(file);
    }
}

The result streams are independent of the TWAIN session and remain valid after result.Dispose() only if copied elsewhere. result.Dispose() disposes every stream.

WinForms pattern

Keep the manager in a field and dispose it with the form. Set the parent window for the source UI:

public partial class ScanForm : Form
{
    private XDsm _dsm;

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        _dsm = XDsm.Create(isShowUI: true);
        _dsm.TwainX.Parent = this.Handle;
    }

    private void ScanButton_Click(object sender, EventArgs e)
    {
        var source = _dsm.DataSources.First();
        source.NativeTransfer(
            result =>
            {
                using var stream = result.Stream;
                using var image = Image.FromStream(stream);
                var copy = new Bitmap(image);
                // The bitmap is owned by the UI thread after BeginInvoke.
                BeginInvoke(new Action(() => ScanPreview.Image = copy));
            },
            errorCallback: error => BeginInvoke(new Action(() => MessageBox.Show(error.Exception.Message))));
    }

    protected override void OnFormClosed(FormClosedEventArgs e)
    {
        _dsm?.Dispose();
        base.OnFormClosed(e);
    }
}

Do not dispose _dsm inside the scan button; TWAIN callbacks may arrive after Acquire() returns.

For the asynchronous path, pass the window handle through the options instead:

var options = new TwainXAcquireOptions
{
    ShowUI = true,
    Parent = this.Handle,
    MaxImages = 1
};

using var result = await source.AcquireAsync(options);

Source picker

var sources = dsm.DataSources.ToList();
var selected = sources[0];

Console.WriteLine($"Selected: {selected.Identity.Name}");
Console.WriteLine($"Default: {selected.IsDefault}");
Console.WriteLine($"TWAIN 2.x: {selected.IsTwain2Compatible}");

Identity, IsDefault and IsTwain2Compatible do not open the source. The first capability or transfer operation opens it.

Fluent capability chain

source
    .GetCapability<float>(TwCap.XResolution).Set(cap => cap.Values.First().Value).DataSource
    .GetCapability<float>(TwCap.YResolution).Set(_ => 300f).DataSource
    .GetCapability<TwUnits>(TwCap.IUnits).Set(_ => TwUnits.Inches).DataSource
    .GetCapability<TwPixelType>(TwCap.IPixelType).Set(_ => TwPixelType.RGB).DataSource
    .GetCapability<TwFF>(TwCap.ImageFileFormat).Set(_ => TwFF.Png).DataSource
    .NativeTransfer(...);

The callback overload is required for chaining; the instance Set(T) returns void.