private void SetupTwain() { logger.Debug("Setup Twain"); _twain32 = new Twain32(); _twain32.TwainStateChanged += _twain_TwainStateChanged; _twain32.AcquireError += OnTwainAcquireError; if (ScanerSetup == ScanerSetup.Custom) { _twain32.SetupMemXferEvent += OnSetupMemXferEvent; _twain32.MemXferEvent += OnMemXferEvent; } _twain32.AcquireCompleted += _twain32_AcquireCompleted; logger.Debug("IsTwain2Enable = {0}", _twain32.IsTwain2Enable); _twain32.OpenDSM(); logger.Debug("IsTwain2Supported = {0}", _twain32.IsTwain2Supported); logger.Debug("Exist Sources:"); for (var i = 0; i < _twain32.SourcesCount; i++) { logger.Debug("{0}: {1}{2}", i, _twain32.GetSourceProductName(i), _twain32.IsTwain2Supported && _twain32.GetIsSourceTwain2Compatible(i)?" (TWAIN 2.x)" : string.Empty); } logger.Debug("Current Source: {0}", _twain32.GetSourceProductName(_twain32.SourceIndex)); }
private void SetupTwain() { _twain32 = new Twain32 (); _twain32.OpenDSM(); _twain32.AcquireCompleted+=(object sender,EventArgs e) => { TotalImages = _twain32.ImageCount; for(int i = 0; i < _twain32.ImageCount; i++) { Pixbuf CurImg = WinImageToPixbuf(_twain32.GetImage(i)); if(ImageTransfer == null) {// Записываем во внутренний массив Images.Add(CurImg); } else {// Передаем через событие ImageTransferEventArgs arg = new ImageTransferEventArgs(); arg.AllImages = TotalImages; arg.Image = CurImg; ImageTransfer(this, arg); } } Console.WriteLine("DataTransferred"); }; }
private void DisplayScanners() { cbxScanner.Items.Clear(); _twain.OpenDSM(); if (_twain.SourcesCount > 0) { for (int index = 0; index < _twain.SourcesCount; index++) { cbxScanner.Items.Add(_twain.GetSourceProductName(index)); } } }
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 ShowUI() { try { mTwain.Language = TwLanguage.CHINESE_SINGAPORE; mTwain.IsTwain2Enable = false; mTwain.OpenDSM(); List <string> srclst = new List <string>(); for (int i = 0; i < mTwain.SourcesCount; i++) { srclst.Add(mTwain.GetSourceProductName(i)); } scanCmb.DataSource = srclst; mTwain.CloseDSM(); //读取扫描仪配置 if (!string.IsNullOrEmpty(hand.ReadConfig("twIndex"))) { this.scanCmb.SelectedIndex = Convert.ToInt32(hand.ReadConfig("twIndex")); } this.urlTxt.Text = hand.ReadConfig("url"); this.IsAutoCbx.Checked = hand.ReadConfig("autoLogin") == "T" ? true : false; this.saveDayTxt.Text = hand.ReadConfig("saveDay"); //this.saveUrlTxt.Text = hand.ReadConfig("saveUrl"); //if (hand.ReadConfig("isShowConfig") == "T") // this.Yradio.Checked = true; //else // this.Nradio.Checked = true; //this.skinList.DataSource = new DirectoryInfo("Skins").GetFiles(); //this.skinList.DisplayMember = "Name"; } catch (Exception) { Logger.Error("未找到支持TWAIN扫描协议的设备,启动失败!"); MessageBox.Show("未找到支持TWAIN扫描协议的设备,启动失败!"); Application.Exit(); } }
public IEnumerable <HWDeviceDesciption> GetDevices() { var twain = new Twain32(); var isDsmOpened = false; try { //twain.OpenDataSource(); isDsmOpened = twain.OpenDSM(); if (twain.IsTwain2Supported) { twain.IsTwain2Enable = true; } } catch (Exception ex) { logger.Error(ex); } if (isDsmOpened) { for (int i = 0; i < twain.SourcesCount; i++) { yield return(new HWDeviceDesciption { Device = DeviceType.Scanner, Name = twain.GetSourceProductName(i), DeviceId = i.ToString() }); } } if (twain != null) { twain.CloseDataSource(); twain.CloseDSM(); twain.Dispose(); } yield break; }
private void Form扫描_Load(object sender, EventArgs e) { mRunPath = System.IO.Directory.GetCurrentDirectory() + "\\"; // mImagePath = mRunPath + "Image\\"; mImagePath = mRunPath + a + "\\"; if (Directory.Exists(mImagePath) == false) { Directory.CreateDirectory(mImagePath); } mTwain.Language = TwLanguage.CHINESE_SINGAPORE; mTwain.IsTwain2Enable = false; mTwain.OpenDSM(); 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; }
private void LoadParametes() { try { _twain32 = new Twain32 { ShowUI = true, IsTwain2Enable = true }; _twain32.OpenDSM(); #region GetScanners for (int i = 0; i < _twain32.SourcesCount; i++) { _scanners.Add(_twain32.GetSourceProductName(i)); } #endregion GetScanners if (Scanners.Count > 0) { SelectedScanner = Scanners.FirstOrDefault(); } } catch (Exception ex) { var messagebox = CustomMessageBox.Show(ex.Message, "Error!", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Error); if (messagebox == System.Windows.Forms.DialogResult.Yes) { _twain32?.CloseDSM(); _twain32?.CloseDataSource(); _twain32.Dispose(); Environment.ExitCode = (int)ExitCodes.ExitCode.ERROR_DEVICE_UNREACHABLE; this.Close(); } } }
private void FrmDemo_Load(object sender, EventArgs e) { mRunPath = System.IO.Directory.GetCurrentDirectory() + "\\"; mImagePath = mRunPath + "Image\\"; if (Directory.Exists(mImagePath) == false) { Directory.CreateDirectory(mImagePath); } mTwain.Language = TwLanguage.CHINESE_SINGAPORE; mTwain.IsTwain2Enable = true; mTwain.OpenDSM(); List <string> srclst = new List <string>(); //int index = 0; for (int i = 0; i < mTwain.SourcesCount; i++) { //Console.WriteLine("name is:"+mTwain.GetSourceProductName(i)); //if (mTwain.GetSourceProductName(i).Equals(Program.machineName)) //{ srclst.Add(mTwain.GetSourceProductName(i)); // index = i; //} } //Console.WriteLine(index); //if(index == -1) //{ //MessageBox.Show("can not find " + Program.machineName); // return; //} //mTwain.SourceIndex = index; //mTwain.OpenDataSource(); combo_Dev.DataSource = srclst; mTwain.EndXfer += twEndXfer; this.btnScan_Click(null, null); }
//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 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 SetupTwain() { logger.Debug("Setup Twain"); _twain32 = new Twain32 (); _twain32.TwainStateChanged += _twain_TwainStateChanged; _twain32.AcquireError += OnTwainAcquireError; _twain32.SetupMemXferEvent += OnSetupMemXferEvent; _twain32.MemXferEvent += OnMemXferEvent; _twain32.AcquireCompleted += _twain32_AcquireCompleted; logger.Debug ("IsTwain2Enable = {0}", _twain32.IsTwain2Enable); _twain32.OpenDSM(); logger.Debug ("IsTwain2Supported = {0}", _twain32.IsTwain2Supported); logger.Debug ("Exist Sources:"); for(var i=0; i<_twain32.SourcesCount; i++) { logger.Debug("{0}: {1}{2}", i, _twain32.GetSourceProductName(i), _twain32.IsTwain2Supported&&_twain32.GetIsSourceTwain2Compatible(i)?" (TWAIN 2.x)" : string.Empty); } logger.Debug ("Current Source: {0}", _twain32.GetSourceProductName (_twain32.SourceIndex)); }
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(); } }
static TwainFactory() { _twain = new Twain32(); _twain.ShowUI = false; _twain.OpenDSM(); }