A C++ Wrapper for TWAIN


This article was contributed by Rajiv Ramachandran.

Environment: VC6 SP2, NT4 SP5, CE 2.11

One of my applications needed some scanner support. I thought it might be a good idea to get into TWAIN and try it out. Well, here are the results.

Firstly, this is NOT a complete implementation of the TWAIN specification. I have followed version 1.8 and have used just the basic functionality to get an image from a scanner, actually , multiple images too can be acquired one after another. By the way - it will work with didigtal cameras too - anything which exports a TWAIN interface is supported.

Well, lets delve a little further into it. Before we do that though, I would have to mention that I will not be able to tell you all about TWAIN here. You can download the specification at http://www.twain.org. They also have a sample Twain source, if you do not have a scanner and wish to try out TWAIN.

For our purposes here, the important things are the Data Source Manager (DSM) and the Data Source (DS) itself. The DS is the actual scanner or digital camera or any other source which implements TWAIN. The DSM is the module that provides us an interface to the DSM. And yes, this is a very simplistic view of TWAIN ( I shudder to think of what the TWAIN designers would make of my description ).

Now for the class itself. First, the header Twain.h has to be included. I've called my class, rather unimaginatively CTwain. Now this class requires the TWAIN_32.DLL module to be loaded. The way I have handled it is by keeping a static Module handle and incrementing and decrementing the reference count. When the interface is released for the last time, the module is unloaded.

Mostly, the class is quite independant of everything else. What it does require though, is a handle to window to which the DSM can send messages. These messages are not meant for the application itself but for Twain implementor, in this case CTwain. This window handle can be passed either to the constructor, or if as is more likely, if the window isn`t ready yet, in a call to InitTwain.

The CTwain class is an abstract class as it has one pure virtual method. So to use this class you will have to derive from CTwain.

I will now explain the important methods - the ones which will let you start scanning .

CTwain(HWND hWnd= NULL) -- Constructor
The hwnd is optional. If a non Null value is given, the Twain interface is initialized using this handle.
~CTwain() -- Destructor
InitTwain(HWND hWnd) -- Initializes TWAIN
This is called by the constructor if the handle passed to the constructor is not null. Else, it can be called later . Loads the Twain Dll and initializes it.
ReleaseTwain() --  Releases Twain interface
NOTE : If TWAIN has been initialized, this must be called before the window handle passed to it is destroyed. Not doing so will result in resource and memory leaks.
GetIdentity()  --  Identitifies application
This is called by InitTwain to initialize the TW_IDENTITY structure. Please refer to twain.h for the structure memnbers and to CTwain::GetIdentity for an example as to how to fill these members. As for now, you need not implement this as long as the default behaviour suits you.
IsValidDriver()  -- Returns true if the Driver was loaded successfully
SourceSelected() -- Returns true if a source was selected successfully
SourceEnabled()  -- Returns true if a source is enabled
In TWAIN parlance, a source being enabled means a scan is in progress.
SelectDefaultSource() -- Selects the default source for the current machine
SelectSource() -- Shows the Select Source Dialog box and allows the user to select one
Acquire(int numImages=1) -- Starts image acquisition
This does not necessarily mean the scanning process is started. All it actually means is that the Source has been enabled and typically a Scanning parameters dialog box has been opened. Scanning typically starts from there. numImages is the number of images that the application can handle or TWCPP_ANYCOUNT for any number.
ProcessMessage(MSG msg) -- Processes messages from Twain
This should be called from the message loop of the window which is intially passed to the class. NOTE : All messages can be passed to this routine. It ignores all Non-Twain messages and will not act on them unless the source is enabled - so it is not a performance botte-neck either.
ShouldTransfer(TW_IMAGEINFO& info)
This is called every time an image is to be scanned. It should return one of the following values : TWCPP_CANCELTHIS : Cancel this image transfer TWCPP_CANCELALL : Abort all transfers TWCPP_DOTRANSFER : Continue with transfer The default implementation returns TWCPP_DOTRANSFER.
CopyImage(HANDLE hBitmap,TW_IMAGEINFO& info)
This is a pure virtual method which will get called everytime an image is transferred from TWAIN. How the image is to be used is upto the application.

Well - these are the routines you would typically use . You can probably do a lot more too, but the TWAIN specification can probably help you a lot more there than I can.

Now for the demo application.

What I have done is used mutiple inheritance with regard to CMainFrame. I figured that would be the simplest way to handle things. So CMainFrame is derived from CTwain. InitTwain is called from the OnCreate member of CMainFrame. Though the destructor would automatically be called when the window closes, the window handle would not be valid at that time. So I call ReleaseTwain from the OnDestroy member function of CMainFrame.

The two additions to the File Menu are

  • Select Source
  • Acquire

Select Source shows the default dialog which lists the TWAIN sources available. Acquire starts the actual acquisition process.

CTwain::ProcessMessage is called from the PreTranslateMessage member of CMainFrame.

Also CMainFrame implements CopyImage. This in turn calls CMainFrame::SetImage which creates a new document along with a frame and assigns the bitmap scanned to that document. So as new images are scanned new documents are created.

I guess thats it as far as explanations go. I will now very briefly just go through the steps required to start scanning .

First , create a class derived from CTwain. Implement CopyImage to handle bitmaps. Bitmaps are sent as a handle to a Device Independant Bitmap . In the demo app , this is handled with a class -CDIB .

Now in the pretranslate member of the window`s class, insert this line :

ProcessMessage(*pMsg);

Add the two menu items - Select Source and Acquire as done in CMainFrame in the demo app.

And well - you`re done. Thats it - the only thing you really have to work on is CopyImage.

Downloads

Download demo project - 11 Kb
Download source - 56 Kb


Comments

  • Interesting

    Posted by snareenactina on 11/06/2012 07:44pm

    All government behavior involves controlling. Should government control be beyond a certain limit, market efficiency would be definitely affected, and in the end, under the circumstance of protecting some people's interests and rights, it may lead to harming some other people's interests and rights to a great extent, and on the whole the economic freedom as well. Nevertheless, some control is required, which on the one hand can safeguard interests of social groups and the country, and at the same time push forward social progress and ensure that people freely enjoy their benefits. The rationale to measure market economy standard determines the rational judgment of the range and degree of government intervention in economy and the definition of differential margin when applying to various countries. mash UK | unspecified consultancy faithi scarecrow transitional strapped

    Reply
  • very useful Twain wrapper

    Posted by Pork on 04/03/2004 11:12am

    I have to write a software that aquire from scanner, but I don't have any knowledge about twain interface. I have readed the source code and have learned nuch. Tanks

    Reply
  • Excellent

    Posted by Legacy on 01/15/2004 12:00am

    Originally posted by: stefano

    Very good, thank's for help

    Reply
  • How to use the buffered memory mode transfer?

    Posted by Legacy on 09/12/2003 12:00am

    Originally posted by: Vader

    Version 1.9 includes three different methods to transfer images. I am able to use two of them (Native and Disk File) but I have problems with the third (Buffered Memory). Can anybody help me?
    Thanks.

    • Have a look at this one...

      Posted by chilly32 on 05/12/2005 04:27pm

      You can check out implementation from www.neatcpp.com b.t.w., memory mode was implemented in TWAIN specifically to avoid any buffering, so you are being a little confused here :)

      Reply
    Reply
  • TWAIN dialog disappears

    Posted by Legacy on 08/19/2003 12:00am

    Originally posted by: Hank

    Hi!

    Thank you for making TWAIN easier to use!
    I have a problem when I run your TWAIN sample application: When I cancel the aquire-dialog, it doesn�t appear again when I click on "aquire". In fact, nothing happens. I have to restart the program to see the dialog again and scan another image. This happens only when I cancel BEFORE scanning. If I start scanning and then cancel, the scanning stops and everything keeps working.
    Can you tell me the cause of that error?

    Thanks
    Hank

    Reply
  • how to set the resolution in TWAIN?

    Posted by Legacy on 04/01/2003 12:00am

    Originally posted by: buttonkou

    Use
    DG_CONTROL/DAT_CAPABILITY/MSG_SET
    CAP = ICAP_XRORESOLUTION

    But Xresolution in TW_IMAGEINFO is TW_FIX32,and Item in TWAIN_Frame is TW_uint16,Date type is not the same.


    I do not how to set the resolution using the no same data type!! No Using UI!!

    Reply
  • How do you know when the scaner is finished

    Posted by Legacy on 03/31/2003 12:00am

    Originally posted by: Mat

    I've been playing with the code a little.
    I would like the application to close after it has finished scanning, but I do not know how to check if the scaner has finished. I am scanning to file, not native.

    MAt

    Reply
  • Writing your own twain dialog?

    Posted by Legacy on 03/21/2003 12:00am

    Originally posted by: gokhan

    I need to write a twain program like scanner's dialog comes
    with scanner drivers. I don't need to use special device
    drivers etc.

    I just want to know how to make a ".ds" file which can be
    placed in windir\twain_32\ and how to make it callable from
    any drawing program?

    Please send an email to me if do you have such information.


    Regards.

    Reply
  • Does not acquire full image while trying to scan without UI

    Posted by Legacy on 01/17/2003 12:00am

    Originally posted by: hemanth

    I am writing a user interface for scanner,without using the scanner UI which is provided by vendor(scanner).
    
    When I am trying to acquire the image from the source without using UI the whole image is not acquired. Why?

    Also I want to know what is the default scan area of a scanner.

    Can any body help me on this................

    Thanks

    Reply
  • TWAIN source exemple

    Posted by Legacy on 09/17/2002 12:00am

    Originally posted by: GORMAND Philippe

    Hello ! Exuse me for my english. So i French.

    I donloaded TWainCPP.h an TWainCpp.Cpp, but this file
    is not completed. Them functions are inexistant :

    Shouldtransfert
    SourceElected
    SourceEnabled
    ModalUI
    CanClose
    ShouldContinue
    CopyImage

    Thank you for help !


    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • New IT trends to support worker mobility — such as VDI and BYOD — are quickly gaining interest and adoption. But just as with any new trend, there are concerns and pitfalls to avoid.  Download this paper to learn the most important considerations to keep in mind for your VDI project.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds