private void btnScan_Click(object sender, EventArgs e) { float val = 100;// Convert.ToSingle(combo_DPI.SelectedText); mTwain.Capabilities.XResolution.Set(val); mTwain.Capabilities.YResolution.Set(val); mTwain.Capabilities.PixelType.Set(TwPixelType.RGB); //if (rb_RGB.Checked) //{ // mTwain.Capabilities.PixelType.Set(TwPixelType.RGB); //} //if (rb_BW.Checked) //{ // mTwain.Capabilities.PixelType.Set(TwPixelType.BW); //} //if (rb_Gray.Checked) //{ // mTwain.Capabilities.PixelType.Set(TwPixelType.Gray); //} mTwain.ShowUI = false; mTwain.DisableAfterAcquire = false; mTwain.Acquire(); mTwain.AcquireError += MTwain_AcquireError; mTwain.AcquireCompleted += MTwain_AcquireCompleted; }
private void _scannersListPreview_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { try { _twain32?.Dispose(); _twain32 = new Twain32 { ShowUI = true, IsTwain2Enable = true }; _twain32.OpenDSM(); _twain32.SourceIndex = Scanners.IndexOf(SelectedScanner); _twain32.OpenDataSource(); _twain32.EndXfer += _twain32_EndXfer; _twain32.AcquireCompleted += _twain32_AcquireCompleted; _twain32.AcquireError += _twain32_AcquireError; _twain32.MemXferEvent += _twain32_MemXferEvent; _twain32.Acquire(); if (_scannedImage != null) { SaveImage(); } Environment.ExitCode = (int)ExitCodes.ExitCode.SUCCESS; CustomMessageBox.Show($"Save photo: {Path.GetFileName(_filePath)}\n{_destinationPath}", "Succes", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } catch (Exception ex) { var messagebox = CustomMessageBox.Show(ex.Message, "Scanner Error!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error); if (messagebox == System.Windows.Forms.DialogResult.Yes) { Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_DEVICE_UNREACHABLE; } } finally { _twain32?.CloseDSM(); _twain32?.CloseDataSource(); _twain32.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); this.Close(); } }
private void btnScan_Click(object sender, EventArgs e) { if (MessageBox.Show("您要删除之前的扫描文件吗?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { #region 初始化删除所有文件 foreach (Panel c in pnlImage.Controls) { foreach (PictureBox pic in c.Controls) { pic.Image.Dispose(); pic.Image = null; } } DirectoryInfo dir = new DirectoryInfo(mImagePath); FileInfo[] inf = dir.GetFiles(); foreach (FileInfo finf in inf) { finf.Delete(); } #endregion } float val = 150;// Convert.ToSingle(combo_DPI.SelectedText); mTwain.Capabilities.XResolution.Set(val); mTwain.Capabilities.YResolution.Set(val); //if (rb_RGB.Checked) //{ // mTwain.Capabilities.PixelType.Set(TwPixelType.RGB); //} //if (rb_BW.Checked) //{ mTwain.Capabilities.PixelType.Set(TwPixelType.BW); //} //if (rb_Gray.Checked) //{ // mTwain.Capabilities.PixelType.Set(TwPixelType.Gray); //} mTwain.ShowUI = true;//chk_ShowUI.Checked; mTwain.Acquire(); aaa(); }
//public static bool _isDataSourceOpen = false; //public static void _twain_TwainStateChanged(object sender, Twain32.TwainStateEventArgs e) //{ // try // { // // ... // _isDataSourceOpen = (e.TwainState & Twain32.TwainStateFlag.DSOpen) != 0; // // ... // MessageBox.Show("twain 상태가 변경되었습니다."); // } // catch (Exception ex) // { // // ... // } //} //public static void timer1_Tick(object sender, EventArgs e) //{ // using (Twain32 PLOCRtwain = new Twain32()) // { // try // { // // MessageBox.Show("타이머 작동 확인용 창"); // // if (_isDataSourceOpen) // // { // // ... // var _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // // ... // MessageBox.Show("처방전이 올려졌습니다."); // // } // } // catch (Exception ex) // { // // ... // } // } //} public static Bitmap scanImage() { Bitmap scanedImage = null; try { using (Twain32 PLOCRtwain = new Twain32()) { PLOCRtwain.IsTwain2Enable = true; // DSM(data source manager 를 열기 전에 twain 2.0 버전이상을 쓰겠다고 지정해야함 // PLOCRtwain.Dispose(); // OpenDSM() 에서 보호된 메모리 쓰려고 하는 오류가 생겨서.... 원인을 찾아보고 이 코드는 안 쓰는 방향으로 해야함. PLOCRtwain.OpenDSM(); // PLOCRtwain.SourceIndex = 0; PLOCRtwain.OpenDataSource(); // PLOCRtwain.GetResolutions(); PLOCRtwain.Capabilities.XResolution.Set(300f); // 스캔 해상도 300dpi 로 지정하고, float 로 넣어야 하므로 300f 로 입력 PLOCRtwain.Capabilities.YResolution.Set(300f); PLOCRtwain.ShowUI = false; // twain 사용자 인터페이서를 보이지 않도록 하고 try { if ((PLOCRtwain.IsCapSupported(TwCap.AutoScan) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoScan, false); // 한장씩 처리하기 위해 aucoscan 을 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.AutoFeed) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoFeed, false); // 한장 처리하고 대기하기 위해 autofed 를 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.DuplexEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.DuplexEnabled, true); } PLOCRtwain.AcquireCompleted += (sender, e) => // 이 부분이 Acquire 보다 먼저 나와야 함, 한참 헤멨음 { // scanImage(); // string _file_name = string.Format("{0}\\ScanImage.jpg", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); scanedImage = (Bitmap)PLOCRtwain.GetImage(0); File.Delete(@"C:\Program Files\PLOCR\prescription.png"); scanedImage.Save(@"C:\Program Files\PLOCR\prescription.png"); }; if ((PLOCRtwain.IsCapSupported(TwCap.FeederEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.FeederEnabled, true); // MessageBox.Show("feederenabled"); var _isFeederLoaded = false; while (_isFeederLoaded == false) // 처방전이 ADF 트레이에 올라올 때까지 무한루프를 돌리며 대기, 좋은 방법은 아닌 것 같음 { // MessageBox.Show("feederloaded 루프 안"); _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // 반복해서 현재 feederloaded 상태를 감시 if (_isFeederLoaded == true) // 처방전이 올라왔으면 바로 읽어들이기 시작 { /////////////////// 처방전 스캔 시작 /////////////////////////// //splashPres fmPres = new splashPres(); //fmPres.Owner = DataEdit.ActiveForm; // child form 을 알리고 //fmPres.Show(); // 스캔중 화면을 띄우고 PLOCRtwain.Acquire(); //fmPres.Close(); // 스캔중 화면 닫고 ///////////////// 처방전 스캔 끝 /////////////////////////// // PLOCRtwain.Dispose(); // twain 닫고 // PLOCRtwain.CloseDataSource(); // PLOCRtwain.CloseDSM(); } else if (_isFeederLoaded == false) { } } } // PLOCRtwain.Acquire(); } catch (Exception) { Console.WriteLine("스캐너 옵션을 가져오지 못했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } //PLOCRtwain.CloseDataSource(); //PLOCRtwain.CloseDSM(); } } catch (TwainException) { Console.WriteLine("스캔 오류가 발생했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } return(scanedImage); }
public static Bitmap scanImage() { Bitmap scanedImage = null; try { using (Twain32 PLOCRtwain = new Twain32()) { PLOCRtwain.IsTwain2Enable = true; // DSM(data source manager 를 열기 전에 twain 2.0 버전이상을 쓰겠다고 지정해야함 // PLOCRtwain.Dispose(); // OpenDSM() 에서 보호된 메모리 쓰려고 하는 오류가 생겨서.... 원인을 찾아보고 이 코드는 안 쓰는 방향으로 해야함. PLOCRtwain.OpenDSM(); // PLOCRtwain.SourceIndex = 0; PLOCRtwain.OpenDataSource(); // PLOCRtwain.GetResolutions(); PLOCRtwain.Capabilities.XResolution.Set(300f); // 스캔 해상도 300dpi 로 지정하고, float 로 넣어야 하므로 300f 로 입력 PLOCRtwain.Capabilities.YResolution.Set(300f); PLOCRtwain.ShowUI = false; // twain 사용자 인터페이서를 보이지 않도록 하고 try { if ((PLOCRtwain.IsCapSupported(TwCap.AutoScan) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoScan, false); // 한장씩 처리하기 위해 aucoscan 을 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.AutoFeed) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.AutoFeed, false); // 한장 처리하고 대기하기 위해 autofed 를 false 로 세팅 } if ((PLOCRtwain.IsCapSupported(TwCap.DuplexEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.DuplexEnabled, true); } PLOCRtwain.AcquireCompleted += (sender, e) => // 이 부분이 Acquire 보다 먼저 나와야 함, 한참 헤멨음 { // scanImage(); // string _file_name = string.Format("{0}\\ScanImage.jpg", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); scanedImage = (Bitmap)PLOCRtwain.GetImage(0); File.Delete(@"C:\Program Files\PLOCR\prescription.png"); scanedImage.Save(@"C:\Program Files\PLOCR\prescription.png"); }; if ((PLOCRtwain.IsCapSupported(TwCap.FeederEnabled) & TwQC.Set) != 0) { PLOCRtwain.SetCap(TwCap.FeederEnabled, true); // MessageBox.Show("feederenabled"); var _isFeederLoaded = false; while (_isFeederLoaded == false) // 처방전이 ADF 트레이에 올라올 때까지 무한루프를 돌리며 대기, 좋은 방법은 아닌 것 같음 { // MessageBox.Show("feederloaded 루프 안"); _isFeederLoaded = (bool)PLOCRtwain.GetCurrentCap(TwCap.FeederLoaded); // 반복해서 현재 feederloaded 상태를 감시 if (_isFeederLoaded == true) // 처방전이 올라왔으면 바로 읽어들이기 시작 { ///////////////// 처방전 스캔 시작 /////////////////////////// splashPres fmPres = new splashPres(); fmPres.Owner = DataEdit.ActiveForm; // child form 을 알리고 fmPres.Show(); // 스캔중 화면을 띄우고 PLOCRtwain.Acquire(); fmPres.Close(); // 스캔중 화면 닫고 ///////////////// 처방전 스캔 끝 /////////////////////////// // PLOCRtwain.Dispose(); // twain 닫고 // PLOCRtwain.CloseDataSource(); // PLOCRtwain.CloseDSM(); } else if (_isFeederLoaded == false) { } } } // PLOCRtwain.Acquire(); } catch (Exception) { Console.WriteLine("스캐너 옵션을 가져오지 못했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } //PLOCRtwain.CloseDataSource(); //PLOCRtwain.CloseDSM(); } } catch (TwainException) { Console.WriteLine("스캔 오류가 발생했습니다."); System.Diagnostics.Process.GetCurrentProcess().Kill(); // 프로그램 강제 종료 } return scanedImage; }
/// <summary> /// start scanning /// </summary> public void Start() { //logger.Debug("Start"); try { if (!twain.OpenDSM()) { logger.Debug("Не могу найти сканер"); Error(this, new HWErrorEventArgs("Не могу найти сканер")); return; } if (!twain.IsTwain2Supported) { twain.CloseDSM(); twain.IsTwain2Enable = false; twain.OpenDSM(); } } catch (Exception ex) { logger.Error(ex); // TODO: add logging Error(this, new HWErrorEventArgs(ex.Message)); return; } if (selectedScanner.DeviceId != "") { twain.SourceIndex = int.Parse(selectedScanner.DeviceId); } else { logger.Debug("selectedScanner.DeviceId == String.Empty "); } try { if (!twain.OpenDataSource()) { logger.Debug("Не могу установить соединение со сканером"); Error(this, new HWErrorEventArgs("Не могу установить соединение со сканером")); return; } } catch (Exception ex) { logger.Error(ex); // TODO: add logging Error(this, new HWErrorEventArgs(ex.Message)); return; } int dpiResolution = 200; if (System.Configuration.ConfigurationManager.AppSettings["ScannerDpi"] != null) { dpiResolution = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ScannerDpi"]); } setPixelType(); float Height, Weight; int X, Y; //ScanWidht try { Height = float.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanHeight"], System.Globalization.CultureInfo.InvariantCulture) / (float)2.54; Weight = float.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanWidht"], System.Globalization.CultureInfo.InvariantCulture) / (float)2.54; X = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanStartPointX"]); Y = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ScanStartPointY"]); } catch (Exception ex) { Height = 6.6462525f; Weight = 6.6462525f; X = 0; Y = 0; logger.Error(ex); } //задаем область сканирования в точке 0 и размером A6 IsLayoutSet = SetImageLayOut(new RectangleF(new PointF(X, Y), new SizeF(Weight, Height))); //если не смогли задать область сканируем не выше 300 dpi if (IsLayoutSet) { SetResolutions(dpiResolution); } else { SetResolutions(300); } try { twain.Acquire(); } catch (Exception ex) { twain.CloseDSM(); twain.CloseDataSource(); logger.Error(ex); // TODO: add logging Error(this, new HWErrorEventArgs(ex.Message)); return; } }
private void RunTwain() { logger.Debug("Run Twain"); logger.Debug("IsTwain2Supported = {0}", _twain32.IsTwain2Supported); logger.Debug("IsTwain2Enable = {0}", _twain32.IsTwain2Enable); if (_twain32.OpenDataSource() == false) { string text = "Не удалось открыть источник."; logger.Error(text); throw new InvalidOperationException(text); } logger.Debug("DataSource is opened."); #if DEBUG logger.Debug("XferMech.IsSupported=", _twain32.Capabilities.XferMech.IsSupported()); logger.Debug("XferMech Support:"); Twain32.Enumeration xferMech = _twain32.Capabilities.XferMech.Get(); for (int i = 0; i < xferMech.Count; i++) { logger.Debug("[{0}] {1}", i, xferMech[i].ToString()); } logger.Debug("All Capabilities"); foreach (TwCap cap in Enum.GetValues(typeof(TwCap))) { if ((_twain32.IsCapSupported(cap) & TwQC.GetCurrent) != 0) { logger.Debug("{0}(Current) = {1}", cap, _twain32.GetCurrentCap(cap)); } else if ((_twain32.IsCapSupported(cap) & TwQC.Get) != 0) { logger.Debug("{0} = {1}", cap, _twain32.GetCap(cap)); } else { logger.Debug("{0} = skiped", cap); } } #endif _twain32.Capabilities.XferMech.Set(TwSX.Memory); //Feeder if (this._twain32.Capabilities.FeederEnabled.IsSupported(TwQC.Set)) { this._twain32.Capabilities.FeederEnabled.Set(true); logger.Debug("TwCap.FeederEnabled = Enabled"); if (this._twain32.Capabilities.AutoFeed.IsSupported(TwQC.Set)) { this._twain32.Capabilities.AutoFeed.Set(true); logger.Debug("TwCap.AutoFeed = Enabled"); } if (this._twain32.Capabilities.XferCount.IsSupported(TwQC.Set)) { this._twain32.Capabilities.XferCount.Set(-1); logger.Debug("TwCap.XferCount = Enabled"); } } #if DEBUG //Отслеживаем все события _twain32.AcquireCompleted += delegate { logger.Debug("AcquireCompleted fired"); }; _twain32.AcquireError += (sender, e) => logger.Debug("AcquireError fired"); _twain32.DeviceEvent += delegate { logger.Debug("DeviceEvent fired"); }; _twain32.EndXfer += delegate { logger.Debug("EndXfer fired"); }; _twain32.FileXferEvent += delegate { logger.Debug("FileXferEvent fired"); }; _twain32.MemXferEvent += delegate { logger.Debug("MemXferEvent fired"); }; _twain32.SetupFileXferEvent += delegate { logger.Debug("SetupFileXferEvent fired"); }; _twain32.SetupMemXferEvent += delegate { logger.Debug("SetupMemXferEvent fired"); }; _twain32.TwainStateChanged += (object sender, Twain32.TwainStateEventArgs e) => { logger.Debug("TwainStateChanged fired"); logger.Debug("TwainState = {0}", e.TwainState); }; _twain32.XferDone += delegate { logger.Debug("XferDone fired"); }; #endif logger.Debug("Run Acquire"); _twain32.Acquire(); logger.Debug("After Acquire"); }
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView3.Columns[e.ColumnIndex].Name == "btnsm" && e.RowIndex >= 0) { /* string str1 = dataGridView3.Rows[e.RowIndex].Cells[1].Value.ToString(); * string str2 = dataGridView3.Rows[e.RowIndex].Cells[2].Value.ToString(); * string str3 = dataGridView3.Rows[e.RowIndex].Cells[3].Value.ToString(); * string str4 = dataGridView3.Rows[e.RowIndex].Cells[4].Value.ToString(); * string str5 = dataGridView3.Rows[e.RowIndex].Cells[5].Value.ToString(); * Form扫描 form = new Form扫描(str1, str2, str3, str4, str5); * this.Hide(); * form.ShowDialog(); * this.Close();*/ a = dataGridView3.Rows[e.RowIndex].Cells[1].Value.ToString(); mRunPath = System.IO.Directory.GetCurrentDirectory() + "\\"; // mImagePath = mRunPath + "Image\\"; mImagePath = mRunPath + a + "\\"; if (Directory.Exists(mImagePath) == false) { Directory.CreateDirectory(mImagePath); } mTwain.Language = TwLanguage.CHINESE_SINGAPORE; if (cnm == 0) { mTwain.IsTwain2Enable = false; mTwain.OpenDSM(); cnm = 1; } List <string> srclst = new List <string>(); for (int i = 0; i < mTwain.SourcesCount; i++) { srclst.Add(mTwain.GetSourceProductName(i)); } combo_Dev.DataSource = srclst; mTwain.EndXfer += twEndXfer; float val = 150; mTwain.Capabilities.XResolution.Set(val); mTwain.Capabilities.YResolution.Set(val); mTwain.Capabilities.PixelType.Set(TwPixelType.BW); mTwain.ShowUI = true; mTwain.Acquire(); } else if (dataGridView3.Columns[e.ColumnIndex].Name == "btnck" && e.RowIndex >= 0) { string str1 = dataGridView3.Rows[e.RowIndex].Cells[1].Value.ToString(); Form3 form = new Form3(str1, pId); form.ShowDialog(); } else if (dataGridView3.Columns[e.ColumnIndex].Name == "btnqk" && e.RowIndex >= 0) { if (MessageBox.Show("您要删除之前的扫描文件吗?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { #region 初始化删除所有文件 DirectoryInfo dir = new DirectoryInfo(System.IO.Directory.GetCurrentDirectory() + "\\" + dataGridView3.Rows[e.RowIndex].Cells[1].Value.ToString() + "\\"); FileInfo[] inf = dir.GetFiles(); foreach (FileInfo finf in inf) { finf.Delete(); } #endregion } } else if (dataGridView3.Columns[e.ColumnIndex].Name == "btntc" && e.RowIndex >= 0) { /* p = new Process(); * //需要启动的程序 * p.StartInfo.FileName = @"D:\scan\NAPS2\NAPS2.exe"; * //为了美观,启动的时候最小化程序 * // p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; * //启动 * p.Start(); * * //这里必须等待,否则启动程序的句柄还没有创建,不能控制程序 * /* Thread.Sleep(10000); * //最大化启动的程序 * ShowWindow(p.MainWindowHandle, (short)ShowWindowStyles.SW_MAXIMIZE); * //设置被绑架程序的父窗口 * SetParent(p.MainWindowHandle, this.Handle); * //改变尺寸 * ResizeControl();*/ string dangId = dataGridView3.Rows[e.RowIndex].Cells[1].Value.ToString(); string mImagePath = ""; index1 = -1; lstImgPath = new List <string>(); DataTable dt = new ZLXIBAL().Select1128(pId); string aaaa = dt.Rows[0][0].ToString(); aaaa = aaaa.Replace("\\", "\\\\"); // mImagePath = mRunPath + a + "\\"; mImagePath = aaaa + "\\" + dangId; // string[] files = Directory.GetFiles((System.IO.Directory.GetCurrentDirectory() + "\\" + dangId + "")); string[] files = Directory.GetFiles((mImagePath + "")); filescpoy1 = files; cnt111 = files.Length; for (int i = 0; i < files.Length; i++) { if (files[i].EndsWith(".png", true, null) || files[i].EndsWith(".bmp", true, null) || files[i].EndsWith(".jpg", true, null) || files[i].EndsWith(".gif", true, null)) { lstImgPath.Add(files[i]); } } string[] options = new string[lstImgPath.Count]; for (int i = 0; i < lstImgPath.Count; i++) { options[i] = lstImgPath[i]; } // options[0] = "C:\\Users\\jnu\\pictures\\微信图片_20181017171157.jpg"; // options[1] = "C:\\Users\\jnu\\pictures\\微信图片_20181017171157.jpg"; RUN(options); } }
private void btnScan_Click(object sender, EventArgs e) { if (HasErrors()) { return; } SetImage(null); _images.Clear(); try { if (cbxResolution.SelectedItem != null) { var resolution = float.Parse(cbxResolution.SelectedItem.ToString()); _twain.Capabilities.XResolution.Set(resolution); _twain.Capabilities.YResolution.Set(resolution); } if (rbtnRGB.Checked) { _twain.Capabilities.PixelType.Set(Saraff.Twain.TwPixelType.RGB); } if (rbtnBW.Checked) { _twain.Capabilities.PixelType.Set(Saraff.Twain.TwPixelType.BW); } if (rbtnGray.Checked) { _twain.Capabilities.PixelType.Set(Saraff.Twain.TwPixelType.Gray); } if (chkDuplex.Enabled) { if (chkDuplex.Checked) { if ((_twain.IsCapSupported(TwCap.FeederEnabled) & TwQC.Set) != 0) { _twain.SetCap(TwCap.FeederEnabled, true); if ((_twain.IsCapSupported(TwCap.XferCount) & TwQC.Set) != 0) { _twain.SetCap(TwCap.XferCount, (short)-1); } if ((_twain.IsCapSupported(TwCap.DuplexEnabled) & TwQC.Set) != 0) { _twain.SetCap(TwCap.DuplexEnabled, true); } } } } if (chkADF.Enabled) { if (chkADF.Checked) { _twain.SetCap(TwCap.FeederEnabled, true); } else { _twain.SetCap(TwCap.FeederEnabled, false); } } _previewing = false; _twain.Acquire(); } catch (TwainException ex) { LogFactory.CreateLog().LogError(ex); MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Cursor = Cursors.WaitCursor; btnScan.Enabled = false; btnPreview.Enabled = false; btnCancel.Enabled = false; RefreshControlsState(); }
static void Main(string[] args) { isSilenced = !(indexOf(args, "-s") >= 0); var d = indexOf(args, "-d"); if (d >= 0 && args.Length > d + 1) { float.TryParse(args[d + 1], out dpi); } var p = indexOf(args, "-p"); if (p >= 0 && args.Length > p + 1) { string val = args[p + 1].ToUpper(); if (val == "BW") { pt = (TwPixelType)0; } if (val == "Gray") { pt = (TwPixelType)1; } if (val == "RGB") { pt = (TwPixelType)2; } if (val == "Palette") { pt = (TwPixelType)3; } if (val == "CMY") { pt = (TwPixelType)4; } if (val == "CMYK") { pt = (TwPixelType)5; } if (val == "YUV") { pt = (TwPixelType)6; } if (val == "YUVK") { pt = (TwPixelType)7; } if (val == "CIEXYZ") { pt = (TwPixelType)8; } if (val == "LAB") { pt = (TwPixelType)9; } if (val == "SRGB") { pt = (TwPixelType)10; } if (val == "SCRGB") { pt = (TwPixelType)11; } if (val == "INFRARED") { pt = (TwPixelType)16; } } try { using (Twain32 twain = new Twain32()) { var _asm = twain.GetType().Assembly; WriteMessage("{1} {2}{0}{3}{0}", Environment.NewLine, ((AssemblyTitleAttribute)_asm.GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]).Title, ((AssemblyFileVersionAttribute)_asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)[0]).Version, ((AssemblyCopyrightAttribute)_asm.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)[0]).Copyright); twain.ShowUI = false; WriteMessage("ShowUI: {0}", twain.ShowUI ? "true" : "false"); WriteMessage("IsTwain2Enable {0}: ", twain.IsTwain2Enable ? "[Y/n]" : "[y/N]"); if (isSilenced) { for (var _res = Console.ReadLine().Trim().ToUpper(); !string.IsNullOrEmpty(_res);) { twain.IsTwain2Enable = _res == "Y"; break; } } else { twain.IsTwain2Enable = false; } WriteMessage("IsTwain2Enable: {0}", twain.IsTwain2Enable ? "true" : "false"); twain.OpenDSM(); WriteMessage("Select Data Source:"); if (isSilenced) { for (var i1 = 0; i1 < twain.SourcesCount; i1++) { WriteMessage("{0}: {1}{2}", i1, twain.GetSourceProductName(i1), twain.IsTwain2Supported && twain.GetIsSourceTwain2Compatible(i1) ? " (TWAIN 2.x)" : string.Empty); } } WriteMessage("[{0}]: ", twain.SourceIndex); if (isSilenced) { for (var _res = Console.ReadLine().Trim(); !string.IsNullOrEmpty(_res);) { twain.SourceIndex = Convert.ToInt32(_res); break; } } else { twain.SourceIndex = 0; } WriteMessage(string.Format("Data Source: {0}", twain.GetSourceProductName(twain.SourceIndex))); twain.OpenDataSource(); WriteMessage("Select Resolution:"); var _resolutions = twain.Capabilities.XResolution.Get(); if (isSilenced) { for (var i1 = 0; i1 < _resolutions.Count; i1++) { WriteMessage(true, "{0}: {1} dpi", i1, _resolutions[i1]); } } WriteMessage("[{0}]: ", _resolutions.CurrentIndex); if (isSilenced) { for (var _res = Console.ReadLine().Trim(); !string.IsNullOrEmpty(_res);) { var _val = (float)_resolutions[Convert.ToInt32(_res)]; twain.Capabilities.XResolution.Set(_val); twain.Capabilities.YResolution.Set(_val); break; } } else { twain.Capabilities.XResolution.Set(dpi); twain.Capabilities.YResolution.Set(dpi); } WriteMessage("Resolution: {0}", twain.Capabilities.XResolution.GetCurrent()); WriteMessage("Select Pixel Type:"); var _pixels = twain.Capabilities.PixelType.Get(); if (isSilenced) { for (var i1 = 0; i1 < _pixels.Count; i1++) { WriteMessage("{0}: {1}", i1, _pixels[i1]); } } WriteMessage("[{0}]: ", _pixels.CurrentIndex); if (isSilenced) { for (var _res = Console.ReadLine().Trim(); !string.IsNullOrEmpty(_res);) { var _val = (TwPixelType)_pixels[Convert.ToInt32(_res)]; twain.Capabilities.PixelType.Set(_val); break; } } else { twain.Capabilities.PixelType.Set(pt); } WriteMessage(string.Format("Pixel Type: {0}", twain.Capabilities.PixelType.GetCurrent())); twain.EndXfer += (object sender, Twain32.EndXferEventArgs e) => { try { var _file = Path.Combine("", Path.ChangeExtension(Path.GetFileName(Path.GetTempFileName()), ".jpg")); e.Image.Save(_file, ImageFormat.Jpeg); WriteMessage(true, "Saved in: {0}", _file); e.Image.Dispose(); } catch (Exception ex) { WriteMessage("{0}: {1}{2}{3}{2}", ex.GetType().Name, ex.Message, Environment.NewLine, ex.StackTrace); } }; twain.AcquireCompleted += (sender, e) => { try { WriteMessage("Acquire Completed."); } catch (Exception ex) { Program.WriteException(ex); } }; twain.AcquireError += (object sender, Twain32.AcquireErrorEventArgs e) => { try { WriteMessage("Acquire Error: ReturnCode = {0}; ConditionCode = {1};", e.Exception.ReturnCode, e.Exception.ConditionCode); Program.WriteException(e.Exception); } catch (Exception ex) { Program.WriteException(ex); } }; twain.Acquire(); } } catch (Exception ex) { WriteException(ex); } if (isSilenced) { Console.WriteLine("{0}{1}", Environment.NewLine, "Press any key to exit..."); Console.ReadKey(); } }