Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Imports System.Threading
'Imports Dynamsoft.Barcode
Imports Dynamsoft.TWAIN
Imports Dynamsoft.Core
'Imports Dynamsoft.UVC
'Imports Dynamsoft.OCR
Imports Dynamsoft.PDF
Imports Dynamsoft.Core.Annotation
'Imports Dynamsoft.UVC.Common
Imports Dynamsoft.TWAIN.Interface
Imports Dynamsoft.Core.Enums
Imports System.IO


'Aktuell3
Public Class frmScan
    Inherits Form
    Implements IAcquireCallback
    Implements IConvertCallback
    Implements ISave
    Private m_StrProductKey As String
    Private m_TwainManager As TwainManager = Nothing
    Private m_ImageCore As ImageCore = Nothing
    Private m_PDFRasterizer As PDFRasterizer = Nothing
    Private m_PDFCreator As PDFCreator = Nothing
    Private Delegate Sub CrossThreadOperationControl()

    ' Public KdNr As Integer = -1

    Public ART As String = ""
    Public ORDNER As String = ""
    Public ReturnValue As Object = Nothing
    Public fileName As String = ""

    Public DefaultFileName = ""
    'Dim DS As New cDATENSERVER

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        m_TwainManager.Dispose()
        m_ImageCore.Dispose()
        m_TwainManager = Nothing
        m_ImageCore = Nothing
    End Sub

    Sub New(ART)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        Me.ART = ART
        init()
    End Sub



    Public Sub OnPostAllTransfers() Implements IAcquireCallback.OnPostAllTransfers
        Me.Invoke(New CrossThreadOperationControl(AddressOf CallMe))
    End Sub

    Public Sub CallMe()
        dsViewer.Visible = True
        checkImageCount()
        '  EnableControls(picboxScan)
    End Sub

    Public Sub OnPreAllTransfers() Implements IAcquireCallback.OnPreAllTransfers
    End Sub

    Public Sub LoadConvertResult(result As ConvertResult) Implements IConvertCallback.LoadConvertResult
        m_ImageCore.IO.LoadImage(result.Image)
        m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, result.Annotations, True)
    End Sub

    Public Function GetAnnotations(iPageNumber As Integer) As Object Implements ISave.GetAnnotations
        If chkMultiPage.Checked = True Then
            Return m_ImageCore.ImageBuffer.GetMetaData(CShort(iPageNumber), EnumMetaDataType.enumAnnotation)
        Else
            Return m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation)
        End If
    End Function
    Public Function GetImage(iPageNumber As Integer) As Bitmap Implements ISave.GetImage
        If chkMultiPage.Checked = True Then
            Return m_ImageCore.ImageBuffer.GetBitmap(CShort(iPageNumber))
        Else
            Return m_ImageCore.ImageBuffer.GetBitmap(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
        End If
    End Function
    Public Function GetPageCount() As Integer Implements ISave.GetPageCount
        If chkMultiPage.Checked = True Then
            Return m_ImageCore.ImageBuffer.HowManyImagesInBuffer
        Else
            Return 1
        End If
    End Function
    'Public Function OnPreTransfer() As Boolean Implements IAcquireCallback.OnPreTransfer
    '    Return True
    'End Function


    'Public Function OnPostTransfer(bit As Bitmap) As Boolean Implements IAcquireCallback.OnPostTransfer
    '    m_ImageCore.IO.LoadImage(bit) 'ungültiger Param????
    '    Return True
    'End Function


    Public Sub New()
        InitializeComponent()
        init()
    End Sub

    Sub init()

        Dim LICENSE_KEY_PDF = "f0068NQAAAHHd/ZqHWlJjPt2W7f40pPn+818Q5PlZzXLGKw3w6Oi3zwzXWB45AOyom6xmOaVeS7nictDJNVEekShtfZmM2JE=" ' "f0068WQAAAH+gY718ZLeqQLD8lbOZ2FGn4EwqZXwHfnnHFla7+8MQS5/qOwvtYLWLNCl4FRxs5YG2tso5CsxMGiwxi1RLj1Q="
        Dim LICENSE_KEY = "f0068NQAAAMzfp6Gvu6Fz+I1fe35VMbxq4AjxirlBtKiw2m/c7+WFUo6cqKV9gdsrUF08tMFDzxyvK2qW7dkB/AMXwWP8+VE=" ' "f0068NQAAALO56JsMvaoZUvgW4W5pH3xZI04YVLRm6RjxrXBNGlXQX66fwwyD9MA7RooXB8R7IGVCGOs0LoQrz74BFUWxuTY="        '"t0068MgAAAIJug/9puT32C74ZTQ22FzetJ8QgWhH3CpvWhJ98JT07diK2qayDBNOEoyk+wYbapUbYlgyAVhm8wuu4zvTLfkw="
        '  Dim LICENSE_KEY_PDF = "t0068MgAAAIJug/9puT32C74ZTQ22FzetJ8QgWhH3CpvWhJ98JT07diK2qayDBNOEoyk+wYbapUbYlgyAVhm8wuu4zvTLfkw="
        '  Dim LICENSE_KEY = "t0068MgAAAIJug/9puT32C74ZTQ22FzetJ8QgWhH3CpvWhJ98JT07diK2qayDBNOEoyk+wYbapUbYlgyAVhm8wuu4zvTLfkw=" '""

        'm_StrProductKey = ConbineLicense(ReadLocalLicense(Application.StartupPath & "\Lizenzen\DynamsoftDotNetTwain.lic")) ' In Projekt SDL / Lizenzen / DynamsoftDotNetTwain.lic
        m_TwainManager = New TwainManager(LICENSE_KEY)
        m_PDFRasterizer = New PDFRasterizer(LICENSE_KEY)
        m_PDFCreator = New PDFCreator(LICENSE_KEY_PDF)
        m_ImageCore = New ImageCore()
        dsViewer.Bind(m_ImageCore)
    End Sub

    <DllImport("kernel32.dll")> _
    Private Shared Function GetSystemDirectory(<Out> lpBuffer As StringBuilder, uSize As UInteger) As UInteger
    End Function

    <DllImport("kernel32.dll")> _
    Private Shared Function GetWindowsDirectory(<Out> lpBuffer As StringBuilder, uSize As UInteger) As UInteger
    End Function

    Public Function GetLicenseFilePath() As String
        Return Application.StartupPath & "\Lizenzen\DynamsoftDotNetTwain.lic"

        Dim sbsSystemDir As New StringBuilder(256)
        Dim iLength As UInteger = 0
        iLength = GetSystemDirectory(sbsSystemDir, 256)
        If iLength = 0 Then
            Return Nothing
        End If
        Dim sbsWindowsDir As New StringBuilder(256)
        iLength = GetWindowsDirectory(sbsWindowsDir, 256)

        If iLength = 0 Then
            Return Nothing
        End If
        If sbsWindowsDir.Length > 0 Then
            If IntPtr.Size = 8 Then
                sbsWindowsDir.Append("\SysWOW64\DynamsoftDotNetTwain.lic")
            Else
                sbsWindowsDir.Append("\System32\DynamsoftDotNetTwain.lic")

            End If
        End If
        Return sbsWindowsDir.ToString()
    End Function

    Private Function ReadLocalLicense(licensePath As String) As List(Of String)
        Dim tempListLicense As List(Of String) = Nothing
        Try
            If File.Exists(licensePath) Then
                Dim tempAllLines As String() = File.ReadAllLines(licensePath)
                For Each temp As String In tempAllLines
                    Dim iTempIndex As Integer = temp.IndexOf("SerialNo")
                    If iTempIndex <> -1 Then
                        Dim iIndex1 As Integer = temp.IndexOf("=")
                        If iIndex1 <> -1 Then
                            If tempListLicense Is Nothing Then
                                tempListLicense = New List(Of String)()
                            End If
                            Dim tempLicense As String = temp.Substring((iIndex1 + 1), (temp.Length - (iIndex1 + 1)))
                            tempListLicense.Add(tempLicense)
                        End If
                    End If
                Next
            End If
        Catch
        End Try
        Return tempListLicense
    End Function

    Private Function ConbineLicense(listlicensePath As List(Of String)) As String
        Dim tempLicenseFilePath As String = GetLicenseFilePath()
        Dim tempListLicense As List(Of String) = ReadLocalLicense(tempLicenseFilePath)
        Dim tempProductKey As String = m_StrProductKey
        If tempListLicense IsNot Nothing Then
            For Each temp As String In tempListLicense
                If temp IsNot Nothing Then
                    If Not m_StrProductKey.Equals(temp) Then
                        tempProductKey = (tempProductKey & Convert.ToString(";")) + temp.ToString()
                    End If
                End If
            Next
        End If
        Return tempProductKey
    End Function

    'here, i need to set a callback function that will be called when the time elapse.
    Private Sub callbk()
        'code here will be executed when the time elapse
        'Threading.Thread.Abort(thread)
        thread.Abort()
    End Sub

    Dim thread As Threading.Thread

    Public ReadOnly Property IfGetImageInfo As Boolean Implements IAcquireCallback.IfGetImageInfo
        Get
            Return True '   Throw New NotImplementedException()
        End Get
    End Property
    'Public Sub OnPostAllTransfers()
    'End Sub

    Public ReadOnly Property IfGetExtImageInfo As Boolean Implements IAcquireCallback.IfGetExtImageInfo
        Get
            Return True '    Throw New NotImplementedException()
        End Get
    End Property

    Private Sub startScanTimeout()
        'setup a timeout here to call the sub callbk when the time elapse.
        'for example, something like this
        thread = New Threading.Thread(AddressOf startScan)
        Dim tcb As TimerCallback = AddressOf callbk
        Dim t As Threading.Timer = New Threading.Timer(tcb, Nothing, 5000, -1)
        'the first argument is the time interval in milliseconds while the second argument is the function to callback after the period of 5 seconds
        thread.Start()
        'While True
        '    startScan()
        'End While
    End Sub

    Private Sub picboxScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
        'startScanTimeout()
        startScan()
    End Sub

    Sub startScan()

        Me.Cursor = Cursors.WaitCursor
        pnl.Enabled = False
        If Me.cboSource.SelectedIndex < 0 Then
            MessageBox.Show(Me, "Es wurde kein Scanner gefunden!", "Information")
        Else
            Try
                Dim sSourceIndex As Short = 0
                sSourceIndex = CShort(cboSource.SelectedIndex)
                Dim sTwainSourceCount As Short = m_TwainManager.SourceCount
                Dim sCameraSourceCount As Short = 0

                'm_TwainManager.TransferMode = Dynamsoft.TWAIN.Enums.TWICapSetupXFer.TWSX_FILE


                If sSourceIndex < sTwainSourceCount Then
                    m_TwainManager.SelectSourceByIndex(sSourceIndex)


                    ''vor Opensource
                    'Dim tmpFile = Path.GetTempFileName & ".pdf"
                    'tmpFile = "D:\Andreas\Dokumente\temptest<>.pdf"
                    ''  m_TwainManager.SetFileXFERInfo(tmpFile, Dynamsoft.TWAIN.Enums.TWICapFileFormat.TWFF_PDFA2) ' Dynamsoft.DWT.EnumDWT_FileFormat)
                    'm_TwainManager.TransferMode = Dynamsoft.TWAIN.Enums.TWICapSetupXFer.TWSX_FILE



                    m_TwainManager.OpenSource()


                    '   m_TwainManager.IfShowUI = chkShowUI.Checked
                    '  m_TwainManager.IfFeederEnabled = chkADF.Checked
                    ' m_TwainManager.IfDuplexEnabled = chkDuplex.Checked
                    m_TwainManager.IfDisableSourceAfterAcquire = True

                    m_TwainManager.IfShowUI = chkShowUI.Checked

                    Select Case cbxEinzug.CheckState
                        Case CheckState.Indeterminate
                            If m_TwainManager.IfPaperDetectable AndAlso m_TwainManager.IfFeederLoaded Then
                                m_TwainManager.IfFeederEnabled = True
                            Else
                                m_TwainManager.IfFeederEnabled = False
                            End If
                            '  m_TwainManager.IfAutoFeed = True

                        Case CheckState.Checked : m_TwainManager.IfFeederEnabled = True
                        Case Not CheckState.Checked : m_TwainManager.IfFeederEnabled = False
                    End Select





                    If rdbtnBW.Checked Then
                        m_TwainManager.PixelType = Dynamsoft.TWAIN.Enums.TWICapPixelType.TWPT_BW
                        m_TwainManager.BitDepth = 1
                    ElseIf rdbtnGray.Checked Then
                        m_TwainManager.PixelType = Dynamsoft.TWAIN.Enums.TWICapPixelType.TWPT_GRAY
                        m_TwainManager.BitDepth = 8
                    Else
                        m_TwainManager.PixelType = Dynamsoft.TWAIN.Enums.TWICapPixelType.TWPT_RGB
                        m_TwainManager.BitDepth = 24
                    End If
                    m_TwainManager.Resolution = Integer.Parse(cboResolution.Text)

                    'm_TwainManager.sca()



                    'If m_TwainManager.TransferMode = Dynamsoft.TWAIN.Enums.TWICapSetupXFer.TWSX_FILE Then


                    '    MsgBox("1")

                    '    'If m_TwainManager.SetFileXFERInfo("C:\Temp\WebTWAINTEST<%06d>.bmp", Dynamsoft.TWAIN.Enums.TWICapFileFormat.TWFF_BMP) Then
                    '    If m_TwainManager.SetFileXFERInfo(tmpFile, Dynamsoft.TWAIN.Enums.TWICapFileFormat.TWFF_PDF) Then
                    '        MsgBox("2")
                    '        m_TwainManager.AcquireImage(TryCast(Me, IAcquireCallback))
                    '    End If

                    'End If

                    m_TwainManager.AcquireImage(TryCast(Me, IAcquireCallback))


                Else
                    Dim sCameraIndex As Short = CShort(sSourceIndex - sTwainSourceCount)


                End If
            Catch exp As Exception
                'EnableControls(picboxScan);
                MsgBox("Scanner nicht verfügbar!" & vbNewLine & exp.Message & exp.StackTrace)
            Finally
                m_TwainManager.Dispose()

                GC.Collect()
                pnl.Enabled = True
                Me.Cursor = Cursors.Default

            End Try
            dsViewer.Visible = True
            checkImageCount()

        End If
        pnl.Enabled = True
        Me.Cursor = Cursors.Default

    End Sub



    Private Sub btn_Click(sender As Object, e As EventArgs)

        Dim tempList As New List(Of String)()
        For i As Integer = 0 To m_TwainManager.SourceCount - 1
            tempList.Add(m_TwainManager.SourceNameItems(CShort(i)))
        Next
        Dim tempSourceListWrapper As New SourceListWrapper(tempList)

        Dim iSelectIndex As Integer = tempSourceListWrapper.SelectSource()
        If iSelectIndex = -1 Then
            Return
        Else
            m_TwainManager.IfDisableSourceAfterAcquire = True
            m_TwainManager.IfShowUI = True
            m_TwainManager.SelectSourceByIndex(CShort(iSelectIndex))
            m_TwainManager.AcquireImage(TryCast(Me, IAcquireCallback))
        End If
    End Sub

    Private Sub InitDefaultValueForTWAIN()

        Try

            dsViewer.IfFitWindow = True
            dsViewer.MouseShape = False
            dsViewer.SetViewMode(-1, -1)
            '   Me.cbxViewMode.SelectedIndex = 0

            ' Init the sources for TWAIN scanning and Webcam grab, show in the cbxSources controls
            If m_TwainManager.SourceCount > 0 Then
                Dim hasTwainSource As Boolean = False
                Dim hasWebcamSource As Boolean = False
                cboSource.Items.Clear()
                For i As Integer = 0 To m_TwainManager.SourceCount - 1
                    cboSource.Items.Add(m_TwainManager.SourceNameItems(CShort(i)))
                    'else if (enumDeviceType == Dynamsoft.DotNet.TWAIN.Enums.EnumDeviceType.SDT_WEBCAM)
                    '    hasWebcamSource = true;
                    hasTwainSource = True
                Next
                If hasTwainSource Then
                    cboSource.Enabled = True
                    ' chkShowUI.Enabled = True
                    ' chkADF.Enabled = True
                    ' chkDuplex.Enabled = True
                    ' cbxResolution.Enabled = True
                    ' rdbtnGray.Checked = True
                    ' cbxResolution.SelectedIndex = 0
                    ' EnableControls(Me.picboxScan)

                End If
            End If
            Dim iSourceCount As Integer = 0



        Catch ex As System.Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub



    Private Sub cboSource_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSource.SelectedIndexChanged, cboResolution.SelectedIndexChanged
        Dim sIndex As Short = CShort(DirectCast(sender, ComboBox).SelectedIndex)

        If sIndex < m_TwainManager.SourceCount Then
            btnScan.Enabled = True
            m_TwainManager.CloseSource()
        Else
            btnScan.Enabled = False
        End If
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn.Click
        '  If KdNr < 0 Then Exit Sub
        Try
            Select Case ART
                Case "DirectScan"
                    Dim PDF_bytes As Byte() = m_PDFCreator.SaveAsBytes(TryCast(Me, ISave))
                    Me.fileName = addExtension(tbxSaveFileName.Text) ' DS.LAST_ID
                    Me.ReturnValue = PDF_bytes ' DS.LAST_ID
                    Me.DialogResult = Windows.Forms.DialogResult.OK

                Case Else : saveToFile()
            End Select
        Catch ex As Exception
            MsgBox(ex.Message)
            pnl.Enabled = True
        End Try
    End Sub


    Function addExtension(ByRef FileName As String) As String
        Dim Extension As String = ""

        If rdbtnJPG.Checked Then
            Extension = ".jpg"
        End If
        If rdbtnBMP.Checked Then
            Extension = ".bmp"
        End If
        If rdbtnPNG.Checked Then
            Extension = ".png"
        End If
        If rdbtnTIFF.Checked Then
            Extension = ".tiff"
        End If
        If rdbtnPDF.Checked Then
            Extension = ".pdf"
        End If
        FileName = FileName.Trim
        If Not FileName.EndsWith(Extension) Then
            FileName = FileName & Extension
        End If
        Return FileName
    End Function


    Sub saveToFile()

        Try
            Dim SaveFileDialog As New SaveFileDialog
            ' Dim fileName As String = "" ' tbxSaveFileName.Text.Trim()
            '  Dim SaveFileDialog
            Dim fileName As String = tbxSaveFileName.Text.Trim()
            If VerifyFileName(fileName) Then
                SaveFileDialog.FileName = Me.tbxSaveFileName.Text

                If rdbtnJPG.Checked Then
                    SaveFileDialog.Filter = "JPEG|*.JPG;*.JPEG;*.JPE;*.JFIF"
                    SaveFileDialog.DefaultExt = "jpg"
                    If SaveFileDialog.ShowDialog() = DialogResult.OK Then
                        m_ImageCore.IO.SaveAsJPEG(SaveFileDialog.FileName, m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
                    End If
                End If
                If rdbtnBMP.Checked Then
                    SaveFileDialog.Filter = "BMP|*.BMP"
                    SaveFileDialog.DefaultExt = "bmp"
                    If SaveFileDialog.ShowDialog() = DialogResult.OK Then
                        m_ImageCore.IO.SaveAsBMP(SaveFileDialog.FileName, m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
                    End If
                End If
                If rdbtnPNG.Checked Then
                    SaveFileDialog.Filter = "PNG|*.PNG"
                    SaveFileDialog.DefaultExt = "png"
                    If SaveFileDialog.ShowDialog() = DialogResult.OK Then
                        m_ImageCore.IO.SaveAsPNG(SaveFileDialog.FileName, m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
                    End If
                End If
                If rdbtnTIFF.Checked Then
                    SaveFileDialog.Filter = "TIFF|*.TIF;*.TIFF"
                    SaveFileDialog.DefaultExt = "tiff"
                    If SaveFileDialog.ShowDialog() = DialogResult.OK Then
                        ' Multi page TIFF
                        Dim tempListIndex As New List(Of Short)()
                        If chkMultiPage.Checked = True Then

                            For sIndex As Short = 0 To m_ImageCore.ImageBuffer.HowManyImagesInBuffer - 1
                                tempListIndex.Add(sIndex)
                            Next
                        Else
                            tempListIndex.Add(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
                        End If
                        m_ImageCore.IO.SaveAsTIFF(SaveFileDialog.FileName, tempListIndex)
                    End If
                End If
                If rdbtnPDF.Checked Then
                    SaveFileDialog.Filter = "PDF|*.PDF"
                    SaveFileDialog.DefaultExt = "pdf"
                    If SaveFileDialog.ShowDialog() = DialogResult.OK Then
                        ' Multi page PDF

                        m_PDFCreator.Save(TryCast(Me, ISave), SaveFileDialog.FileName)
                    End If
                End If
            Else
                Me.tbxSaveFileName.Focus()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            m_ImageCore.Dispose() 'Speicherfreigabe
            m_PDFCreator = Nothing 'Speicherfreigabe??
        End Try
    End Sub



    Private Function VerifyFileName(fileName As String) As Boolean
        Try
            If fileName.LastIndexOfAny(System.IO.Path.GetInvalidFileNameChars()) = -1 Then
                Return True
            End If
        Catch e As Exception
        End Try
        MessageBox.Show("The file name contains invalid chars!", "Save Image To File", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Return False
    End Function




    Private Sub picboxRotateLeft_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim iImageWidth As Integer = m_ImageCore.ImageBuffer.GetBitmap(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer).Width
        Dim iImageHeight As Integer = m_ImageCore.ImageBuffer.GetBitmap(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer).Height
        Dim tempListAnnotation As List(Of AnnotationData) = DirectCast(m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation), List(Of AnnotationData))
        If tempListAnnotation IsNot Nothing AndAlso tempListAnnotation.Count <> 0 Then
            For Each tempAnnotation As AnnotationData In tempListAnnotation
                Dim x As Integer = tempAnnotation.Location.Y
                Dim y As Integer = iImageWidth - (tempAnnotation.EndPoint.X)
                Dim iWidth As Integer = (tempAnnotation.EndPoint.Y - tempAnnotation.StartPoint.Y)
                Dim iHeight As Integer = (tempAnnotation.EndPoint.X - tempAnnotation.StartPoint.X)
                Select Case tempAnnotation.AnnotationType
                    'case AnnotationType.enumLine:
                    Case AnnotationType.enumEllipse, AnnotationType.enumRectangle, AnnotationType.enumText
                        tempAnnotation.StartPoint = New Point(x, y)
                        'tempAnnotation.Size = new Size(iWidth, iHeight);
                        tempAnnotation.EndPoint = New Point((tempAnnotation.StartPoint.X + iWidth), (tempAnnotation.StartPoint.Y + iHeight))
                        Exit Select
                    Case AnnotationType.enumLine
                        Dim startPoint As Point = tempAnnotation.StartPoint
                        x = startPoint.Y
                        y = iImageWidth - startPoint.X
                        tempAnnotation.StartPoint = New Point(x, y)
                        Dim endPoint As Point = tempAnnotation.EndPoint
                        x = endPoint.Y
                        y = iImageWidth - endPoint.X
                        tempAnnotation.EndPoint = New Point(x, y)
                        Exit Select
                End Select
            Next
        End If
        m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempListAnnotation, True)
        m_ImageCore.ImageProcesser.RotateLeft(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
    End Sub

    Private Sub picboxRotateRight_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim iImageWidth As Integer = m_ImageCore.ImageBuffer.GetBitmap(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer).Width
        Dim iImageHeight As Integer = m_ImageCore.ImageBuffer.GetBitmap(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer).Height
        Dim tempListAnnotation As List(Of AnnotationData) = DirectCast(m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation), List(Of AnnotationData))
        For Each tempAnnotation As AnnotationData In tempListAnnotation
            Dim x As Integer = iImageHeight - (tempAnnotation.Location.Y + tempAnnotation.Size.Height)
            Dim y As Integer = tempAnnotation.Location.X
            Dim iWidth As Integer = tempAnnotation.Size.Height
            Dim iHeight As Integer = tempAnnotation.Size.Width
            Select Case tempAnnotation.AnnotationType
                'case AnnotationType.enumLine:
                Case AnnotationType.enumEllipse, AnnotationType.enumRectangle, AnnotationType.enumText
                    tempAnnotation.StartPoint = New Point(x, y)
                    tempAnnotation.EndPoint = New Point((tempAnnotation.StartPoint.X + iWidth), (tempAnnotation.StartPoint.Y + iHeight))
                    Exit Select
                Case AnnotationType.enumLine
                    Dim startPoint As Point = tempAnnotation.StartPoint
                    x = iImageHeight - startPoint.Y
                    y = startPoint.X
                    tempAnnotation.StartPoint = New Point(x, y)
                    Dim endPoint As Point = tempAnnotation.EndPoint
                    x = iImageHeight - endPoint.Y
                    y = endPoint.X
                    tempAnnotation.EndPoint = New Point(x, y)
                    Exit Select
            End Select
        Next
        m_ImageCore.ImageProcesser.RotateRight(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer)
    End Sub


    Private Sub frmScan_Load(sender As Object, e As EventArgs) Handles Me.Load
        InitDefaultValueForTWAIN()
        cboResolution.Text = 240

        Select Case ART
            Case "DirectScan"
                grpTyp.Visible = False
            Case "QuickScan"

        End Select


    End Sub



    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Dim zoom As Single = dsViewer.Zoom + 0.1F
        dsViewer.IfFitWindow = False
        dsViewer.Zoom = zoom
        'checkZoom()
    End Sub

    Private Sub picboxZoomOut_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim zoom As Single = dsViewer.Zoom - 0.1F
        dsViewer.IfFitWindow = False
        dsViewer.Zoom = zoom
        ' checkZoom()
    End Sub

    Private Sub picboxPrevious_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If m_ImageCore.ImageBuffer.HowManyImagesInBuffer > 0 AndAlso m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer > 0 Then
            m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer -= 1
        End If
        checkImageCount()
    End Sub

    Private Sub picboxNext_Click(sender As Object, e As EventArgs) Handles Button4.Click
        If m_ImageCore.ImageBuffer.HowManyImagesInBuffer > 0 AndAlso m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer < m_ImageCore.ImageBuffer.HowManyImagesInBuffer - 1 Then
            m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer += 1
        End If
        checkImageCount()
    End Sub

    Private Sub checkImageCount()
        Dim currentImageIndex = m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer
        Dim currentIndex As Integer = currentImageIndex + 1
        Dim imageCount As Integer = m_ImageCore.ImageBuffer.HowManyImagesInBuffer
        If imageCount = 0 Then
            currentIndex = 0
        End If

        tbxCurrentImageIndex.Text = currentIndex.ToString()
        tbxTotalImageNum.Text = imageCount.ToString()

        If imageCount > 0 Then
            Button1.Enabled = True
            Button4.Enabled = True
        Else

            Button1.Enabled = False
            Button4.Enabled = False
        End If

        '   ShowSelectedImageArea()
    End Sub

    Private Sub frmScan_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If cboSource.Items.Count > 0 Then
            btnScan.Enabled = True
            cboSource.SelectedIndex = 0
        End If
        tbxSaveFileName.Text = DefaultFileName

        Select Case ART
            Case "DirectScan"

            Case "QuickScan"
                Do
                    startScan()
                    Dim PDF_bytes As Byte() = m_PDFCreator.SaveAsBytes(TryCast(Me, ISave))
                    Me.fileName = addExtension(tbxSaveFileName.Text) ' DS.LAST_ID
                    Me.ReturnValue = PDF_bytes ' DS.LAST_ID
                Loop While MsgBox("Möchten Sie weitere Dokumente scannen?" & vbNewLine & "NEIN = fertig!", vbYesNo) = vbYes

                Me.DialogResult = Windows.Forms.DialogResult.OK
        End Select
    End Sub

    Private Sub frmScan_TabStopChanged(sender As Object, e As EventArgs) Handles Me.TabStopChanged

    End Sub

    'Public Sub OnPreAllTransfers() Implements IAcquireCallback.OnPreAllTransfers
    '    Throw New NotImplementedException()
    'End Sub



    'Public Sub OnPostAllTransfers() Implements IAcquireCallback.OnPostAllTransfers
    '    Throw New NotImplementedException()
    'End Sub

    Public Sub OnSourceUIClose() Implements IAcquireCallback.OnSourceUIClose
        '  Throw New NotImplementedException()
    End Sub

    Public Sub OnTransferCancelled() Implements IAcquireCallback.OnTransferCancelled
        'Throw New NotImplementedException()
    End Sub

    Public Sub OnTransferError() Implements IAcquireCallback.OnTransferError
        'Throw New NotImplementedException()
    End Sub

    Public Function OnPostTransfer(bit As Bitmap, info As String) As Boolean Implements IAcquireCallback.OnPostTransfer
        m_ImageCore.IO.LoadImage(bit) 'ungültiger Param????
        GC.Collect()
        Return True
        'Throw New NotImplementedException()
    End Function

    Public Function OnPreTransfer() As Boolean Implements IAcquireCallback.OnPreTransfer
        Return True
        'Throw New NotImplementedException()
    End Function
End Class


Public Class SourceListWrapper
    Private m_listSourceNames As List(Of String) = Nothing
    Public Sub New(listSourceNames As List(Of String))
        m_listSourceNames = listSourceNames
    End Sub

    Private m_SelectedIndex As Integer = 0
    Public Function SelectSource() As Integer
        Dim temp As New frmSourceList(m_listSourceNames)
        temp.ShowDialog()
        m_SelectedIndex = temp.GetSelectedIndex()
        Return m_SelectedIndex
    End Function

End Class
