示例#1
0
        private bool FilterMessage(NativeStructs.tagMSG msg)
        {
            if (twEvent.pEvent == IntPtr.Zero)
            {
                twEvent.pEvent = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeStructs.tagMSG)));
            }

            Marshal.StructureToPtr(msg, twEvent.pEvent, false);

            ResultCode rc = twainEvent(ref appId, ref deviceId, DataGroup.Control, DataArgumentType.Event, TwainMessages.ProcessEvent, ref twEvent);

            if (rc != ResultCode.DSEvent && rc != ResultCode.NotDSEvent)
            {
                return(false);
            }

            switch (twEvent.TWMessage)
            {
            case TwainMessages.XferReady:
                this.state     = TwainState.TransferReady;
                this.latestDIB = DoOneTransfer();
                break;

            case TwainMessages.CloseDSReq:
                this.latestDIB = IntPtr.Zero;
                DisableSource();
                this.breakModalLoop = true;
                break;

            default:
                break;
            }

            return(rc == ResultCode.DSEvent);
        }
示例#2
0
        private IntPtr DoNativeTransfer()
        {
            IntPtr hDib = IntPtr.Zero;

            if (state == TwainState.TransferReady)
            {
                ResultCode rc = twainNativeTransfer(ref appId, ref deviceId, DataGroup.Image, DataArgumentType.ImageNativeXfer, TwainMessages.Get, ref hDib);

                switch (rc)
                {
                case ResultCode.Cancel:
                case ResultCode.TransferDone:
                    this.state = TwainState.Transfering;
                    break;

                case ResultCode.Failure:
                default:
                    this.state = TwainState.TransferReady;
                    hDib       = IntPtr.Zero;
                    break;
                }
            }

            return(hDib);
        }
示例#3
0
        private void EndTransfer()
        {
            TwainStructs.PendingXfers pending = new TwainStructs.PendingXfers();
            ResultCode rc = ResultCode.Failure;

            if (state == TwainState.Transfering)
            {
                rc = twainPendingXfers(ref appId, ref deviceId, DataGroup.Control, DataArgumentType.PendingXfers, TwainMessages.EndXfer, ref pending);

                if (rc == ResultCode.Success)
                {
                    if (pending.Count != 0)
                    {
                        this.state = TwainState.TransferReady;
                    }
                    else
                    {
                        this.state = TwainState.SourceEnabled;
                    }
                }
            }

            if (state == TwainState.TransferReady)
            {
                twainPendingXfers(ref appId, ref deviceId, DataGroup.Control, DataArgumentType.PendingXfers, TwainMessages.Reset, ref pending);
            }
        }
示例#4
0
        protected virtual void Dispose(bool disposing)
        {
            Marshal.FreeHGlobal(_eventMessage.EventPtr);

            if (disposing)
            {
                DataSource.Dispose();

                IntPtr windowHandle = _messageHook.WindowHandle;

                if (ApplicationId.Id != 0)
                {
                    // Close down the data source manager
                    var result = Twain32Native.DsmParent(
                        ApplicationId,
                        IntPtr.Zero,
                        DataGroup.Control,
                        DataArgumentType.Parent,
                        Message.CloseDSM,
                        ref windowHandle);

                    _log.Debug(string.Format("CloseDSM, result: {0}", result));

                    if (result != TwainResult.Failure)
                    {
                        _twainState = TwainState.SourceManagerLoaded;
                    }
                }

                ApplicationId.Id = 0;
            }
        }
示例#5
0
        public TwainProxy(ITwainApplication app)
        {
            this.disposed = false;
            this.state    = TwainState.PreSession;

            this.availableSources   = new List <TwainStructs.Identity>();
            this.defaultSourceIndex = -1;
            this.latestDIB          = IntPtr.Zero;

            this.appId             = new TwainStructs.Identity();
            appId.Id               = 0U;
            appId.Version.MajorNum = 1;
            appId.Version.MinorNum = 0;
            appId.Version.Country  = TwainConstants.TWCY_USA;
            appId.Version.Language = TwainConstants.TWLG_ENGLISH_USA;
            appId.Version.Info     = string.Format("TwainProxy v{0}", typeof(TwainProxy).Assembly.GetName().Version.ToString(4));
            appId.Manufacturer     = "null54";
            appId.ProductFamily    = "TwainablePlus";
            appId.ProductName      = "TwainProxy";
            appId.ProtocolMajor    = TwainConstants.ProtocolMajor;
            appId.ProtocolMinor    = TwainConstants.ProtocolMinor;
            appId.SupportedGroups  = (uint)(DataGroup.Control | DataGroup.Image);

            this.deviceId           = new TwainStructs.Identity();
            this.parentWindowHandle = app.WindowHandle;
            this.hostApp            = app;
        }
示例#6
0
 private void CloseDataSource()
 {
     DataSource.DisableAndClose();
     if (DataSource.SourceState == null)
     {
         _twainState = TwainState.SourceManagerOpen;
     }
 }
示例#7
0
 private void DisableSource()
 {
     if (state == TwainState.SourceEnabled)
     {
         ResultCode rc = twainUI(ref appId, ref deviceId, DataGroup.Control, DataArgumentType.USERINTERFACE, TwainMessages.DisableDS, ref ui);
         if (rc == ResultCode.Success)
         {
             this.state = TwainState.SourceOpen;
         }
     }
 }
示例#8
0
        private void CloseSource()
        {
            DisableSource();

            if (state == TwainState.SourceOpen)
            {
                if (DSMIdentity(DataGroup.Control, TwainMessages.CloseDS, ref deviceId) == ResultCode.Success)
                {
                    state = TwainState.SourceManagerOpen;
                }
            }
        }
示例#9
0
        private void CloseSourceManager()
        {
            CloseSource();
            if (state == TwainState.SourceManagerOpen)
            {
                ResultCode rc = twainParent(ref appId, IntPtr.Zero, DataGroup.Control, DataArgumentType.Parent, TwainMessages.CloseDSM, ref parentWindowHandle);

                if (rc == ResultCode.Success)
                {
                    this.state = TwainState.SourceManagerLoaded;
                }
            }
        }
示例#10
0
        /// <summary>
        /// Steps down to the target session state.
        /// </summary>
        /// <param name="targetState"></param>
        /// <returns></returns>
        public ReturnCode StepDown(TwainState targetState)
        {
            if (targetState == this.State)
            {
                return(ReturnCode.Success);
            }

            var rc = ReturnCode.Failure;

            while (State > targetState)
            {
                switch (State)
                {
                case TwainState.DsmLoaded:
                case TwainState.DsmUnloaded:
                case TwainState.Invalid:
                    // can do nothing in these states
                    return(ReturnCode.Success);

                case TwainState.DsmOpened:
                    rc = Close();
                    if (rc != ReturnCode.Success)
                    {
                        return(rc);
                    }
                    break;

                case TwainState.SourceOpened:
                    rc = DGControl.Identity.CloseDS(CurrentSource.Identity32);
                    if (rc != ReturnCode.Success)
                    {
                        return(rc);
                    }
                    break;

                case TwainState.SourceEnabled:
                    rc = DGControl.UserInterface.DisableDS(ref _lastEnableUI, false);
                    if (rc != ReturnCode.Success)
                    {
                        return(rc);
                    }
                    break;

                case TwainState.TransferReady:
                case TwainState.Transferring:
                    _disableDSNow = true;
                    break;
                }
            }
            return(rc);
        }
示例#11
0
        private bool OpenSource()
        {
            if (state == TwainState.SourceManagerOpen)
            {
                ResultCode rc = DSMIdentity(DataGroup.Control, TwainMessages.OpenDS, ref deviceId);

                if (rc == ResultCode.Success)
                {
                    this.state = TwainState.SourceOpen;
                }
            }

            return(this.state >= TwainState.SourceOpen);
        }
示例#12
0
        private bool OpenSourceManager()
        {
            if (state < TwainState.SourceManagerOpen)
            {
                if (LoadSourceManager())
                {
                    ResultCode rc = twainParent(ref appId, IntPtr.Zero, DataGroup.Control, DataArgumentType.Parent, TwainMessages.OpenDSM, ref parentWindowHandle);

                    if (rc == ResultCode.Success)
                    {
                        this.state = TwainState.SourceManagerOpen;
                    }
                }
            }

            return(this.state >= TwainState.SourceManagerOpen);
        }
示例#13
0
        private bool EnableSource()
        {
            if (state == TwainState.SourceOpen)
            {
                ui.ShowUI  = 1;
                ui.hParent = parentWindowHandle;


                ResultCode rc = twainUI(ref appId, ref deviceId, DataGroup.Control, DataArgumentType.USERINTERFACE, TwainMessages.EnableDS, ref ui);

                if (rc == ResultCode.Success)
                {
                    this.state = TwainState.SourceEnabled;
                }
            }

            return(this.state >= TwainState.SourceEnabled);
        }
示例#14
0
        public DataSourceManager(Identity applicationId, IWindowsMessageHook messageHook)
        {

            // Make a copy of the identity in case it gets modified
            ApplicationId = applicationId.Clone();

            ScanningComplete += delegate { };
            TransferImage += delegate { };

            _messageHook = messageHook;
            _messageHook.FilterMessageCallback = FilterMessage;
            IntPtr windowHandle = _messageHook.WindowHandle;

            _eventMessage.EventPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WindowsMessage)));

            // Initialise the data source manager
            TwainResult result = Twain32Native.DsmParent(
                ApplicationId,
                IntPtr.Zero,
                DataGroup.Control,
                DataArgumentType.Parent,
                Message.OpenDSM,
                ref windowHandle);

			_log.Debug(string.Format("OpenDSM, result: {0}", result));
            if (result == TwainResult.Success)
            {
                //according to the 2.0 spec (2-10) if (applicationId.SupportedGroups
                // | DataGroup.Dsm2) > 0 then we should call DM_Entry(id, 0, DG_Control, DAT_Entrypoint, MSG_Get, wh)
                //right here
				
	            _twainState = TwainState.SourceManagerOpen;
                DataSource = GetDefault(ApplicationId);
            }
            else
            {
                throw new TwainException("Error initialising DSM: " + result, result);
            }
        }
示例#15
0
        public DataSourceManager(Identity applicationId, IWindowsMessageHook messageHook)
        {
            // Make a copy of the identity in case it gets modified
            ApplicationId = applicationId.Clone();

            ScanningComplete += delegate { };
            TransferImage    += delegate { };

            _messageHook = messageHook;
            _messageHook.FilterMessageCallback = FilterMessage;
            IntPtr windowHandle = _messageHook.WindowHandle;

            _eventMessage.EventPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WindowsMessage)));

            // Initialise the data source manager
            TwainResult result = Twain32Native.DsmParent(
                ApplicationId,
                IntPtr.Zero,
                DataGroup.Control,
                DataArgumentType.Parent,
                Message.OpenDSM,
                ref windowHandle);

            _log.Debug(string.Format("OpenDSM, result: {0}", result));
            if (result == TwainResult.Success)
            {
                //according to the 2.0 spec (2-10) if (applicationId.SupportedGroups
                // | DataGroup.Dsm2) > 0 then we should call DM_Entry(id, 0, DG_Control, DAT_Entrypoint, MSG_Get, wh)
                //right here

                _twainState = TwainState.SourceManagerOpen;
                DataSource  = GetDefault(ApplicationId);
            }
            else
            {
                throw new TwainException("Error initialising DSM: " + result, result);
            }
        }
示例#16
0
        private bool LoadSourceManager()
        {
            if (state >= TwainState.SourceManagerLoaded)
            {
                return(true);
            }

            if (!string.IsNullOrEmpty(WindowsDirectory))
            {
                string path = Path.Combine(WindowsDirectory, TwainDllName);

                if (File.Exists(path))
                {
                    this.hModule = UnsafeNativeMethods.LoadLibraryW(path);
                    if (!hModule.IsInvalid)
                    {
                        IntPtr entry = UnsafeNativeMethods.GetProcAddress(hModule, TwainEntryPoint);
                        if (entry != IntPtr.Zero)
                        {
                            twainEvent          = (TwainDelegates.TwainEvent)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwainEvent));
                            twainIdentity       = (TwainDelegates.TwainIdentity)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwainIdentity));
                            twainParent         = (TwainDelegates.TwianParent)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwianParent));
                            twainUI             = (TwainDelegates.TwainUI)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwainUI));
                            twainCapability     = (TwainDelegates.TwainCapability)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwainCapability));
                            twainNativeTransfer = (TwainDelegates.TwianNativeTransfer)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwianNativeTransfer));
                            twainPendingXfers   = (TwainDelegates.TwianPendingXfer)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwianPendingXfer));
                            twainStatus         = (TwainDelegates.TwainStatus)Marshal.GetDelegateForFunctionPointer(entry, typeof(TwainDelegates.TwainStatus));

                            this.state = TwainState.SourceManagerLoaded;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
示例#17
0
        protected void TransferPictures()
        {
            if (DataSource.SourceId.Id == 0)
            {
                return;
            }

            var         pendingTransfer = new PendingXfers();
            TwainResult result;

            try
            {
                do
                {
                    pendingTransfer.Count = 0;
                    var hbitmap = IntPtr.Zero;

                    // Get the image info
                    var imageInfo = new ImageInfo();
                    result = Twain32Native.DsImageInfo(
                        ApplicationId,
                        DataSource.SourceId,
                        DataGroup.Image,
                        DataArgumentType.ImageInfo,
                        Message.Get,
                        imageInfo);

                    _log.Debug(string.Format("Get(ImageInfo), result: {0}", result));
                    if (result != TwainResult.Success)
                    {
                        CloseDataSource();
                        break;
                    }

                    // Transfer the image from the device
                    result = Twain32Native.DsImageTransfer(
                        ApplicationId,
                        DataSource.SourceId,
                        DataGroup.Image,
                        DataArgumentType.ImageNativeXfer,
                        Message.Get,
                        ref hbitmap);

                    _log.Debug(string.Format("Get(ImageNativeXfer), result: {0}", result));

                    if (result != TwainResult.XferDone)
                    {
                        _log.ErrorFormat("Transfer the image from the device failed. Result: {0}", result);
                        CloseDataSource();
                        break;
                    }

                    DataSource.SourceState = TwainState.Transfering;

                    // End pending transfers
                    result = Twain32Native.DsPendingTransfer(
                        ApplicationId,
                        DataSource.SourceId,
                        DataGroup.Control,
                        DataArgumentType.PendingXfers,
                        Message.EndXfer,
                        pendingTransfer);

                    _log.Debug(string.Format("EndXfer(PendingXfers), result: {0}", result));
                    if (result != TwainResult.Success)
                    {
                        CloseDataSource();
                        break;
                    }

                    DataSource.SourceState = TwainState.TransferReady;

                    if (hbitmap == IntPtr.Zero)
                    {
                        _log.Warn("Transfer complete but bitmap pointer is still null.");
                    }
                    else
                    {
                        using (var renderer = new BitmapRenderer(hbitmap))
                        {
                            TransferImageEventArgs args = new TransferImageEventArgs(renderer.RenderToBitmap(),
                                                                                     pendingTransfer.Count != 0);
                            TransferImage(this, args);
                            if (!args.ContinueScanning)
                            {
                                break;
                            }
                        }
                    }
                } while (pendingTransfer.Count != 0);
            }
            catch (Exception e)
            {
            }
            finally
            {
                // Reset any pending transfers
                result = Twain32Native.DsPendingTransfer(
                    ApplicationId,
                    DataSource.SourceId,
                    DataGroup.Control,
                    DataArgumentType.PendingXfers,
                    Message.Reset,
                    pendingTransfer);


                if (result == TwainResult.Success)
                {
                    _twainState = TwainState.SourceEnabled;
                    _log.Debug(string.Format("Reset(PendingXfers), result: {0}", result));
                }
                else
                {
                    var conditionCode = GetConditionCode(ApplicationId, DataSource.SourceId);
                    _log.ErrorFormat("Reset(PendingXfers), result: {0}, condition code: {1}", result, conditionCode);
                }
            }
        }
示例#18
0
	    private void CloseDataSource()
	    {
			DataSource.DisableAndClose();
			if (DataSource.SourceState == null)
				_twainState = TwainState.SourceManagerOpen;
	    }
示例#19
0
        protected void TransferPictures()
        {
            if (DataSource.SourceId.Id == 0)
            {
                return;
            }

            var pendingTransfer = new PendingXfers();
            TwainResult result;
	        try
	        {
		        do
		        {
			        pendingTransfer.Count = 0;
			        var hbitmap = IntPtr.Zero;

			        // Get the image info
			        var imageInfo = new ImageInfo();
			        result = Twain32Native.DsImageInfo(
				        ApplicationId,
				        DataSource.SourceId,
				        DataGroup.Image,
				        DataArgumentType.ImageInfo,
				        Message.Get,
				        imageInfo);

					_log.Debug(string.Format("Get(ImageInfo), result: {0}", result));
			        if (result != TwainResult.Success)
			        {
				        CloseDataSource();
				        break;
			        }

			        // Transfer the image from the device
			        result = Twain32Native.DsImageTransfer(
				        ApplicationId,
				        DataSource.SourceId,
				        DataGroup.Image,
				        DataArgumentType.ImageNativeXfer,
				        Message.Get,
				        ref hbitmap);

					_log.Debug(string.Format("Get(ImageNativeXfer), result: {0}", result));

			        if (result != TwainResult.XferDone)
			        {
						_log.ErrorFormat("Transfer the image from the device failed. Result: {0}", result);
				        CloseDataSource();
				        break;
			        }

			        DataSource.SourceState = TwainState.Transfering;

			        // End pending transfers
			        result = Twain32Native.DsPendingTransfer(
				        ApplicationId,
				        DataSource.SourceId,
				        DataGroup.Control,
				        DataArgumentType.PendingXfers,
				        Message.EndXfer,
				        pendingTransfer);

					_log.Debug(string.Format("EndXfer(PendingXfers), result: {0}", result));
			        if (result != TwainResult.Success)
			        {
				        CloseDataSource();
				        break;
			        }

			        DataSource.SourceState = TwainState.TransferReady;

			        if (hbitmap == IntPtr.Zero)
			        {
				        _log.Warn("Transfer complete but bitmap pointer is still null.");
			        }
			        else
			        {
				        using (var renderer = new BitmapRenderer(hbitmap))
				        {
					        TransferImageEventArgs args = new TransferImageEventArgs(renderer.RenderToBitmap(),
						        pendingTransfer.Count != 0);
					        TransferImage(this, args);
					        if (!args.ContinueScanning)
						        break;
				        }
			        }
		        } while (pendingTransfer.Count != 0);
	        }
	        catch (Exception e)
	        {
		        
	        }
            finally
            {
                // Reset any pending transfers
                result = Twain32Native.DsPendingTransfer(
                    ApplicationId,
                    DataSource.SourceId,
                    DataGroup.Control,
                    DataArgumentType.PendingXfers,
                    Message.Reset,
                    pendingTransfer);

				
	            if (result == TwainResult.Success)
	            {
		            _twainState = TwainState.SourceEnabled;
					_log.Debug(string.Format("Reset(PendingXfers), result: {0}", result));
	            }
	            else
	            {
					var conditionCode = GetConditionCode(ApplicationId, DataSource.SourceId);
					_log.ErrorFormat("Reset(PendingXfers), result: {0}, condition code: {1}", result, conditionCode);		
	            }
            }
        }
示例#20
0
        protected virtual void Dispose(bool disposing)
        {
            Marshal.FreeHGlobal(_eventMessage.EventPtr);

            if (disposing)
            {
                DataSource.Dispose();

                IntPtr windowHandle = _messageHook.WindowHandle;

                if (ApplicationId.Id != 0)
                {
                    // Close down the data source manager
                    var result = Twain32Native.DsmParent(
                        ApplicationId,
                        IntPtr.Zero,
                        DataGroup.Control,
                        DataArgumentType.Parent,
                        Message.CloseDSM,
                        ref windowHandle);

					_log.Debug(string.Format("CloseDSM, result: {0}", result));

	                if (result != TwainResult.Failure)
	                {
		                _twainState = TwainState.SourceManagerLoaded;
	                }
                }

                ApplicationId.Id = 0;
            }
        }