调用Twain 直接返回扫描图片

来源:互联网 发布:迪奥西斯形态数据 编辑:程序博客网 时间:2024/06/01 16:55

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.Collections.Generic;


using System.Linq;
using System.Text;

using TwainLib;
using System.Drawing.Imaging;

using TwainGui;

using System.Runtime.InteropServices;
using GdiPlusLib;
using WindowsFormsApplication1;
using System.IO;

namespace TwainGui
{
    public class MainFrame : System.Windows.Forms.Form, IMessageFilter
    {
        private System.Windows.Forms.MdiClient mdiClient1;
        private System.Windows.Forms.MenuItem menuMainFile;
        private System.Windows.Forms.MenuItem menuItemScan;
        private System.Windows.Forms.MenuItem menuItemSelSrc;
        private System.Windows.Forms.MenuItem menuMainWindow;
        private System.Windows.Forms.MenuItem menuItemExit;
        private System.Windows.Forms.MenuItem menuItemSepr;
        private System.Windows.Forms.MainMenu mainFrameMenu;
        private MenuItem menuItem1;
        private IContainer components;

        public MainFrame()
        {
            InitializeComponent();
            tw = new Twain();
            tw.Init(this.Handle);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                tw.Finish();
                if (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()
        {
            this.components = new System.ComponentModel.Container();
            this.menuMainFile = new System.Windows.Forms.MenuItem();
            this.menuItemSelSrc = new System.Windows.Forms.MenuItem();
            this.menuItemScan = new System.Windows.Forms.MenuItem();
            this.menuItemSepr = new System.Windows.Forms.MenuItem();
            this.menuItemExit = new System.Windows.Forms.MenuItem();
            this.mainFrameMenu = new System.Windows.Forms.MainMenu(this.components);
            this.menuMainWindow = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.mdiClient1 = new System.Windows.Forms.MdiClient();
            this.SuspendLayout();
            //
            // menuMainFile
            //
            this.menuMainFile.Index = 0;
            this.menuMainFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemSelSrc,
            this.menuItemScan,
            this.menuItemSepr,
            this.menuItemExit});
            this.menuMainFile.MergeType = System.Windows.Forms.MenuMerge.MergeItems;
            this.menuMainFile.Text = "&操作";
            //
            // menuItemSelSrc
            //
            this.menuItemSelSrc.Index = 0;
            this.menuItemSelSrc.MergeOrder = 11;
            this.menuItemSelSrc.Text = "&選擇掃描機";
            this.menuItemSelSrc.Click += new System.EventHandler(this.menuItemSelSrc_Click);
            //
            // menuItemScan
            //
            this.menuItemScan.Index = 1;
            this.menuItemScan.MergeOrder = 12;
            this.menuItemScan.Text = "&掃描";
            this.menuItemScan.Click += new System.EventHandler(this.menuItemScan_Click);
            //
            // menuItemSepr
            //
            this.menuItemSepr.Index = 2;
            this.menuItemSepr.MergeOrder = 19;
            this.menuItemSepr.Text = "-";
            //
            // menuItemExit
            //
            this.menuItemExit.Index = 3;
            this.menuItemExit.MergeOrder = 21;
            this.menuItemExit.Text = "&退出";
            this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
            //
            // mainFrameMenu
            //
            this.mainFrameMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuMainFile,
            this.menuMainWindow,
            this.menuItem1});
            //
            // menuMainWindow
            //
            this.menuMainWindow.Index = 1;
            this.menuMainWindow.MdiList = true;
            this.menuMainWindow.Text = "&窗口";
            this.menuMainWindow.Click += new System.EventHandler(this.menuMainWindow_Click);
            //
            // menuItem1
            //
            this.menuItem1.Index = 2;
            this.menuItem1.Text = "截图";
            this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
            //
            // mdiClient1
            //
            this.mdiClient1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.mdiClient1.Location = new System.Drawing.Point(0, 0);
            this.mdiClient1.Name = "mdiClient1";
            this.mdiClient1.Size = new System.Drawing.Size(600, 345);
            this.mdiClient1.TabIndex = 0;
            //
            // MainFrame
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(600, 345);
            this.Controls.Add(this.mdiClient1);
            this.IsMdiContainer = true;
            this.Menu = this.mainFrameMenu;
            this.Name = "MainFrame";
            this.Text = "掃描";
            this.Load += new System.EventHandler(this.MainFrame_Load);
            this.ResumeLayout(false);

        }
        #endregion

 

        private void menuItemExit_Click(object sender, System.EventArgs e)
        {
            Close();
        }

        private void menuItemScan_Click(object sender, System.EventArgs e)
        {
            if (!msgfilter)
            {
                this.Enabled = false;
                msgfilter = true;
                Application.AddMessageFilter(this);
            }
            tw.Acquire();
        }

        private void menuItemSelSrc_Click(object sender, System.EventArgs e)
        {
            tw.Select();
        }


        bool IMessageFilter.PreFilterMessage(ref Message m)
        {
            TwainCommand cmd = tw.PassMessage(ref m);
            if (cmd == TwainCommand.Not)
                return false;

            switch (cmd)
            {
                case TwainCommand.CloseRequest:
                    {
                        EndingScan();
                        tw.CloseSrc();
                        break;
                    }
                case TwainCommand.CloseOk:
                    {
                        EndingScan();
                        tw.CloseSrc();
                        break;
                    }
                case TwainCommand.DeviceEvent:
                    {
                        break;
                    }
                case TwainCommand.TransferReady:
                    {
                        ArrayList pics = tw.TransferPictures();
                        EndingScan();
                        tw.CloseSrc();
                        picnumber++;
                        for (int i = 0; i < pics.Count; i++)
                        {
                            IntPtr img = (IntPtr)pics[i];
                            Image retimg = ImageFromIntPtr(img);
                            Immm = retimg;
                           // new FrmSQR("").pictureBox1.Image = retimg;
                          //  PicForm newpic = new PicForm(img);
                          //newpic.MdiParent = this;
                          //  int picnum = i + 1;
                          //  newpic.Text = "ScanPass" + picnumber.ToString() + "_Pic" + picnum.ToString();
                          // newpic.Show();
                            //Graphics g = new Graphics();
                            //Bitmap ga = g.
                            //Graphics get = new GetGraphics(img);
                            //Bitmap b = get.GetImage();
                            //FrmSQR f = ;
                           
                            //f.pictureBox1.Image = (Image)b;
                          //IntPtr bmpptr = GlobalLock(img);
                      //   IntPtr pixptr = GetPixelInfo(bmpptr);
                           // Gdip.SaveDIBAs(this.Text, bmpptr, pixptr);
                        }
                        break;
                    }
            }

            return true;
        }
        public Image ImageFromIntPtr(IntPtr imagePtr)
        {
             bmi = new BITMAPINFOHEADER();

            IntPtr bmpptr = GlobalLock(imagePtr);
            IntPtr pixptr = GetPixelInfo(bmpptr);

            Bitmap bitmap = new Bitmap(bmi.biWidth, bmi.biHeight);
            Graphics graphics = Graphics.FromImage(bitmap);

            IntPtr hdc = graphics.GetHdc();

            SetDIBitsToDevice(hdc, 0, 0, bmi.biWidth, bmi.biHeight,
                    0, 0, 0, bmi.biHeight, pixptr, bmpptr, 0);

            graphics.ReleaseHdc(hdc);

            return (Image)bitmap;
        }

        [DllImport("gdi32.dll", ExactSpelling = true)]
        internal static extern int SetDIBitsToDevice(IntPtr hdc, int xdst, int ydst,
                                                int width, int height, int xsrc, int ysrc, int start, int lines,
                                                IntPtr bitsptr, IntPtr bmiptr, int color);
        BITMAPINFOHEADER bmi;
        Rectangle bmprect;
        protected IntPtr GetPixelInfo(IntPtr bmpptr)
        {
          
            Marshal.PtrToStructure(bmpptr, bmi);

            bmprect.X = bmprect.Y = 0;
            bmprect.Width = bmi.biWidth;
            bmprect.Height = bmi.biHeight;

            if (bmi.biSizeImage == 0)
                bmi.biSizeImage = ((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight;

            int p = bmi.biClrUsed;
            if ((p == 0) && (bmi.biBitCount <= 8))
                p = 1 << bmi.biBitCount;
            p = (p * 4) + bmi.biSize + (int)bmpptr;
            return (IntPtr)p;
        }
        [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern IntPtr GlobalLock(IntPtr handle);

        [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern IntPtr GlobalFree(IntPtr handle);
        private void EndingScan()
        {
            if (msgfilter)
            {
                Application.RemoveMessageFilter(this);
                msgfilter = false;
                this.Enabled = true;
                this.Activate();
            }
        }

        private bool msgfilter;
        private Twain tw;
        private int picnumber = 0;

       // [STAThread]
      //  static void Main()
     //   {
       //     if (Twain.ScreenBitDepth < 15)
        //    {
         //       MessageBox.Show("Need high/true-color video mode!", "Screen Bit Depth", MessageBoxButtons.OK, MessageBoxIcon.Information);
       //         return;
           // }

         //   MainFrame mf = new MainFrame();
     //   //    Application.Run(mf);
     //   }

        private void menuMainWindow_Click(object sender, EventArgs e)
        {
            //Form1 mf = new Form1();
            //Application.Run(mf);
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            Form1 f = new Form1();
            f.Show();
        }

        private void MainFrame_Load(object sender, EventArgs e)
        {

        }
        Image immm;

        public Image Immm
        {
            get { return immm; }
            set { immm = value; }
        }
        private void menuItem2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            // openFileDialog.InitialDirectory = "c://";//注意这里写路径时要用c://而不是c:/
            openFileDialog.Filter = "圖片文件|*.*";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
             //   FileInfo fi = new FileInfo(openFileDialog.FileName);
             //   string a = fi.DirectoryName + "\\" + fi.Name.Replace(".", "_Thumb.");

             string   op = openFileDialog.FileName;
             //  ImageThumbnailMake.MakeThumbnail(op, a, 100, 200, "HW");
           Immm=Image.FromFile(op);
               // new FrmSQR("").pictureBox1.Image=
            }
        }

    } // class MainFrame

} // namespace TwainGui