Click here to Skip to main content
15,887,945 members
Articles / Programming Languages / C#
Article

.NET TWAIN image scanner

Rate me:
Please Sign up or sign in to vote.
4.91/5 (227 votes)
12 May 2002Public Domain2 min read 7.2M   132.2K   421   996
Using TWAIN API to scan images

Sample Screenshot

Abstract

In Windows imaging applications, the most used API for scanning is TWAIN www.twain.org. Unfortunately, the new .NET Framework has no built-in support for TWAIN. So we have to work with the interop methods of .NET to access this API. This article doesn't explain this interop techniques, and good knowledge of the TWAIN 1.9 specifications is assumed! The sample code included doesn't present a finished library, only some essential steps for a minimal TWAIN adaption to .NET applications.

Details

First step was to port the most important parts of TWAIN.H, these are found in TwainDefs.cs. The real logic for calling TWAIN is coded in the class Twain, in file TwainLib.cs.. As the TWAIN API is exposed by the Windows DLL, twain_32.dll, we have to use the .NET DllImport mechanism for interop with legacy code. This DLL has the central DSM_Entry(), ordinal #1 function exported as the entry point to TWAIN. This call has numerous parameters, and the last one is of variable type! It was found to be best if we declare multiple variants of the call like:

C#
[DllImport("twain_32.dll", EntryPoint="#1")]
private static extern TwRC DSMparent(
    [In, Out] TwIdentity origin,
    IntPtr zeroptr,
    TwDG dg, TwDAT dat, TwMSG msg,
    ref IntPtr refptr );

The Twain class has a simple 5-step interface:

C#
class Twain
{
    Init();
    Select();
    Acquire();
    PassMessage();
    TransferPictures();
}

For some sort of 'callbacks', TWAIN uses special Windows messages, and these must be caught from the application-message-loop. In .NET, the only way found was IMessageFilter.PreFilterMessage(), and this filter has to be activated with a call like Application.AddMessageFilter(). Within the filter method, we have to forward each message to Twain.PassMessage(), and we get a hint (enum TwainCommand) back for how we have to react.

Sample App

The sample is a Windows Forms MDI-style application. It has the two TWAIN-related menu items Select Source... and Acquire... Once an image is scanned in, we can save it to a file in any of the GDI+ supported file formats (BMP, GIF, TIFF, JPEG...)

Limitations

All code was only tested on Windows 2000SP2, with an Epson Perfection USB scanner and an Olympus digital photo camera. The scanned picture is (by TWAIN spec) a Windows DIB, and the sample code has VERY little checking against error return codes and bitmap formats. Unfortunately, no direct method is available in .NET to convert a DIB to the managed Bitmap class... Some known problems may show up with color palettes and menus.

Note, TWAIN has it's root in 16-Bit Windows! For a more modern API supported on Windows ME/XP, have a look at Windows Image Acquisition (WIA).

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Web Developer
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: TW_ARRAY Pin
kwpatrick5-Aug-05 12:46
kwpatrick5-Aug-05 12:46 
GeneralRe: TW_ARRAY Pin
CodeMusho4-Jun-10 0:25
CodeMusho4-Jun-10 0:25 
GeneralVB.net version... please! Pin
AmaiaR11-Jul-05 9:00
AmaiaR11-Jul-05 9:00 
GeneralRe: VB.net version... please! Pin
wbdurano11-Jul-05 22:27
wbdurano11-Jul-05 22:27 
AnswerRe: VB.net version... please! Pin
KoreTex26-Aug-05 0:01
KoreTex26-Aug-05 0:01 
GeneralRe: VB.net version... please! Pin
Olivier DALET6-Sep-05 5:50
Olivier DALET6-Sep-05 5:50 
AnswerRe: VB.net version... please! Pin
Xdream6612-Dec-05 21:21
Xdream6612-Dec-05 21:21 
GeneralSetResolution with TwRange Please! Pin
MarceloGA6-Jul-05 23:51
MarceloGA6-Jul-05 23:51 
Hi guys

I´m working whit a flat scanner, i wanna set up the resolution more than 1200 dpi but the program don´t response this order, i don´t know why.

The Units are set up good, the program run perfect with 1200 dpi, but the program don´t run with more than 1200 dpi.

I´m trying to set up a range, but the program don´t response. The code is the folowing

Code TwainLib.cs

TwRange neuRangeXAufl = new TwRange();
neuRangeXAufl.MinValue = 100;
neuRangeXAufl.MaxValue = 1200;
neuRangeXAufl.StepSize = 100;
neuRangeXAufl.CurrentValue = 1200;
TwCapabilityR capXAufl = new TwCapabilityR( TwCap.IXResolution, neuRangeXAufl );
rc = DScapRange( appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, neuRangeXAufl );
if( rc != TwRC.Success )
{
CloseSrc();
return;
}


[DllImport("twain_32.dll", EntryPoint="#1")]
private static extern TwRC DScapRange( [In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, TwRange SetTwRange );



TwainDefs.cs

/* TWON_ARRAY. Container for array of values (a simplified TW_ENUMERATION) */
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwArray
{
public short ItemType;
public int NumItems; /* How many items in ItemList */
[MarshalAs( UnmanagedType.ByValArray, SizeConst=1)]
public short[] ItemList; /* Array of ItemType values starts here */
}

/* TWON_ENUMERATION. Container for a collection of values. */
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwEnumeration
{
public short ItemType;
public int NumItems; /* How many items in ItemList */
public int CurrentIndex; /* Current value is in ItemList[CurrentIndex] */
public int DefaultIndex; /* Powerup value is in ItemList[DefaultIndex] */
[MarshalAs( UnmanagedType.ByValArray, SizeConst=1)]
public short[] ItemList; /* Array of ItemType values starts here */
}

/* TWON_ONEVALUE. Container for one value. */
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwOneValue
{
public short ItemType;
public int Item;
}

/* TWON_RANGE. Container for a range of values. */
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwRange
{
public short ItemType;
public short MinValue; /* Starting value in the range. */
public short MaxValue; /* Final value in the range. */
public short StepSize; /* Increment from MinValue to MaxValue. */
public short DefaultValue; /* Power-up value. */
public short CurrentValue; /* The value that is currently in effect. */
}


[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class TwCapabilityR
{ // TW_CAPABILITY_RANGE
public TwCapabilityR( TwCap capR )
{
Cap = (short) capR;
short i = 6;
short[] ConType = new short[i];
}
public TwCapabilityR( TwCap capR, TwRange rangeVek )
{
Cap = (short) capR;
short i = (short) TwOn.Range;
short[] ConType = new short[i];
Handle = Twain.GlobalAlloc( 0x42, 6 );
IntPtr pv = Twain.GlobalLock( Handle );
Marshal.PtrToStructure(pv, rangeVek );
Twain.GlobalUnlock( Handle );
}
~TwCapabilityR()
{
if( Handle != IntPtr.Zero )
Twain.GlobalFree( Handle );
}
public short Cap; // id of capability to set or get, e.g. CAP_BRIGHTNESS
public TwRange ConType; // TWON_RANGE
public IntPtr Handle; // Handle to container of type Dat
}

If anyone have the solution, please can you help me!

kind Regards

Marcelo




GeneralScan a little document from my Application Pin
AmaiaR29-Jun-05 13:10
AmaiaR29-Jun-05 13:10 
GeneralMultiple images scan Pin
Member 188542931-May-05 0:28
Member 188542931-May-05 0:28 
GeneralRe: Multiple images scan Pin
Jwalant Natvarlal Soneji29-Jun-07 5:31
Jwalant Natvarlal Soneji29-Jun-07 5:31 
GeneralIsaac Pin
ipsas10-May-05 22:52
ipsas10-May-05 22:52 
GeneralDid anyone manage to change ICAP_XRESOLUTION Pin
TroLoo2-May-05 10:01
TroLoo2-May-05 10:01 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
Anonymous11-May-05 21:36
Anonymous11-May-05 21:36 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
TroLoo13-May-05 7:40
TroLoo13-May-05 7:40 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
Echooff321-Jul-05 9:26
Echooff321-Jul-05 9:26 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
Ludmal de silva21-Nov-05 0:57
Ludmal de silva21-Nov-05 0:57 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
Member 1326118821-Jun-17 21:51
Member 1326118821-Jun-17 21:51 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
Echooff318-Jul-05 9:59
Echooff318-Jul-05 9:59 
GeneralRe: Did anyone manage to change ICAP_XRESOLUTION Pin
Anonymous6-Jun-05 14:14
Anonymous6-Jun-05 14:14 
QuestionRe: Did anyone manage to change ICAP_XRESOLUTION Pin
mosquets31-Aug-06 4:35
mosquets31-Aug-06 4:35 
GeneralProblem: Make one multipage tiff image Pin
MaxJam29-Apr-05 5:32
MaxJam29-Apr-05 5:32 
GeneralRe: Problem: Make one multipage tiff image Pin
TroLoo23-Jun-05 8:30
TroLoo23-Jun-05 8:30 
GeneralURGENT!!! HELP!!! Scanning A DOCUMENT AND storing it Pin
mansoorbaig26-Apr-05 21:30
mansoorbaig26-Apr-05 21:30 
GeneralScan Multiple Pages Pin
Athar Aziz21-Apr-05 3:25
Athar Aziz21-Apr-05 3:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.