Search code examples
c#.netusbimage-scanner

Get input from a scanner connected to USB port or Serial Port in .net


I am working on an application, where my app need to get input from the scanner in an image format.

This is a wpf application, a scanner is connected to the system, user put the document in scanner and print the button in the application to scan the document and then the application have to save the scanned document as image in system.

I don't want to use any paid component, I believe there must be some inbuilt way to read input from the ports.


Solution

  • Where I work, we wrote a custom wrapper around Windows Image Acquisition. Here's a really simple example that should capture it from the scanner the user selects.

     //Reference "Windows Image Acquisition Library v2.0" on the COM tab.
    
    private void Button1_Click(object sender, EventArgs e)
    {
        var dialog = new WIA.CommonDialog();
        var file = dialog.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType);
        file.SaveFile("C:\Temp\WIA." + file.FileExtension);
    }
    

    If you want to do it without displaying any dialogs, here's an awesome article with some code neatly organized in static functions of a class called WIAScanner: http://miljenkobarbir.com/using-a-scanner-without-dialogs-in-net/

    To use the code from the article, assuming you have one scanner and want to use just that one, or you only want to use the first scanner on the system, you could do:

    private void Button1_Click(object sender, EventArgs e)
    {
        var scannerIds = WIAScanner.GetDevices();
    
        if(scannerIds.Count > 0) {
            var images = WIAScanner.Scan(scannerIds[0]);
    
            //Process the images here.
        }
    }
    

    I hope this helps.