Click here to Skip to main content
15,868,085 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.1M   132.1K   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: Source Code for VB.NET 2005 Pin
gabegabe25-Apr-07 10:24
gabegabe25-Apr-07 10:24 
QuestionInit() method hangs up Pin
DiMann1-Mar-07 10:54
DiMann1-Mar-07 10:54 
AnswerRe: Init() method hangs up Pin
Ronsch4-Dec-08 22:06
Ronsch4-Dec-08 22:06 
GeneralSource Code para VB Pin
phalcom228-Feb-07 7:37
phalcom228-Feb-07 7:37 
GeneralRe: Source Code para VB Pin
rgf2128-Mar-07 0:45
rgf2128-Mar-07 0:45 
GeneralRe: Source Code para VB Pin
yalenap31-May-07 7:14
yalenap31-May-07 7:14 
AnswerRe: Source Code para VB Pin
cmchuan8-Jul-07 22:11
cmchuan8-Jul-07 22:11 
AnswerRe: Source Code para VB Pin
cmchuan8-Jul-07 22:12
cmchuan8-Jul-07 22:12 
TwainDefs.vb

Imports System
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Namespace TwainLib

Public Class TwProtocol
Public Const Major As Short = 1
Public Const Minor As Short = 9
End Class

#Region " Enums "
<Flags()> Friend Enum TwDG As Short
Control = &H1
Image = &H2
Audio = &H4
End Enum

Friend Enum TwDAT As Short
Null = &H0
Capability = &H1
[Event] = &H2
Identity = &H3
Parent = &H4
PendingXfers = &H5
SetupMemXfer = &H6
SetupFileXfer = &H7
Status = &H8
UserInterface = &H9
XferGroup = &HA
TwunkIdentity = &HB
CustomDSData = &HC
DeviceEvent = &HD
FileSystem = &HE
PassThru = &HF

ImageInfo = &H101
ImageLayout = &H102
ImageMemXfer = &H103
ImageNativeXfer = &H104
ImageFileXfer = &H105
CieColor = &H106
GrayResponse = &H107
RGBResponse = &H108
JpegCompression = &H109
Palette8 = &H10A
ExtImageInfo = &H10B

SetupFileXfer2 = &H301
End Enum

Friend Enum TwMSG As Short
Null = &H0
[Get] = &H1
GetCurrent = &H2
GetDefault = &H3
GetFirst = &H4
GetNext = &H5
[Set] = &H6
Reset = &H7
QuerySupport = &H8

XFerReady = &H101
CloseDSReq = &H102
CloseDSOK = &H103
DeviceEvent = &H104

CheckStatus = &H201

OpenDSM = &H301
CloseDSM = &H302

OpenDS = &H401
CloseDS = &H402
UserSelect = &H403

DisableDS = &H501
EnableDS = &H502
EnableDSUIOnly = &H503

ProcessEvent = &H601

EndXfer = &H701
StopFeeder = &H702

ChangeDirectory = &H801
CreateDirectory = &H802
Delete = &H803
FormatMedia = &H804
GetClose = &H805
GetFirstFile = &H806
GetInfo = &H807
GetNextFile = &H808
Rename = &H809
Copy = &H80A
AutoCaptureDir = &H80B

PassThru = &H901
End Enum

Friend Enum TwRC As Short
Success = &H0
Failure = &H1
CheckStatus = &H2
Cancel = &H3
DSEvent = &H4
NotDSEvent = &H5
XferDone = &H6
EndOfList = &H7
InfoNotSupported = &H8
DataNotAvailable = &H9
End Enum

Friend Enum TwCC As Short
Success = &H0
Bummer = &H1
LowMemory = &H2
NoDS = &H3
MaxConnections = &H4
OperationError = &H5
BadCap = &H6
BadProtocol = &H9
BadValue = &HA
SeqError = &HB
BadDest = &HC
CapUnsupported = &HD
CapBadOperation = &HE
CapSeqError = &HF
Denied = &H10
FileExists = &H11
FileNotFound = &H12
NotEmpty = &H13
PaperJam = &H14
PaperDoubleFeed = &H15
FileWriteError = &H16
CheckDeviceOnline = &H17
End Enum

Friend Enum TwOn As Short
Array = &H3
[Enum] = &H4
One = &H5
Range = &H6
DontCare = -1
End Enum

Friend Enum TwType As Short
Int8 = &H0
Int16 = &H1
Int32 = &H2
UInt8 = &H3
UInt16 = &H4
UInt32 = &H5
Bool = &H6
Fix32 = &H7
Frame = &H8
Str32 = &H9
Str64 = &HA
Str128 = &HB
Str255 = &HC
Str1024 = &HD
Str512 = &HE
End Enum

Friend Enum TwCap As Short
XferCount = &H1
ICompression = &H100
IPixelType = &H101
IUnits = &H102
IXferMech = &H103
BitDepth = &H112B
ImageFileFormat = &H110C
XResolution = &H1118
YResolution = &H1119
ImageWidth = &H1116
ImageLength = &H1117
SupportedSizes = &H1122
XScaling = &H1124
YScaling = &H1125

End Enum

Public Enum TwSS As Short
TwSS_None = &H0
TwSS_A4 = &H1
TwSS_B5Letter = &H2
TwSS_USLetter = &H3
End Enum


Public Enum TwColourType As Short
twBW = 0
twGREY = 1
twRGB = 2
End Enum

Public Enum TwUnit As Short
tw_PICAS = 2
twCENTIMETERS = 1
twINCHES = 0
twPIXELS = 5
twPOINTS = 3
twTWIPS = 4
End Enum

#End Region

<StructLayout(LayoutKind.Sequential, Pack:=2, CharSet:=CharSet.Ansi)> Friend Class TwIdentity
Public Id As IntPtr
Public Version As TwVersion
Public ProtocolMajor As Short
Public ProtocolMinor As Short
Public SupportedGroups As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public Manufacturer As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public ProductFamily As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public ProductName As String
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2, CharSet:=CharSet.Ansi)> Friend Structure TwVersion
Public MajorNum As Short
Public MinorNum As Short
Public Language As Short
Public Country As Short
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public Info As String
End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwUserInterface
Public ShowUI As Short
Public ModalUI As Short
Public ParentHand As IntPtr
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwStatus
Public ConditionCode As Short
Public Reserved As Short
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Structure TwEvent
Public EventPtr As IntPtr
Public Message As Short
End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwImageInfo
Public XResolution As Int32
Public YResolution As Int32
Public ImageWidth As Int32
Public ImageLength As Int32
Public SamplesPerPixel As Int16
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=8)> Public BitsPerSample() As Short
Public BitsPerPixel As Int16
Public Planar As Boolean
Public PixelType As Int16
Public Compression As Short
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwPendingXfers
Public Count As Short
Public EOJ As Integer
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Structure TwFix32
Public Whole As System.Int16
Public Frac As System.UInt32

Public Function ToFloat() As Single
Dim frac_sng As Single
frac_sng = System.Convert.ToSingle(Frac)
Return CType(Whole + (CType(frac_sng, Single) / 65536.0F), Single)
End Function

Public Sub FromFloat(ByVal f As Single)
Dim i As Int32 = CType(((f * 65536.0F) + 0.5F), Int32)
Whole = System.Convert.ToInt16(i / 2 ^ 16)
Frac = System.Convert.ToUInt32((i Or &HFFFF))
End Sub

End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Structure TwFrame
Public Left As TwFix32
Public Top As TwFix32
Public Right As TwFix32
Public Bottom As TwFix32
End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwImageLayout
Public Frame As TwFrame
Public DocumentNumber As Integer
Public PageNumber As Integer
Public FrameNumber As Integer
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwCapability
Public Cap As Short
Public ConType As Short
Public Handle As IntPtr
Public Sub TwCapability(ByVal capIn As TwCap)
Cap = CType(capIn, Short)
ConType = -1
End Sub

Public Sub New(ByVal capIn As TwCap, ByVal sval As Short, ByVal TWType As TwType)
Cap = CType(capIn, Short)
ConType = CType(TwOn.One, Short)
Handle = Twain.GlobalAlloc(&H42, 6)
Dim pv As IntPtr = Twain.GlobalLock(Handle)
Marshal.WriteInt16(pv, 0, CType(TWType, Short))
Marshal.WriteInt32(pv, 2, CType(sval, Short))
Twain.GlobalUnlock(Handle)
End Sub

Public Sub Dispose()
If Not Equals(Handle, IntPtr.Zero) Then
Twain.GlobalFree(Handle)
End If
End Sub

Protected Overrides Sub Finalize()
If Not Equals(Handle, IntPtr.Zero) Then
Twain.GlobalFree(Handle)
End If
End Sub
End Class


End Namespace
AnswerRe: Source Code para VB Pin
cmchuan8-Jul-07 22:14
cmchuan8-Jul-07 22:14 
GeneralRe: Source Code para VB Pin
svincetic13-Nov-09 0:46
svincetic13-Nov-09 0:46 
GeneralRe: Source Code para VB Pin
djdrew17-Dec-09 6:39
djdrew17-Dec-09 6:39 
QuestionRe: Source Code para VB Pin
VBdotnetSara19-Oct-10 18:38
VBdotnetSara19-Oct-10 18:38 
QuestionHow to put this in a HTML page Pin
memovera26-Feb-07 9:40
memovera26-Feb-07 9:40 
Questionproblem with scan area Pin
koncuch20-Feb-07 11:06
koncuch20-Feb-07 11:06 
AnswerRe: problem with scan area Pin
cmchuan8-Jul-07 22:23
cmchuan8-Jul-07 22:23 
GeneralRe: problem with scan area Pin
alien2501-Aug-07 4:32
alien2501-Aug-07 4:32 
GeneralGiving something back Pin
alanmac15-Feb-07 13:17
alanmac15-Feb-07 13:17 
GeneralRe: Giving something back Pin
adnanmn19-Nov-07 21:20
adnanmn19-Nov-07 21:20 
QuestionDirect Scanning Pin
realblue15-Feb-07 7:24
realblue15-Feb-07 7:24 
AnswerRe: Direct Scanning Pin
josepaulino22-Mar-07 18:40
josepaulino22-Mar-07 18:40 
GeneralRe: Direct Scanning Pin
NitinMakwana17-Feb-10 19:34
NitinMakwana17-Feb-10 19:34 
Questionhow to change the source manage user interface Pin
jiuheng4-Feb-07 20:21
jiuheng4-Feb-07 20:21 
GeneralDetecting Scanner event Pin
Armanirani17-Jan-07 19:22
Armanirani17-Jan-07 19:22 
QuestionHow can I suppress the error UI and scanning progress UI? Pin
bgunes10-Jan-07 7:26
bgunes10-Jan-07 7:26 
AnswerRe: How can I suppress the error UI and scanning progress UI? Pin
Jeff Circeo12-Jan-07 6:36
Jeff Circeo12-Jan-07 6:36 

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.