Click here to Skip to main content
13,045,566 members (70,647 online)
Click here to Skip to main content
Add your own
alternative version


33 bookmarked
Posted 13 Feb 2014

Automatic Scanner code in C#

, 13 Feb 2014
Rate this:
Please Sign up or sign in to vote.
Scanner automatically scans multiple pages using BackgroundWorker Thread



This application automatically scans the document or photo from the scanner in some particular interval given by the user. We can easily and quickly scan bulk amount of documents (i.e 10,000 pages) with this application.


Normally we can scan the documents using scanner application or WIA (Windows Image Acquisition) driver. For scanning the documents it takes too much time to scan upto 1000 pages.

A basic Windows application runs on a single thread usually referred to as UI thread. This UI thread is responsible for creating/painting all the controls and upon which the code execution takes place.

The BackgroundWorker is designed to let you run heavy or long operations on a separate thread to that of the UI. If you were to run a lengthy process on the UI thread, your UI will most likely freeze until the process completes.

The background worker thread is there to help to offload long running function calls to the background so that the interface will not freeze.

Suppose you have something that takes 5 sec to compute when you click a button. During that time, the interface will appear 'frozen': you won't be able to interact with it.

Synchronous Process

The difference in behavior is because the call to the background worker thread will not execute in the same thread as the interface, freeing it to continue its normal work. If you used the background worker thread instead, the button event would setup the worker thread and return immediately. That will allow the interface to keep accepting new events like other button clicks.

Asynchronous Process

Implementing Automatic Scanning

DoWork event is the starting point for a BackgroundWorker. This event is fired when the RunWorkerAsync method is called. In this event handler, we call our code that is being processed in the background where our application is still doing some other work. 

Thread Process Code:  

private void bgwScan_DoWork(object sender, DoWorkEventArgs e)
            while (!bgwScan.CancellationPending)
                if (newDoc == 0)
                    newDoc = 1;
                for (int k = 1; k <= 10 * (int)nudTime.Value; k++)
                    bgwScan.ReportProgress((int)(k / (int)nudTime.Value));
                    if (k == 10 * (int)nudTime.Value)
                        newDoc = 0;

The above code asynchronously calls the ScanDoc() method until pressing the stop button.  

Image Scanning Code: 

ScanDoc() is the method for scanning the documents from the Scanner.   

private void ScanDoc()
            CommonDialogClass commonDialogClass = new CommonDialogClass();
            Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
            if (scannerDevice != null)
                Item scannnerItem = scannerDevice.Items[1];
                AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex);
                object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatTIFF, false);
                if (scanResult != null)
                    ImageFile image = (ImageFile)scanResult;
                    string fileName = "";
                    var files = Directory.GetFiles(txtPath.Text, "*.tiff");
                        string f = ((files.Max(p1 => Int32.Parse(Path.GetFileNameWithoutExtension(p1)))) + 1).ToString();
                        fileName = txtPath.Text + "\\" + f + ".tiff";
                    catch (Exception ex)
                        fileName = txtPath.Text + "\\" + "1.tiff";
                    SaveImageToTiff(image, fileName);
                    picScan.ImageLocation = fileName;

Scanner Settings Code:  

AdjustScannerSettings is the method to change scanner color mode, document size and crop size.

private static void AdjustScannerSettings(IItem scannnerItem, int scanResolutionDPI, int scanStartLeftPixel, int scanStartTopPixel,
                    int scanWidthPixels, int scanHeightPixels, int brightnessPercents, int contrastPercents, int colorMode)
            const string WIA_SCAN_COLOR_MODE = "6146";
            const string WIA_HORIZONTAL_SCAN_RESOLUTION_DPI = "6147";
            const string WIA_VERTICAL_SCAN_RESOLUTION_DPI = "6148";
            const string WIA_HORIZONTAL_SCAN_START_PIXEL = "6149";
            const string WIA_VERTICAL_SCAN_START_PIXEL = "6150";
            const string WIA_HORIZONTAL_SCAN_SIZE_PIXELS = "6151";
            const string WIA_VERTICAL_SCAN_SIZE_PIXELS = "6152";
            const string WIA_SCAN_BRIGHTNESS_PERCENTS = "6154";
            const string WIA_SCAN_CONTRAST_PERCENTS = "6155";
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, scanResolutionDPI);
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_START_PIXEL, scanStartLeftPixel);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_START_PIXEL, scanStartTopPixel);
            SetWIAProperty(scannnerItem.Properties, WIA_HORIZONTAL_SCAN_SIZE_PIXELS, scanWidthPixels);
            SetWIAProperty(scannnerItem.Properties, WIA_VERTICAL_SCAN_SIZE_PIXELS, scanHeightPixels);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_BRIGHTNESS_PERCENTS, brightnessPercents);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_CONTRAST_PERCENTS, contrastPercents);
            SetWIAProperty(scannnerItem.Properties, WIA_SCAN_COLOR_MODE, colorMode);
        private static void SetWIAProperty(IProperties properties, object propName, object propValue)
            Property prop = properties.get_Item(ref propName);
            prop.set_Value(ref propValue);

Saving Image Code:  

SaveImageToTiff is the method to save the scanned image to tiff image format file. 

private static void SaveImageToTiff(ImageFile image, string fileName)
            ImageProcess imgProcess = new ImageProcess();
            object convertFilter = "Convert";
            string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID;
            imgProcess.Filters.Add(convertFilterID, 0);
            SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", WIA.FormatID.wiaFormatTIFF);
            image = imgProcess.Apply(image);

Further Uses of the Code

In this code can used to consequently load the records from Network Database when the records made changed, it can be done with the Checksum function.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Anand Gunasekaran
Software Developer Azeal Groups
India India
Thinking Innovation. .. ... .... ..... ......

Technologies: .Net, Java, Php, Phython, Android, HTML

You may also be interested in...


Comments and Discussions

Questionthere is a WIA dll missing error Pin
Member 117322732-Mar-17 20:45
memberMember 117322732-Mar-17 20:45 
QuestionDuplex Pleeease Pin
Member 1287383510-Dec-16 21:28
memberMember 1287383510-Dec-16 21:28 
AnswerRe: Duplex Pleeease Pin
OriginalGriff10-Dec-16 21:30
protectorOriginalGriff10-Dec-16 21:30 
QuestionGreat work! Pin
sidz18-May-16 8:18
membersidz18-May-16 8:18 
AnswerWork perfect in VS15 .NET Frame Work 3.5. Pin
Member 1215383319-Nov-15 23:00
memberMember 1215383319-Nov-15 23:00 
QuestionWill this work for any scanner? 2- Is TWAIN necessary for such functionality? Pin
Member 77957107-Sep-15 2:33
memberMember 77957107-Sep-15 2:33 
AnswerRe: Will this work for any scanner? 2- Is TWAIN necessary for such functionality? Pin
Member 1215383319-Nov-15 23:07
memberMember 1215383319-Nov-15 23:07 
QuestionDoesn't work Pin
IARSAN13-Aug-15 14:06
memberIARSAN13-Aug-15 14:06 
QuestionImage does not shown Pin
Raza Hussain1-Jul-15 16:06
memberRaza Hussain1-Jul-15 16:06 
QuestionADF support? Pin
eqiz17-Jun-15 8:45
membereqiz17-Jun-15 8:45 
QuestionHow to scan both side ?? Pin
Member 1168935119-May-15 22:42
memberMember 1168935119-May-15 22:42 
QuestionVirtual Scanner Pin
cronaldo4ever11-Mar-15 10:20
membercronaldo4ever11-Mar-15 10:20 
QuestionDevice not found Pin
Member 1136238827-Feb-15 0:00
memberMember 1136238827-Feb-15 0:00 
QuestionTrès bon projet Pin
tachaaig5-Feb-15 21:40
membertachaaig5-Feb-15 21:40 
QuestionDoesn't works Pin
SpArtA11-May-14 1:02
memberSpArtA11-May-14 1:02 
AnswerRe: Doesn't works Pin
Anand Gunasekaran12-May-14 0:18
professionalAnand Gunasekaran12-May-14 0:18 
GeneralRe: Doesn't works Pin
Member 102193884-Aug-14 15:29
memberMember 102193884-Aug-14 15:29 
AnswerRe: Doesn't works Pin
Anand Gunasekaran6-Aug-14 3:42
professionalAnand Gunasekaran6-Aug-14 3:42 
Questionquestion about SaveImageToTiff method Pin
rickyhu11-Mar-14 17:11
memberrickyhu11-Mar-14 17:11 
GeneralRe: question about SaveImageToTiff method Pin
Anand Gunasekaran12-Mar-14 7:07
professionalAnand Gunasekaran12-Mar-14 7:07 
QuestionError using your code. Please help Pin
Member 104094008-Mar-14 9:19
memberMember 104094008-Mar-14 9:19 
AnswerRe: Error using your code. Please help Pin
Anand Gunasekaran8-Mar-14 23:18
professionalAnand Gunasekaran8-Mar-14 23:18 
GeneralRe: Error using your code. Please help Pin
Member 104094009-Mar-14 14:59
memberMember 104094009-Mar-14 14:59 
SuggestionRe: Error using your code. Please help Pin
Anand Gunasekaran10-Mar-14 3:45
professionalAnand Gunasekaran10-Mar-14 3:45 
GeneralRe: Error using your code. Please help Pin
Member 1040940010-Mar-14 8:24
memberMember 1040940010-Mar-14 8:24 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170713.1 | Last Updated 14 Feb 2014
Article Copyright 2014 by Anand Gunasekaran
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid