I use the NTWAIN library, found a good solution for interacting with this library, modified it a little. This is actually it:
public class ScanningTwain
{
List<Image> ImagesScan;
DataSource myDS;
TwainSession session;
public ScanningTwain()
{
ImagesScan = new List<Image>();
}
public List<Image> Scan(decimal dpi)
{
ImagesScan.Clear();
var appId = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetExecutingAssembly());
session = new TwainSession(appId);
session.TransferReady += session_TransferReady;
session.DataTransferred += session_DataTransferred;
session.SourceDisabled += session_SourceDisable;
session.Open();
IEnumerable<DataSource> lesSources = session.GetSources();
myDS = lesSources.FirstOrDefault();
myDS.Open();
PixelType typeCouleur = PixelType.Gray;
if (myDS.Capabilities.ICapPixelType.CanSet &&
myDS.Capabilities.ICapPixelType.GetValues().Contains(typeCouleur))
{
myDS.Capabilities.ICapPixelType.SetValue(typeCouleur);
}
TWFix32 DPI = (float)dpi;
if (myDS.Capabilities.ICapXResolution.CanSet &&
myDS.Capabilities.ICapXResolution.GetValues().Contains(DPI))
{
myDS.Capabilities.ICapXResolution.SetValue(DPI);
}
if (myDS.Capabilities.ICapYResolution.CanSet &&
myDS.Capabilities.ICapYResolution.GetValues().Contains(DPI))
{
myDS.Capabilities.ICapYResolution.SetValue(DPI);
}
myDS.Enable(SourceEnableMode.ShowUI, false, System.IntPtr.Zero);
EventWaitHandle session_SourceDisable_Wait = new EventWaitHandle(false, EventResetMode.AutoReset);
session_SourceDisable_Wait.WaitOne();
return ImagesScan;
}
void session_DataTransferred(object sender, NTwain.DataTransferredEventArgs e)
{
if (e.NativeData != IntPtr.Zero)
{
Bitmap img = null;
//Need to save out the data.
Stream s = e.GetNativeImageStream();
BitmapSource bitmapsource = s.ConvertToWpfBitmap();
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
img = new Bitmap(outStream);
}
if (img != null)
{
ImagesScan.Add(img);
}
}
}
void session_SourceDisable(object sender, EventArgs e)
{
myDS.Close();
session.Close();
}
void session_TransferReady(object sender, NTwain.TransferReadyEventArgs e)
{
}
}
The error occurs at the line: myDS.Open () ; in the public List <Image> Scan (decimal dpi) method writes that myDS = null , I suppose this is due to the fact that when this line is executed session.Open () ; DSM does not appear so that you can select a scanner. Although I downloaded DSM from the official site. Thank you in advance for your help!