Click here to Skip to main content
15,891,607 members
Articles / Hosted Services / Storage
Tip/Trick

WIA Scanner in C# Windows Forms

Rate me:
Please Sign up or sign in to vote.
5.00/5 (19 votes)
4 Jul 2014CPOL 214.5K   42K   36   41
How to use WIA supported scanner using C#

Image 1

Introduction

This project is used to show how to use WIA Windows Image Acquisition supported Scanner. Using this project, we can scan applications from scanner and save into specific location automatically.

Background

With this project, we can learn how we can Access Scanners through C#. For this project, we need two things:

  1. WIA DLL
  2. WIA class

WIA dll is available in my resource file.

You can add this WIA class and there is no need to change anything.

C#
class WIAScanner
    {
        const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";
        class WIA_DPS_DOCUMENT_HANDLING_SELECT
        {
            public const uint FEEDER = 0x00000001;
            public const uint FLATBED = 0x00000002;
        }
        class WIA_DPS_DOCUMENT_HANDLING_STATUS
        {
            public const uint FEED_READY = 0x00000001;
        }
        class WIA_PROPERTIES
        { 
            public const uint WIA_RESERVED_FOR_NEW_PROPS = 1024;
            public const uint WIA_DIP_FIRST = 2;
            public const uint WIA_DPA_FIRST = WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
            public const uint WIA_DPC_FIRST = WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
            //
            // Scanner only device properties (DPS)
            //
            public const uint WIA_DPS_FIRST = WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
            public const uint WIA_DPS_DOCUMENT_HANDLING_STATUS = WIA_DPS_FIRST + 13;
            public const uint WIA_DPS_DOCUMENT_HANDLING_SELECT = WIA_DPS_FIRST + 14;
        }
         /// <summary>
        /// Use scanner to scan an image (with user selecting the scanner from a dialog).
        /// </summary>
        /// <returns>Scanned images.</returns>
        public static List<Image> Scan()
        {
            WIA.ICommonDialog dialog = new WIA.CommonDialog();
            WIA.Device device = dialog.ShowSelectDevice
                (WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
            if (device != null)
            {
                return Scan(device.DeviceID);
            }
            else
            {
                throw new Exception("You must select a device for scanning.");
            }
        }
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
      public static List<Image> Scan(string scannerId)
        {
            List<Image> images = new List<Image>();
            bool hasMorePages = true;
            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device device = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }
                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found. 
                    Available Devices:\n" + availableDevices);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
        WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item,wiaFormatBMP                                                                           , false);
                      // save to temp file
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.Properties)
                    {
                    if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                            documentHandlingSelect = prop;
                    if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                            documentHandlingStatus = prop;
                    }
                    // assume there are no more pages
                    hasMorePages = false;
                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // check for document feeder
                        if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & 
                        WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                        {
                            hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & 
                            WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                        }
                    }
                }
            }
            return images;
        }
        /// <summary>
        /// Gets the list of available WIA devices.
        /// </summary>
        /// <returns></returns>
        public static List<string> GetDevices()
        {
            List<string> devices = new List<string>();
            WIA.DeviceManager manager = new WIA.DeviceManager();
            foreach (WIA.DeviceInfo info in manager.DeviceInfos)
            {
                devices.Add(info.DeviceID);
            }
            return devices;
        }
    }

Using the Code

I have created a UserInterface design like this:

Image 2

Here Scan button is used to trigger the event to scan the objects placed in Scanner. I have used panel control to show scanned image.

After scanning the object placed in Scanner device, the UI will be like this:

Image 3

Image 4

Here, I have saved scanned image into specific location with yyyy-MM-dd HHmmss format.

Points of Interest

With this project, we can learn how to access local devices like printers, scanners and cameras.

License

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


Written By
Software Developer
India India
Having good experience of developing code for CTI, Scanner, Cammera, Interactive maps for IRP(International Registration Plan)integration and 311 service request maps using different Geocoding API providers.

Comments and Discussions

 
QuestionWIA UI parameters Pin
Antonio Toledo26-Aug-23 3:39
Antonio Toledo26-Aug-23 3:39 
QuestionThanks Pin
Eromv096-Oct-22 16:34
Eromv096-Oct-22 16:34 
PraiseMessage Closed Pin
17-Feb-22 22:25
Resha Soni17-Feb-22 22:25 
PraiseMessage Closed Pin
17-Feb-22 22:22
Resha Soni17-Feb-22 22:22 
PraiseMessage Closed Pin
17-Feb-22 22:14
Resha Soni17-Feb-22 22:14 
QuestionVery Helpful ! Thanks Pin
Paul Chu27-Oct-21 19:50
Paul Chu27-Oct-21 19:50 
Questionvalue does not fall within the expected range Pin
sany116-Jun-21 21:30
sany116-Jun-21 21:30 
GeneralMy vote of 5 Pin
Deniz Akin20-Jan-21 8:04
Deniz Akin20-Jan-21 8:04 
QuestionAlways return true when hasmorepage is validated Pin
Edson Nieto9-Jul-19 4:10
Edson Nieto9-Jul-19 4:10 
QuestionScan the image connected the mobile device Pin
Member 138907957-Dec-18 21:46
Member 138907957-Dec-18 21:46 
QuestionHelp me, please Pin
__Radik__21-Nov-17 0:46
__Radik__21-Nov-17 0:46 
QuestionChange Height and Width Pin
Member 1295166520-Nov-17 23:31
Member 1295166520-Nov-17 23:31 
QuestionHow to ADF? Pin
Member 1239823712-Sep-17 1:51
Member 1239823712-Sep-17 1:51 
Questionappear error message you dont have any WAI device Pin
Member 1246467624-Apr-17 23:00
Member 1246467624-Apr-17 23:00 
QuestionHow to save to a specific location? Pin
alfred angkasa2-Nov-16 15:36
alfred angkasa2-Nov-16 15:36 
QuestionThanks for this useful information Pin
Member 999352020-Aug-16 0:33
Member 999352020-Aug-16 0:33 
QuestionHow to set the alternate light source Pin
Wolfgang Kurz23-Jun-16 22:07
professionalWolfgang Kurz23-Jun-16 22:07 
Hello Chakravarthi,

I want to write an application which is capable to scan sections of a cine film ( 5 cm to 20 cm long - according to the TPU width of the selected scanner). From these film section (called strips) the contained frames shall be extracted to get an array of consecutive film images (called frames). These frames shall be used to generate a video either in SD [576x768 pixels] or HD - 720P [720x1280 pixels] or 1080i [1080 x 1920 pixels].

The WIA device properties contain definitions for the alternate light source.
These are WIA_DPS_TRANSPARENCY with the flags: WIA_LIGHT_SOURCE_PRESENT_DETECT, WIA_LIGHT_SOURCE_PRESENT,
WIA_LIGHT_SOURCE_DETECT_READY,WIA_LIGHT_SOURCE_READY as well as
WIA_DPS_TRANSPARENCY_SELECT with the flags WIA_LIGHT_SOURCE_SELECT.

As I have zero experience in developing C++ and COM code, can you please tell me how to select the tranparency unit (the alternative light source) using C# (and your scannner class provided above) in order to scan also transparent documents with this class. Is it also possible to specify a constant for the JPG format (according to
C#
const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";

Many thanks for any hint how to set up the scanning of transparent documents.

Best regards
Wolfgang

see also: here
This is the site where the cine film generation process is described. The reason, why a new cine strip scanner is needed is because the ScanController described in this documentation no longer works under Windows 10 (64 or 32 Bit).

A screenshot of the envisaged user interface main window (generated with MS Visual Studio 2015 Community for Windows 10 32 Bit using WPF) you can see here:
http://wkurz.com/upload/Scrennshot_MainWindow.jpg
Currently working: the selection of the envisaged scanner (with WIA Driver installed - in my case an EPSON PERFECTION 4990 PHOTO or an EPSON PERFECTION V750 PRO).
Not working: the TPU scanning and the image transfer.
Question[Solved] How to get the human readable name of a selected WIA scanner Pin
Wolfgang Kurz22-Jun-16 2:54
professionalWolfgang Kurz22-Jun-16 2:54 
AnswerRe: [Solved] How to get the human readable name of a selected WIA scanner Pin
AbdulAziz Alotaibi16-Mar-22 9:46
AbdulAziz Alotaibi16-Mar-22 9:46 
QuestionHow to change DPI or size? Pin
Boris Brock1-Feb-16 6:23
Boris Brock1-Feb-16 6:23 
QuestionHow i increase scan image width. When i scan image it comming 50% only ? Pin
aarif moh shaikh3-Dec-15 23:13
professionalaarif moh shaikh3-Dec-15 23:13 
AnswerRe: How i increase scan image width. When i scan image it comming 50% only ? Pin
Member 1295166520-Nov-17 23:35
Member 1295166520-Nov-17 23:35 
QuestionUsing WIA to capture Image from camera Pin
ahmedfaruk8817-Nov-15 1:23
ahmedfaruk8817-Nov-15 1:23 
QuestionHow to duplex scanning ? Pin
thucap22-Oct-15 23:59
thucap22-Oct-15 23:59 
BugHRESULT E_FAIL Pin
Member 117521108-Jun-15 22:16
Member 117521108-Jun-15 22:16 

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.