Try to put KDS values in own namespace and enum.

This commit is contained in:
Eugene Wang
2025-03-09 08:55:45 -04:00
parent 5c15ec3711
commit c8ee66a828
17 changed files with 5569 additions and 87 deletions

341
samples/ScannerTester/MainForm.Designer.cs generated Normal file
View File

@@ -0,0 +1,341 @@
namespace ScannerTester
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
label1 = new Label();
btnSelectScanner = new Button();
groupSettings = new GroupBox();
listFormat = new ComboBox();
label7 = new Label();
boxNamePrefix = new TextBox();
label6 = new Label();
btnOpenFolder = new Button();
btnBrowseFolder = new Button();
boxFolder = new TextBox();
label5 = new Label();
boxLimit = new NumericUpDown();
label4 = new Label();
listDpi = new ComboBox();
label3 = new Label();
lblCurScanner = new Label();
groupTest = new GroupBox();
boxLog = new RichTextBox();
label2 = new Label();
ckShowUI = new CheckBox();
btnStop = new Button();
btnTransfer = new Button();
btnDriverOnly = new Button();
groupSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)boxLimit).BeginInit();
groupTest.SuspendLayout();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 9);
label1.Name = "label1";
label1.Size = new Size(612, 25);
label1.TabIndex = 0;
label1.Text = "Use this tool to see if the scanner can be used with the ScanCloud Scan App";
//
// btnSelectScanner
//
btnSelectScanner.Location = new Point(12, 46);
btnSelectScanner.Name = "btnSelectScanner";
btnSelectScanner.Size = new Size(238, 34);
btnSelectScanner.TabIndex = 1;
btnSelectScanner.Text = "Choose Scanner...";
btnSelectScanner.UseVisualStyleBackColor = true;
btnSelectScanner.Click += btnSelectScanner_Click;
//
// groupSettings
//
groupSettings.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
groupSettings.Controls.Add(listFormat);
groupSettings.Controls.Add(label7);
groupSettings.Controls.Add(boxNamePrefix);
groupSettings.Controls.Add(label6);
groupSettings.Controls.Add(btnOpenFolder);
groupSettings.Controls.Add(btnBrowseFolder);
groupSettings.Controls.Add(boxFolder);
groupSettings.Controls.Add(label5);
groupSettings.Controls.Add(boxLimit);
groupSettings.Controls.Add(label4);
groupSettings.Controls.Add(listDpi);
groupSettings.Controls.Add(label3);
groupSettings.Location = new Point(12, 99);
groupSettings.Name = "groupSettings";
groupSettings.Size = new Size(742, 932);
groupSettings.TabIndex = 2;
groupSettings.TabStop = false;
groupSettings.Text = "Settings";
//
// listFormat
//
listFormat.DropDownStyle = ComboBoxStyle.DropDownList;
listFormat.FormattingEnabled = true;
listFormat.Location = new Point(157, 243);
listFormat.Name = "listFormat";
listFormat.Size = new Size(182, 33);
listFormat.TabIndex = 10;
//
// label7
//
label7.AutoSize = true;
label7.Location = new Point(47, 246);
label7.Name = "label7";
label7.Size = new Size(100, 25);
label7.TabIndex = 9;
label7.Text = "File Format";
//
// boxNamePrefix
//
boxNamePrefix.Location = new Point(157, 207);
boxNamePrefix.Name = "boxNamePrefix";
boxNamePrefix.Size = new Size(182, 31);
boxNamePrefix.TabIndex = 8;
boxNamePrefix.Text = "Capture_";
//
// label6
//
label6.AutoSize = true;
label6.Location = new Point(13, 210);
label6.Name = "label6";
label6.Size = new Size(138, 25);
label6.TabIndex = 7;
label6.Text = "File Name Prefix";
//
// btnOpenFolder
//
btnOpenFolder.Location = new Point(275, 167);
btnOpenFolder.Name = "btnOpenFolder";
btnOpenFolder.Size = new Size(112, 34);
btnOpenFolder.TabIndex = 6;
btnOpenFolder.Text = "Open";
btnOpenFolder.UseVisualStyleBackColor = true;
btnOpenFolder.Click += btnOpenFolder_Click;
//
// btnBrowseFolder
//
btnBrowseFolder.Location = new Point(157, 167);
btnBrowseFolder.Name = "btnBrowseFolder";
btnBrowseFolder.Size = new Size(112, 34);
btnBrowseFolder.TabIndex = 6;
btnBrowseFolder.Text = "Browse...";
btnBrowseFolder.UseVisualStyleBackColor = true;
btnBrowseFolder.Click += btnBrowseFolder_Click;
//
// boxFolder
//
boxFolder.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
boxFolder.Location = new Point(157, 130);
boxFolder.Name = "boxFolder";
boxFolder.Size = new Size(556, 31);
boxFolder.TabIndex = 5;
boxFolder.Text = "Images";
//
// label5
//
label5.AutoSize = true;
label5.Location = new Point(47, 133);
label5.Name = "label5";
label5.Size = new Size(104, 25);
label5.TabIndex = 4;
label5.Text = "Save Folder";
//
// boxLimit
//
boxLimit.Location = new Point(157, 93);
boxLimit.Minimum = new decimal(new int[] { 1, 0, 0, int.MinValue });
boxLimit.Name = "boxLimit";
boxLimit.Size = new Size(182, 31);
boxLimit.TabIndex = 3;
boxLimit.Value = new decimal(new int[] { 1, 0, 0, int.MinValue });
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(35, 95);
label4.Name = "label4";
label4.Size = new Size(116, 25);
label4.TabIndex = 2;
label4.Text = "Transfer Limit";
//
// listDpi
//
listDpi.DropDownStyle = ComboBoxStyle.DropDownList;
listDpi.FormattingEnabled = true;
listDpi.Location = new Point(157, 54);
listDpi.Name = "listDpi";
listDpi.Size = new Size(182, 33);
listDpi.TabIndex = 1;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(111, 57);
label3.Name = "label3";
label3.Size = new Size(40, 25);
label3.TabIndex = 0;
label3.Text = "DPI";
//
// lblCurScanner
//
lblCurScanner.AutoSize = true;
lblCurScanner.Location = new Point(256, 51);
lblCurScanner.Name = "lblCurScanner";
lblCurScanner.Size = new Size(124, 25);
lblCurScanner.TabIndex = 3;
lblCurScanner.Text = "None selected";
//
// groupTest
//
groupTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
groupTest.Controls.Add(boxLog);
groupTest.Controls.Add(label2);
groupTest.Controls.Add(ckShowUI);
groupTest.Controls.Add(btnStop);
groupTest.Controls.Add(btnTransfer);
groupTest.Controls.Add(btnDriverOnly);
groupTest.Location = new Point(760, 99);
groupTest.Name = "groupTest";
groupTest.Size = new Size(1038, 932);
groupTest.TabIndex = 4;
groupTest.TabStop = false;
groupTest.Text = "Test";
//
// boxLog
//
boxLog.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
boxLog.Location = new Point(22, 118);
boxLog.Name = "boxLog";
boxLog.Size = new Size(999, 796);
boxLog.TabIndex = 4;
boxLog.Text = "";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(22, 90);
label2.Name = "label2";
label2.Size = new Size(50, 25);
label2.TabIndex = 3;
label2.Text = "Logs";
//
// ckShowUI
//
ckShowUI.AutoSize = true;
ckShowUI.Location = new Point(451, 43);
ckShowUI.Name = "ckShowUI";
ckShowUI.Size = new Size(253, 29);
ckShowUI.TabIndex = 2;
ckShowUI.Text = "Show driver during capture";
ckShowUI.UseVisualStyleBackColor = true;
//
// btnStop
//
btnStop.Anchor = AnchorStyles.Top | AnchorStyles.Right;
btnStop.Location = new Point(897, 39);
btnStop.Name = "btnStop";
btnStop.Size = new Size(124, 34);
btnStop.TabIndex = 2;
btnStop.Text = "Stop";
btnStop.UseVisualStyleBackColor = true;
btnStop.Click += btnStop_Click;
//
// btnTransfer
//
btnTransfer.Location = new Point(239, 39);
btnTransfer.Name = "btnTransfer";
btnTransfer.Size = new Size(206, 34);
btnTransfer.TabIndex = 1;
btnTransfer.Text = "Start Capture";
btnTransfer.UseVisualStyleBackColor = true;
btnTransfer.Click += btnTransfer_Click;
//
// btnDriverOnly
//
btnDriverOnly.Location = new Point(22, 39);
btnDriverOnly.Name = "btnDriverOnly";
btnDriverOnly.Size = new Size(206, 34);
btnDriverOnly.TabIndex = 0;
btnDriverOnly.Text = "Open Driver UI";
btnDriverOnly.UseVisualStyleBackColor = true;
btnDriverOnly.Click += btnDriverOnly_Click;
//
// MainForm
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1810, 1043);
Controls.Add(groupTest);
Controls.Add(lblCurScanner);
Controls.Add(groupSettings);
Controls.Add(btnSelectScanner);
Controls.Add(label1);
Name = "MainForm";
SizeGripStyle = SizeGripStyle.Show;
Text = "Scanner Tester Utility";
groupSettings.ResumeLayout(false);
groupSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)boxLimit).EndInit();
groupTest.ResumeLayout(false);
groupTest.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Button btnSelectScanner;
private GroupBox groupSettings;
private Label lblCurScanner;
private GroupBox groupTest;
private CheckBox ckShowUI;
private Button btnTransfer;
private Button btnDriverOnly;
private RichTextBox boxLog;
private Label label2;
private Button btnStop;
private ComboBox listDpi;
private Label label3;
private Label label4;
private NumericUpDown boxLimit;
private Label label5;
private Button btnOpenFolder;
private Button btnBrowseFolder;
private TextBox boxFolder;
private TextBox boxNamePrefix;
private Label label6;
private ComboBox listFormat;
private Label label7;
}
}

View File

@@ -0,0 +1,591 @@
using NTwain;
using NTwain.Data;
using NTwain.Data.KDS;
using NTwain.Triplets;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
namespace ScannerTester
{
public partial class MainForm : Form
{
TwainAppSession _twain;
private bool _stopTransfer;
public MainForm()
{
InitializeComponent();
_twain = new TwainAppSession();
_twain.TransferReady += _twain_TransferReady;
_twain.Transferred += _twain_Transferred;
_twain.SourceDisabled += _twain_SourceDisabled;
_twain.AddWinformFilter();
}
private void _twain_SourceDisabled(TwainAppSession sender, TW_IDENTITY_LEGACY e)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_twain.OpenDSM(Handle, SynchronizationContext.Current!);
//_ = _twain.OpenDSMAsync();
}
protected override void OnClosed(EventArgs e)
{
_twain.CloseDSM();
//_ = _twain.CloseDSMAsync();
base.OnClosed(e);
}
private void _twain_Transferred(TwainAppSession sender, TransferredEventArgs e)
{
Invoke(() =>
{
TW_EXTIMAGEINFO extInfo = TW_EXTIMAGEINFO.CreateRequest(TWEI.CAMERA);
e.GetExtendedImageInfo(ref extInfo);
string? camera = null;
foreach (var ei in extInfo.AsInfos())
{
if (ei.ReturnCode == TWRC.SUCCESS)
{
switch (ei.InfoId)
{
//case (TWEI)KDS_TWEI.HDR_PAGENUMBER:
// LogIt($"TWEI_HDR_PAGENUMBER Value = {ei.ReadNonPointerData<int>()}");
// break;
case TWEI.CAMERA:
camera = ei.ReadHandleString(_twain);
LogIt($"{ei.InfoId} Value = {camera}");
break;
}
}
else
{
LogIt($"{ei.InfoId} RC = {ei.ReturnCode}");
}
}
extInfo.Free(_twain);
if (e.Data != null)
{
LogIt($"Received {e.ImageInfo.PixelType} in {e.ImageInfo.Compression} compressed memory image.");
var folder = boxFolder.Text;
if (string.IsNullOrWhiteSpace(folder))
{
folder = "Images";
Directory.CreateDirectory(folder);
boxFolder.Text = folder;
}
var prefix = boxNamePrefix.Text;
if (string.IsNullOrWhiteSpace(prefix))
{
prefix = "Capture_";
boxNamePrefix.Text = prefix;
}
using (var img = System.Drawing.Image.FromStream(e.Data.AsStream()))
{
//var saveFile = img.SaveToSmallestFormat(folder, prefix, lossless: false).ToString();
//LogIt($"File saved to {saveFile}");
}
}
else if (e.FileInfo != null)
{
var info = e.FileInfo.Value;
var path = info.FileName.ToString();
LogIt($"Received {e.ImageInfo.PixelType} {info.Format} in {e.ImageInfo.Compression} compressed file {path}");
}
e.Dispose();
LogIt("");
});
}
int _xferCount = 0;
private void _twain_TransferReady(TwainAppSession sender, TransferReadyEventArgs e)
{
Invoke(() =>
{
if (_stopTransfer)
{
e.Cancel = CancelType.EndNow;
return;
}
_xferCount++;
LogIt($"Got pending transfer with mode = {e.ImgXferMech}");
if (e.ImgXferMech == TWSX.FILE)
{
var folder = boxFolder.Text;
if (string.IsNullOrWhiteSpace(folder))
{
folder = "Images";
Directory.CreateDirectory(folder);
boxFolder.Text = folder;
}
var prefix = boxNamePrefix.Text;
if (string.IsNullOrWhiteSpace(prefix))
{
prefix = "Capture_";
boxNamePrefix.Text = prefix;
}
TWCP comp = TWCP.NONE;
TW_EXTIMAGEINFO extInfo = TW_EXTIMAGEINFO.CreateRequest((TWEI)KDS_TWEI.HDR_COMPRESSION);
e.GetExtendedImageInfo(ref extInfo);
foreach (var ei in extInfo.AsInfos())
{
if (ei.ReturnCode == TWRC.SUCCESS)
{
switch (ei.InfoId)
{
case (TWEI)KDS_TWEI.HDR_COMPRESSION:
comp = ei.ReadNonPointerData<TWCP>();
LogIt($"{ei.InfoId} Value = {comp}");
break;
}
}
else
{
LogIt($"{ei.InfoId} RC = {ei.ReturnCode}");
}
}
extInfo.Free(_twain);
LogIt($"Compression at ready step = {comp}");
string? targetName = $"{prefix}_{_xferCount:D4}";
TWFF format = TWFF.TIFF;
switch (comp)
{
case TWCP.JPEG:
targetName = $"{prefix}_{_xferCount:D4}.jpg";
format = TWFF.JFIF;
break;
case TWCP.NONE:
targetName = $"{prefix}_{_xferCount:D4}.bmp";
format = TWFF.BMP;
break;
case TWCP.GROUP4:
default:
targetName = $"{prefix}_{_xferCount:D4}.tif";
break;
}
TW_SETUPFILEXFER setup = new()
{
FileName = Path.Combine(folder, targetName),
Format = format
};
var sts = e.SetupFileTransfer(ref setup);
LogIt($"Want to save image as {setup.Format} {setup.FileName}.", sts);
var appId = _twain.AppIdentity;
var srcId = _twain.CurrentSource;
sts = _twain.WrapInSTS(DGControl.SetupFileXfer.Get(ref appId, ref srcId, out setup));
LogIt($"Checked actual file settings as {setup.Format} {setup.FileName}.", sts);
}
LogIt("");
});
}
protected override void OnClosing(CancelEventArgs e)
{
if (_twain.State > STATE.S5)
{
e.Cancel = true;
}
_twain.TryStepdown(STATE.S2);
base.OnClosing(e);
}
private void btnSelectScanner_Click(object sender, EventArgs e)
{
var sts = _twain.ShowUserSelect();
if (sts.IsSuccess && _twain.DefaultSource.Id > 0)
{
if (_twain.State > STATE.S3)
{
_twain.TryStepdown(STATE.S3);
}
sts = _twain.OpenSource(_twain.DefaultSource);
LogIt("Open scanner", sts);
if (sts.IsSuccess)
{
var src = _twain.CurrentSource;
lblCurScanner.Text = $"{src.ProductName} | v{src.Version} | protocol: {src.ProtocolMajor}.{src.ProtocolMinor}";
LoadSettings();
return;
}
}
lblCurScanner.Text = "None selected";
}
private void LogIt(string msg)
{
boxLog.AppendText($"{msg}\n");
}
private void LogIt(string msg, STS sts)
{
if (sts.IsSuccess)
{
boxLog.AppendText($"{msg} result = {sts.RC}\n");
}
else
{
boxLog.AppendText($"{msg} result = {sts.RC} - {sts.ConditionCode}\n");
}
}
private void LoadSettings()
{
var mechs = _twain.Caps.ICAP_XFERMECH.Get();
if (!mechs.Contains(TWSX.FILE))
{
LogIt("File transfer is not supported.");
}
var sts = _twain.Caps.ICAP_XFERMECH.Set(TWSX.FILE);
LogIt("Use file transfer", sts);
if (_twain.Caps.ICAP_UNITS.GetCurrent().FirstOrDefault() != TWUN.INCHES)
{
sts = _twain.Caps.ICAP_UNITS.Set(TWUN.INCHES);
LogIt("Set unit to inches", sts);
}
var dpis = _twain.Caps.ICAP_XRESOLUTION.Get();
listDpi.Items.Clear();
if (dpis.Contains(200))
{
listDpi.Items.Add(200);
listDpi.SelectedItem = 200;
}
else
{
LogIt("200 DPI doesn't appear to be supported.");
}
if (dpis.Contains(300))
{
listDpi.Items.Add(300);
listDpi.SelectedItem = 300;
}
else
{
LogIt("300 DPI doesn't appear to be supported.");
}
var formats = _twain.Caps.ICAP_IMAGEFILEFORMAT.Get();
listFormat.Items.Clear();
foreach (var format in formats)
{
listFormat.Items.Add(format);
}
listFormat.SelectedItem = _twain.Caps.ICAP_IMAGEFILEFORMAT.GetCurrent().FirstOrDefault();
LogIt("");
}
private void btnDriverOnly_Click(object sender, EventArgs e)
{
if (_twain.State != STATE.S4) return;
var sts = _twain.EnableSource(true, true);
LogIt("Show drivers", sts);
LogIt("");
}
private void btnTransfer_Click(object sender, EventArgs e)
{
if (_twain.State != STATE.S4 || !EnsureBoxFolder()) return;
var _isIndustrialKodak = _twain.CurrentSource.ProductName.ToString().StartsWith("KODAK Scanner: i");
if (_isIndustrialKodak)
{
CaptureAsKodakSDMI();
}
else
{
CaptureAsStandardScanner();
}
_stopTransfer = false;
_xferCount = 0;
var sts = _twain.EnableSource(ckShowUI.Checked, false);
LogIt("Start capture", sts);
LogIt("");
}
private void CaptureAsKodakSDMI()
{
LogIt("Attempting Kodak SDMI mode");
LogIt($"Resolution supports {FlattenFlag(_twain.Caps.ICAP_XRESOLUTION.Supports)}");
LogIt($"File format supports {FlattenFlag(_twain.Caps.ICAP_IMAGEFILEFORMAT.Supports)}");
LogIt($"Compression supports {FlattenFlag(_twain.Caps.ICAP_COMPRESSION.Supports)}");
LogIt($"EXTINFO supports {FlattenFlag(_twain.Caps.ICAP_EXTIMAGEINFO.Supports)}");
LogIt("");
var limit = (short)boxLimit.Value;
if (limit > 0) limit *= 2;
var sts = _twain.Caps.CAP_XFERCOUNT.Set(limit);
LogIt($"Set transfer limit {limit}", sts);
sts = _twain.Caps.ICAP_EXTIMAGEINFO.Set(TW_BOOL.True);
LogIt($"Set extimageinfo enabled", sts);
var format = (TWFF)listFormat.SelectedItem!;
sts = _twain.Caps.ICAP_IMAGEFILEFORMAT.Set(format);
LogIt($"Set {format} format.", sts);
if (!sts.IsSuccess)
{
return;
}
LogIt("");
var appId = _twain.AppIdentity;
var srcId = _twain.CurrentSource;
TW_FILESYSTEM fs = new() { InputName = "/Camera_Bitonal_Both" };
sts = _twain.WrapInSTS(DGControl.FileSystem.ChangeDirectory(ref appId, ref srcId, ref fs));
LogIt("Change to bw cameras", sts);
if (sts.IsSuccess)
{
sts = _twain.Caps.CAP_CAMERAENABLED.Set(TW_BOOL.True);
LogIt("Set camera enabled", sts);
var dpi = listDpi.SelectedValue == null ? 300 : Convert.ToInt32(listDpi.SelectedValue);
sts = _twain.Caps.ICAP_XRESOLUTION.Set(dpi);
LogIt("Set x-resolution", sts);
sts = _twain.Caps.ICAP_YRESOLUTION.Set(dpi);
LogIt("Set y-resolution", sts);
if (format != TWFF.BMP)
{
LogIt($"Current format={_twain.Caps.ICAP_IMAGEFILEFORMAT.GetCurrent().First()}");
LogIt($"Current compression={_twain.Caps.ICAP_COMPRESSION.GetCurrent().First()}");
if (_twain.Caps.ICAP_COMPRESSION.Supports.HasFlag(TWQC.SET))
{
sts = _twain.Caps.ICAP_COMPRESSION.Set(TWCP.GROUP4);
LogIt("Set compression to group4", sts);
}
}
}
LogIt("");
fs = new() { FileType = (int)TWFY.CAMERA, InputName = "/Camera_Color_Both" }; sts = _twain.WrapInSTS(DGControl.FileSystem.ChangeDirectory(ref appId, ref srcId, ref fs));
LogIt("Change to color cameras", sts);
if (sts.IsSuccess)
{
sts = _twain.Caps.CAP_CAMERAENABLED.Set(TW_BOOL.True);
LogIt("Set camera enabled", sts);
var dpi = listDpi.SelectedValue == null ? 300 : Convert.ToInt32(listDpi.SelectedValue);
sts = _twain.Caps.ICAP_XRESOLUTION.Set(dpi);
LogIt("Set x-resolution", sts);
sts = _twain.Caps.ICAP_YRESOLUTION.Set(dpi);
LogIt("Set y-resolution", sts);
if (format != TWFF.BMP)
{
LogIt($"Current format={_twain.Caps.ICAP_IMAGEFILEFORMAT.GetCurrent().First()}");
LogIt($"Current compression={_twain.Caps.ICAP_COMPRESSION.GetCurrent().First()}");
if (_twain.Caps.ICAP_COMPRESSION.Supports.HasFlag(TWQC.SET))
{
sts = _twain.Caps.ICAP_COMPRESSION.Set(TWCP.JPEG);
LogIt("Set compression to jpg", sts);
if (sts.IsSuccess)
{
LogIt($"jpeg quality supports {FlattenFlag(_twain.Caps.ICAP_JPEGQUALITY.Supports)}");
short quality = 90;
sts = _twain.Caps.ICAP_JPEGQUALITY.Set((TWJQ)quality);
LogIt($"Set jpg quality to {quality}", sts);
if (!sts.IsSuccess)
{
quality = 85;
sts = _twain.Caps.ICAP_JPEGQUALITY.Set((TWJQ)quality);
LogIt($"Set jpg quality to {quality}", sts);
if (!sts.IsSuccess)
{
sts = _twain.Caps.ICAP_JPEGQUALITY.Set(TWJQ.HIGH);
LogIt($"Set jpg quality to {TWJQ.HIGH}", sts);
}
}
}
}
}
}
LogIt("");
}
const ushort TWQC_MACHINE = 0x1000;// applies to entire session/machine
const ushort TWQC_BITONAL = 0x2000; // applies to Bitonal "cameras"
const ushort TWQC_COLOR = 0x4000; // applies to Color "cameras"
[Flags]
public enum TWQC2 : ushort
{
MACHINE = 0x1000,
BITONAL = 0x2000,
COLOR = 0x4000
}
private string FlattenFlag(TWQC val)
{
StringBuilder sb = new();
foreach (var type in Enum.GetValues(typeof(TWQC)))
{
if (((ushort)val & (ushort)type) > 0)
{
sb.Append(type).Append(", ");
}
}
foreach (var type in Enum.GetValues(typeof(TWQC2)))
{
if (((ushort)val & (ushort)type) > 0)
{
sb.Append(type).Append(", ");
}
}
if (sb.Length > 0)
{
sb.Length = sb.Length - 2;
}
return sb.ToString();
}
private void CaptureAsStandardScanner()
{
LogIt("Attempting Standard Scanner mode");
var sts = _twain.Caps.ICAP_PIXELTYPE.Set(TWPT.RGB);
LogIt("Set rgb pixel type", sts);
if (_twain.Caps.CAP_DUPLEXENABLED.Supports.HasFlag(TWQC.SET))
{
sts = _twain.Caps.CAP_DUPLEXENABLED.Set(TW_BOOL.True);
LogIt("Set duplex enabled", sts);
}
var dpi = listDpi.SelectedValue == null ? 300 : Convert.ToInt32(listDpi.SelectedValue);
sts = _twain.Caps.ICAP_XRESOLUTION.Set(dpi);
LogIt("Set x-resolution", sts);
sts = _twain.Caps.ICAP_YRESOLUTION.Set(dpi);
LogIt("Set y-resolution", sts);
if (listFormat.SelectedItem != null)
{
var format = (TWFF)listFormat.SelectedItem;
sts = _twain.Caps.ICAP_IMAGEFILEFORMAT.Set(format);
LogIt($"Set {format} format.", sts);
if (!sts.IsSuccess)
{
return;
}
if (format != TWFF.BMP)
{
if (_twain.Caps.ICAP_COMPRESSION.Supports.HasFlag(TWQC.SET))
{
sts = _twain.Caps.ICAP_COMPRESSION.Set(TWCP.JPEG);
LogIt("Set compression to jpg", sts);
if (sts.IsSuccess)
{
short quality = 90;
sts = _twain.Caps.ICAP_JPEGQUALITY.Set((TWJQ)quality);
LogIt($"Set jpg quality to {quality}", sts);
if (!sts.IsSuccess)
{
quality = 85;
sts = _twain.Caps.ICAP_JPEGQUALITY.Set((TWJQ)quality);
LogIt($"Set jpg quality to {quality}", sts);
if (!sts.IsSuccess)
{
sts = _twain.Caps.ICAP_JPEGQUALITY.Set(TWJQ.HIGH);
LogIt($"Set jpg quality to {TWJQ.HIGH}", sts);
}
}
}
}
}
}
var limit = (short)boxLimit.Value;
sts = _twain.Caps.CAP_XFERCOUNT.Set(limit);
LogIt($"Set transfer limit {boxLimit.Value}", sts);
}
private void btnStop_Click(object sender, EventArgs e)
{
_stopTransfer = true;
}
private void btnBrowseFolder_Click(object sender, EventArgs e)
{
using FolderBrowserDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
boxFolder.Text = dialog.SelectedPath;
}
}
private void btnOpenFolder_Click(object sender, EventArgs e)
{
if (EnsureBoxFolder())
{
try
{
using var p = Process.Start("explorer.exe", boxFolder.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private bool EnsureBoxFolder()
{
if (!string.IsNullOrEmpty(boxFolder.Text))
{
if (!Directory.Exists(boxFolder.Text))
{
try
{
Directory.CreateDirectory(boxFolder.Text);
}
catch (Exception ex)
{
LogIt($"Failed to ensure save folder: {ex.Message}");
return false;
}
}
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,17 @@
namespace ScannerTester
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new MainForm());
}
}
}

View File

@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<ApplicationManifest>app.manifest</ApplicationManifest>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\NTwain\NTwain.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel element will disable file and registry virtualization.
Remove this element if your application requires this virtualization for backwards
compatibility.
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config.
Makes the application long-path aware. See https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation -->
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2,PerMonitor</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
<!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>