Click here to Skip to main content
Click here to Skip to main content
Go to top

A C++ Wrapper for TWAIN

, 7 Feb 2000
Rate this:
Please Sign up or sign in to vote.
A C++ wrapper for TWAIN. Allows you to implement a scanning interface.
  • Download demo executable - 11 Kb
  • Download source files - 56 Kb
  • Sample Image - twaintest.jpg

    <!-- Article Starts -->

    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.

    NOTE: You need to have TWAIN_32.DLL installed on your system for this application to work.

    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 digital 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.

    The class is mostly 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 OnClose 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.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    Share

    About the Author

    Rajiv Ramachandran
    Web Developer
    United States United States
    No Biography provided

    Comments and Discussions

     
    QuestionBug in CTwain:GetImage - a problem caused the program to stop working correctly Pinmembertmjac227-Sep-13 13:39 
    QuestionCloseDS()- Twain Related PinmemberAditya221-Jul-13 0:26 
    Questionwill this twain code work with windows 7 operating system Pinmembersiva jyothi18-Feb-13 23:43 
    AnswerRe: will this twain code work with windows 7 operating system Pinmembercnmmd21-May-13 23:22 
    GeneralRe: will this twain code work with windows 7 operating system Pinmembertmjac227-Sep-13 13:30 
    AnswerRe: will this twain code work with windows 7 operating system Pinmemberimabyter20-Nov-13 4:04 
    QuestionHow to set the Image Type Pinmemberclaudio106015-Nov-12 23:09 
    QuestionFor business, you could try this one Pinmembery_sir22-Jul-12 23:12 
    QuestionUserInterface not work properly PinmemberMember 857373411-Apr-12 14:30 
    GeneralMy vote of 5 Pinmemberrrossenbg21-Oct-11 6:39 
    GeneralMy vote of 5 Pinmembergnegovetc20-Apr-11 11:16 
    GeneralDetect if the Twain Device is a Scanner Pinmemberkingmax_00723-Dec-09 3:48 
    QuestionA bug about the code? Pinmembergrandiose17-Oct-09 17:27 
    Questionhow to rewrite into .net? Pinmemberpclion17-Jun-09 18:20 
    QuestionHow to set DPI? Pinmemberwangshun11-Jun-09 1:49 
    Questionshowui( false) ,work only once Pinmemberxwtzjz12-Mar-09 16:33 
    AnswerRe: showui( false) ,work only once PinmemberClive Neil8-Jan-11 21:32 
    GeneralRe: showui( false) ,work only once PinmemberMember 10210829-Jan-12 13:32 
    GeneralRe: showui( false) ,work only once PinmemberMember 10210829-Jan-12 13:46 
    GeneralGurus HELP please with SelectSource() Pinmembernobutaka.yamazaki11-Aug-08 1:59 
    GeneralRe: Gurus HELP please with SelectSource() Pinmembernobutaka.yamazaki11-Aug-08 2:21 
    Questioncan not return to the demo itself... PinmemberXiaoming Huang27-Feb-08 11:21 
    QuestionTWAIN &#1080; BCB6 PinmemberSpin7ion18-Sep-07 0:38 
    Questionhow to inherit from 'CTwain' in Visual C++ 2005 Pinmembercoocol12-Jul-07 5:09 
    AnswerRe: how to inherit from 'CTwain' in Visual C++ 2005 PinmemberRajiv Ramachandran14-Jul-07 9:47 
    QuestionCtwain and Barcode detection PinmemberRisKhan15-May-07 20:47 
    AnswerRe: Ctwain and Barcode detection Pinmemberimabyter13-Jun-07 2:57 
    QuestionWill it work for a Finger Print Scanner PinmemberVikrant for VC++9-Apr-07 2:07 
    GeneralloadedWaiting for ur reply Pinmembermallik2323-Jan-07 0:11 
    GeneralSave BMP does not work Pinmemberjefft15-Dec-06 0:11 
    QuestionFile Transfer Mode ? Pinmembervovahh20-Nov-06 20:58 
    AnswerRe: File Transfer Mode ? Pinmemberimabyter13-Jun-07 3:08 
    GeneralRe: File Transfer Mode ? Pinmembersiva jyothi9-Oct-12 1:50 
    GeneralRe: File Transfer Mode ? Pinmemberimabyter9-Oct-12 3:23 
    GeneralRe: File Transfer Mode ? Pinmembersiva jyothi11-Oct-12 23:21 
    GeneralThanks for this useful sample. Pinmemberddas779-Nov-06 4:56 
    Generaldirect call to scan function. Pinmembershekharchandra25-Oct-06 1:17 
    Generalmy scanner got smoked Pinmembernapolean99912-Aug-06 15:07 
    GeneralEnumerating TWAIN devices PinmemberAlexEvans17-May-06 14:30 
    One major problem I have with this topic, is in the need to prompt the user to select a TWAIN device from a list.
     
    Is there a way for me to enumerate the current TWAIN devices on a machine (via a USB port), and "Select" the one I want programatically, avoiding the pop-up to the user?
     
    Some code sample will help
     
    Cheers
    Alex
    GeneralRe: Enumerating TWAIN devices Pinmembernenemong29-Jul-07 16:42 
    GeneralRe: Enumerating TWAIN devices Pinmembermaypo19-Oct-10 4:22 
    GeneralEnumerating TWAIN devices PinmemberAlexEvans17-May-06 14:29 
    GeneralThere is something wrong with the user interface Pinmemberlionhaert23-Apr-06 19:47 
    GeneralDialogue base Pinmembertsehonkit8-Jan-06 16:47 
    GeneralRe: Dialogue base Pinmemberlingfengme11-Sep-06 3:16 
    GeneralRe: Dialogue base Pinmemberasdasd@yahoo.com15-Nov-06 23:05 
    GeneralRe: Dialogue base PinmemberHamid Reza Mohammadi25-Feb-07 19:55 
    GeneralRe: Dialogue base PinmemberMarcus Carey26-May-09 19:01 
    GeneralRe: Dialogue base [modified] PinmemberHamid Reza Mohammadi27-May-09 3:52 
    GeneralRe: Dialogue base Pinmemberemule122-Jul-09 7:36 

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

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

    | Advertise | Privacy | Mobile
    Web02 | 2.8.140916.1 | Last Updated 8 Feb 2000
    Article Copyright 2000 by Rajiv Ramachandran
    Everything else Copyright © CodeProject, 1999-2014
    Terms of Service
    Layout: fixed | fluid