Public Class frmHotKey_Add
    Dim Form_loaded As Boolean = False
    Private Control_Sequence As Integer
    Private Sub ObjektTypenEintragen()
        Try
            Dim oDokumentTyp As WINDREAMLib.WMObject
            ' Combobox leeren
            Me.cmbObjekttyp.Items.Clear()
            ' alle Objekttypen durchlaufen
            For Each oDokumentTyp In ClassWindream.GetObjecttypesAsObjects
                ' und in die Combobox eintragen
                Me.cmbObjekttyp.Items.Add(oDokumentTyp.aName)
            Next
        Catch ex As Exception
            MsgBox("Fehlernachricht:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Unexpected error inm Eintragen der Objekttypen")
        End Try

    End Sub
    Private Sub btnpnlStart_weiter_Click(sender As Object, e As EventArgs) Handles btnpnlStart_weiter.Click
        If ListBox_FormTitles.SelectedIndex <> -1 Then
            GroupBox2_Controls.Visible = True
            List_Controls(ListBox_FormTitles.SelectedItem, 1)
        Else
            GroupBox2_Controls.Visible = False
        End If
    End Sub

    Private Sub frmHotKey_Add_Load(sender As Object, e As EventArgs) Handles Me.Load

        Me.TBDD_USERTableAdapter.Connection.ConnectionString = MyConnectionString
        Me.TBHOTKEY_PATTERNSTableAdapter.Connection.ConnectionString = MyConnectionString
        Me.TBHOTKEY_PROFILETableAdapter.Connection.ConnectionString = MyConnectionString
        Me.TBHOTKEY_USER_PROFILETableAdapter.Connection.ConnectionString = MyConnectionString
        Me.TBHOTKEY_PATTERNS_REWORKTableAdapter.Connection.ConnectionString = MyConnectionString
        Me.TBHOTKEY_WINDOW_HOOKTableAdapter.Connection.ConnectionString = MyConnectionString
        TabControlDetails.SelectedIndex = 0
        TabControl1.SelectedIndex = 0
        Load_Profiles()
        load_users()
        GroupBox1.Visible = True
        GroupBox2_Controls.Visible = False
        GroupBoxMainWindow.Visible = False
        If ClassWindream.Init() = True Then
            ObjektTypenEintragen()
        Else
            MsgBox("Windream konnte nicht initiiert werden! Formular wird geschlossen - Check logfile", MsgBoxStyle.Information)
            Me.Close()
        End If

    End Sub
    Sub load_users()
        Try
            Me.TBDD_USERTableAdapter.Fill(Me.MyDataset.TBDD_USER)
            chklbUser.Items.Clear()
            For Each row As DataRow In MyDataset.TBDD_USER.Rows
                chklbUser.Items.Add(row.Item("USERNAME"))
            Next
        Catch ex As Exception
            MsgBox("Fehlernachricht:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Unexpected error in Load_Users:")
        End Try
    End Sub
    Sub Load_Profiles()
        Try
            Me.TBHOTKEY_PROFILETableAdapter.Fill(MyDataset.TBHOTKEY_PROFILE)
        Catch ex As Exception
            MsgBox("Fehlernachricht:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Unexpected error in Load_Profiles:")
        End Try
    End Sub
    Sub List_FormTitles(Tabindex As Integer)

        Try
            Select Case Tabindex
                Case 1
                    ListBox_FormTitles.Items.Clear()
                Case 2
                    ListBox_MainWindows_Test.Items.Clear()
                    ListViewControls_Test.Items.Clear()
            End Select
            Dim enumerator As New ClassWindowAPI
            For Each top As ClassWindowAPI.ApiWindow In enumerator.GetTopLevelWindows()
                If top.MainWindowTitle <> "" And top.MainWindowTitle <> "Global Indexer" And top.MainWindowTitle <> "Hot Key - Administration" Then
                    Select Case Tabindex
                        Case 1
                            ListBox_FormTitles.Items.Add(top.MainWindowTitle)
                        Case 2
                            ListBox_MainWindows_Test.Items.Add(top.MainWindowTitle)
                    End Select
                End If
            Next top

        Catch ex As Exception
            MsgBox("Error in List_FormTitles: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Function CheckFormTitle_isOpen(windowname As String)
        Dim isopen As Boolean = False
        Try
            Dim enumerator As New ClassWindowAPI
            For Each top As ClassWindowAPI.ApiWindow In enumerator.GetTopLevelWindows()
                If top.MainWindowTitle <> "" And top.MainWindowTitle <> "Global Indexer" And top.MainWindowTitle <> "Hot Key - Administration" Then
                    If top.MainWindowTitle = windowname Then
                        Return True
                    End If
                End If
            Next top
            Return False
        Catch ex As Exception
            MsgBox("Error in CheckFormTitle_isOpen: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function

    Sub List_Controls(Title As String, Tabindex As Integer)
        ' Try
        Select Case Tabindex
            Case 1
                If GroupBox2_Controls.Visible = False Then
                    GroupBox2_Controls.Visible = True
                End If
                ListViewControls.Items.Clear()
                txtControl.Text = ""
            Case 2
                ListViewControls_Test.Items.Clear()
        End Select

        Dim enumerator As New ClassWindowAPI
        'Jedes Fenster durchlaufen
        For Each top As ClassWindowAPI.ApiWindow In enumerator.GetTopLevelWindows()
            If top.MainWindowTitle.Contains(Title) Or top.MainWindowTitle.ToLower = Title.ToLower Then
                Dim anz As Integer = 0
                Control_Sequence = 0
                'Jedes Control durchlaufen
                For Each child As ClassWindowAPI.ApiWindow In enumerator.GetChildWindows(top.hWnd)
                    Select Case Tabindex
                        Case 1
                            If chkboxshowfilledControlsOnly.Checked Then
                                If child.MainWindowTitle <> "" Then
                                    ListViewControls.Items.Add(Control_Sequence)
                                    ListViewControls.Items(anz).SubItems.Add(child.hWnd.ToString)
                                    ListViewControls.Items(anz).SubItems.Add(child.MainWindowTitle)
                                    anz += 1
                                End If
                            Else
                                ListViewControls.Items.Add(Control_Sequence)
                                ListViewControls.Items(anz).SubItems.Add(child.hWnd.ToString)
                                ListViewControls.Items(anz).SubItems.Add(child.MainWindowTitle)
                                anz += 1
                            End If
                        Case 2
                            If chkboxshowfilledControlsOnly_Test.Checked Then
                                If child.MainWindowTitle <> "" Then
                                    ListViewControls_Test.Items.Add(Control_Sequence)
                                    ListViewControls_Test.Items(anz).SubItems.Add(child.hWnd.ToString)
                                    ListViewControls_Test.Items(anz).SubItems.Add(child.MainWindowTitle)
                                    anz += 1
                                End If
                            Else
                                ListViewControls_Test.Items.Add(Control_Sequence)
                                ListViewControls_Test.Items(anz).SubItems.Add(child.hWnd.ToString)
                                ListViewControls_Test.Items(anz).SubItems.Add(child.MainWindowTitle)
                                anz += 1
                            End If
                            'ListBox_Controls_Test.Items.Add("ID: " & child.hWnd.ToString & " || Aktueller Wert: " & child.MainWindowTitle)
                    End Select
                    Control_Sequence += 1
                Next child
            End If
        Next top
        'Catch ex As Exception
        '    MsgBox("Error in List_Controls: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        'End Try
    End Sub

    Private Sub ListBox_FormTitles_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox_FormTitles.SelectedIndexChanged
        If ListBox_FormTitles.SelectedIndex <> -1 And GroupBox2_Controls.Visible = True Then
            List_Controls(ListBox_FormTitles.SelectedItem, 1)
        End If
    End Sub

    Private Sub txtKey_KeyDown(sender As Object, e As KeyEventArgs) Handles txtKey.KeyDown
        txtKey.Text = ""
    End Sub

    Private Sub btnGB1_Click(sender As Object, e As EventArgs) Handles btnGB1.Click
        If txtProfilname.Text <> "" And txtWDSearch.Text <> "" And txtKey.Text <> "" And cmbFunktionstaste.Text <> "" Then
            Me.GroupBoxMainWindow.Visible = True
            List_FormTitles(1)
        Else
            MsgBox("Eingabe fehlt!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub TBHOTKEY_PROFILEBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TBHOTKEY_PROFILEBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.MyDataset)

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnadd_Pattern.Click
        Try
            lblLinkadd.Visible = False
            If txtPattern.Text = "" Then
                Exit Sub
            End If
            Dim sql As String = "select max(guid) from tbhotkey_Profile where upper(name) =  Upper('" & txtProfilname.Text & "')"
            Dim kopf = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            If IsDBNull(kopf) Then
                TBHOTKEY_PROFILETableAdapter.Insert(txtProfilname.Text, "NONE", txtWDSearch.Text, cmbFunktionstaste.Text, txtKey.Text.ToUpper, ListBox_FormTitles.SelectedItem, Environment.UserName)
            Else
                TBHOTKEY_PROFILETableAdapter.cmdUpdate(txtProfilname.Text, "NONE", txtWDSearch.Text, cmbFunktionstaste.Text, txtKey.Text.ToUpper, ListBox_FormTitles.SelectedItem, Environment.UserName, kopf)
            End If
            lblSaveHotkey.Visible = True
            sql = "select max(guid) from tbhotkey_Profile where upper(name) =  Upper('" & txtProfilname.Text & "')"
            Dim id = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            If id > 0 Then
                TBHOTKEY_PATTERNSTableAdapter.Insert(id, txtPattern.Text, Control_ID, Environment.UserName, txtControl.Text)
                lblLinkadd.Text = "Pattern-Link " & txtControl.Text & " || " & txtPattern.Text & " erfolgreich angelegt"
                lblLinkadd.Visible = True
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in Add Pattern or Profile:")
        End Try

    End Sub

    Private Sub txtPattern_TextChanged(sender As Object, e As EventArgs) Handles txtPattern.TextChanged

    End Sub


    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        If Not Me.txtWDSearch.Text = "" Then
            Me.OFDWindreamsuche.FileName = Me.txtWDSearch.Text
        End If

        If Me.OFDWindreamsuche.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.txtWDSearch.Text = Me.OFDWindreamsuche.FileName
        End If
    End Sub
    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControlMain.SelectedIndexChanged
        Select Case TabControlMain.SelectedIndex

            Case 0
                TabControl1.SelectedIndex = 0
                TabControlDetails.SelectedIndex = 0
                Load_Profiles()
            Case 1
                If NAMETextBox.Text <> "" And CheckFormTitle_isOpen(WINDOW_NAMETextBox.Text) = True Then
                    btnnewProfile.Visible = True
                    txtProfilname.Text = NAMETextBox.Text
                    txtWDSearch.Text = WD_SEARCHTextBox.Text
                    cmbFunktionstaste.SelectedIndex = cmbFunktionstaste.FindStringExact(HOTKEY1ComboBox.Text)
                    txtKey.Text = HOTKEY2TextBox.Text
                    Me.GroupBoxMainWindow.Visible = True
                    List_FormTitles(1)
                    ListBox_FormTitles.SelectedIndex = ListBox_FormTitles.FindStringExact(WINDOW_NAMETextBox.Text)
                    ListBox_FormTitles.SetSelected(ListBox_FormTitles.SelectedIndex, True)
                    GroupBox2_Controls.Visible = True
                    If Not IsNothing(ListBox_FormTitles.SelectedItem) Then
                        List_Controls(ListBox_FormTitles.SelectedItem, 1)
                    End If
                Else
                    btnnewProfile.Visible = False
                    Me.GroupBoxMainWindow.Visible = False
                    GroupBox2_Controls.Visible = False
                    txtProfilname.Text = ""
                    txtWDSearch.Text = ""
                    cmbFunktionstaste.SelectedIndex = -1
                    txtKey.Text = ""
                End If
            Case 2
                List_FormTitles(2)
        End Select
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        List_FormTitles(2)
    End Sub

    Private Sub ListBox_MainWindows_Test_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox_MainWindows_Test.SelectedIndexChanged
        If ListBox_MainWindows_Test.SelectedIndex <> -1 Then
            List_Controls(ListBox_MainWindows_Test.SelectedItem, 2)
        End If
    End Sub

    Private Sub btndelete_Click(sender As Object, e As EventArgs) Handles btndelete.Click
        Dim ID
        Try
            ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
        Catch ex As Exception
            ID = 0
        End Try
        If ID > 1 Then
            Dim result As MsgBoxResult
            result = MessageBox.Show("Sind Sie sicher dass Sie dieses Hotkeyprofil löschen wollen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Try

                    Dim del As String = "DELETE FROM TBHOTKEY_USER_PROFILE WHERE HKPROFILE_ID = " & ID
                    If ClassDatabase.Execute_non_Query(del, True) = True Then
                        del = "DELETE FROM TBHOTKEY_PATTERNS_REWORK WHERE HKPATTERN_ID IN (SELECT GUID FROM TBHOTKEY_PATTERNS WHERE HKPROFILE_ID = " & ID & ")"
                        If ClassDatabase.Execute_non_Query(del, True) = True Then
                            del = "DELETE FROM TBHOTKEY_PATTERNS WHERE HKPROFILE_ID = " & ID
                            If ClassDatabase.Execute_non_Query(del, True) = True Then
                                del = "DELETE FROM TBHOTKEY_WINDOW_HOOK WHERE HKPROFILE_ID = " & ID
                                If ClassDatabase.Execute_non_Query(del, True) = True Then
                                    del = "DELETE FROM TBHOTKEY_PROFILE WHERE GUID = " & ID
                                    If ClassDatabase.Execute_non_Query(del, True) = True Then
                                        ClassLogger.Add(">> Hotkey-Profil: " & ID & " wurde gelöscht!", False)
                                        Load_Profiles()
                                        Load_UserForProfiles()
                                        MsgBox("Profil wurde erfolgreich gelöscht!", MsgBoxStyle.Information, "Erfolgsmeldung")
                                    End If
                                End If
                            End If
                        End If
                    End If
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in Delete Profiles: ")
                End Try
            End If
        End If
    End Sub

    Private Sub btnUserAdd_Profile_Click(sender As Object, e As EventArgs) Handles btnUserAdd_Profile.Click
        Try
            Dim added As Integer = 0
            Dim items As CheckedListBox.CheckedItemCollection = chklbUser.CheckedItems
            Dim ID
            Try
                ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
            Catch ex As Exception
                ID = 0
            End Try
            If ID > 1 And items.Count > 0 Then
                For Each item In items
                    Dim SQL
                    SQL = "SELECT GUID FROM TBDD_USER WHERE USERNAME = '" & item.ToString & "'"
                    Dim userid = ClassDatabase.Execute_Scalar(SQL, MyConnectionString, True)

                    SQL = "SELECT COUNT(*) FROM TBHOTKEY_USER_PROFILE WHERE USER_ID = " & userid & " and HKPROFILE_ID = " & ID
                    Dim exists = ClassDatabase.Execute_Scalar(SQL, MyConnectionString, True)
                    If exists = 0 Then
                        TBHOTKEY_USER_PROFILETableAdapter.cmdInsert(userid, ID)
                        added += 1
                    End If

                Next

            Else
                MsgBox("Keine Benutzer und/oder kein Profil ausgewählt")
                Exit Sub
            End If

            If added >= 1 Then
                MsgBox(added & " neue Profil/User-Verknüpfungen angelegt!", MsgBoxStyle.Information)
                Load_UserForProfiles()
            Else
                MsgBox("Keine Verknüpfungen angelegt!", MsgBoxStyle.Information)
            End If

        Catch ex As Exception
            MsgBox("Error in Add MyHotkey: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub AlleAuswählenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AlleAuswählenToolStripMenuItem.Click
        If TabControl1.SelectedIndex = 1 Then
            For i = 0 To chklbUser.Items.Count - 1
                chklbUser.SetItemChecked(i, True)
            Next
        ElseIf TabControl1.SelectedIndex = 2 Then
            For i = 0 To chklbUserProfile.Items.Count - 1
                chklbUserProfile.SetItemChecked(i, True)
            Next
        End If
       
    End Sub

    Private Sub KeineAuswählenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KeineAuswählenToolStripMenuItem.Click
        If TabControl1.SelectedIndex = 1 Then
            For i = 0 To chklbUser.Items.Count - 1
                chklbUser.SetItemChecked(i, False)
            Next
        ElseIf TabControl1.SelectedIndex = 2 Then
            For i = 0 To chklbUserProfile.Items.Count - 1
                chklbUserProfile.SetItemChecked(i, False)
            Next
        End If
       
    End Sub

    Private Sub TabControl2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        GroupBoxPatterns.Visible = False
        Select Case TabControl1.SelectedIndex
            Case 0
                GroupBoxPatterns.Visible = True
            Case 2
                Load_UserForProfiles()
        End Select
    End Sub
    Sub Load_UserForProfiles()
        Try
            Dim ID
            Try
                ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
            Catch ex As Exception
                ID = 0
            End Try
            If ID > 1 Then
                chklbUserProfile.Items.Clear()
                Dim SQL = "SELECT T.USERNAME FROM TBHOTKEY_USER_PROFILE T1, TBDD_USER T WHERE T.GUID = T1.USER_ID and T1.HKPROFILE_ID = " & ID
                Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL, True)
                If Not IsNothing(DT) Then
                    For Each dr As DataRow In DT.Rows
                        chklbUserProfile.Items.Add(dr.Item(0))
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in LoadUserForProfiles: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ListBox_Profiles_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim ID
        Try
            ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
        Catch ex As Exception
            ID = 0
        End Try
        If ID > 0 Then
            Select Case TabControl1.SelectedIndex
                Case 1
                    'Try
                    '    TBHOTKEY_PROFILETableAdapter.FillByID(MyDataset.TBHOTKEY_PROFILE, ListBox_Profiles.SelectedValue)
                    'Catch ex As Exception
                    '    MsgBox("Error in Fillby Profile-ID: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                    'End Try
                    Load_Patterns()
                    Load_MatchPatterns()
                Case 2
                    Load_UserForProfiles()
            End Select
            lblSave.Visible = False
        End If


    End Sub
    Sub Load_Patterns()
        Try
            TBHOTKEY_PATTERNSTableAdapter.Fill(MyDataset.TBHOTKEY_PATTERNS, GUIDTextBox.Text)
            tslbl_Hotkeywindow.Text = WINDOW_NAMETextBox.Text
            tslbl_HotkeySequence.Text = SEQUENCE_NUMBERTextBox.Text
        Catch ex As Exception
            MsgBox("Error in Fill Patterns: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_MatchPatterns()
        Try
            TBHOTKEY_WINDOW_HOOKTableAdapter.Fill(MyDataset.TBHOTKEY_WINDOW_HOOK, GUIDTextBox.Text)
        Catch ex As Exception
            MsgBox("Error in Fill Match-Patterns: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub btndeleteUserProfile_Click(sender As Object, e As EventArgs) Handles btndeleteUserProfile.Click
        Try
            Dim deleted As Integer = 0
            Dim items As CheckedListBox.CheckedItemCollection = chklbUserProfile.CheckedItems
            Dim ID
            Try
                ID = GridView1.GetFocusedRowCellValue(GridView1.Columns("GUID"))
            Catch ex As Exception
                ID = 0
            End Try
            If ID > 1 And items.Count > 0 Then
                For Each item In items
                    Dim SQL
                    SQL = "SELECT GUID FROM TBDD_USER WHERE USERNAME = '" & item.ToString & "'"
                    Dim userid = ClassDatabase.Execute_Scalar(SQL, MyConnectionString, True)
                    If IsNothing(userid) Then
                        MsgBox("Unerwarteter Unexpected error inm Holen der User-ID!", MsgBoxStyle.Exclamation)
                        Exit Sub
                    End If
                    SQL = "SELECT GUID FROM TBHOTKEY_USER_PROFILE WHERE USER_ID = " & userid & " and HKPROFILE_ID = " & ID
                    Dim ID1 = ClassDatabase.Execute_Scalar(SQL, MyConnectionString, True)
                    If ID1 > 0 Then
                        TBHOTKEY_USER_PROFILETableAdapter.Delete(ID1)
                        deleted += 1
                    End If
                Next

            Else
                MsgBox("Keine Benutzer und/oder kein Profil ausgewählt")
                Exit Sub
            End If

            If deleted >= 1 Then
                MsgBox(deleted & " Profilbeziehungen wurden gelöscht!", MsgBoxStyle.Information)
                Load_UserForProfiles()
            End If
        Catch ex As Exception
            MsgBox("Error in Delete Profile for Users: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
        Try
            TBHOTKEY_PROFILEBindingSource.EndEdit()
            If Me.MyDataset.TBHOTKEY_PROFILE.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = Environment.UserName
                TBHOTKEY_PROFILEBindingSource.EndEdit()
                TBHOTKEY_PROFILETableAdapter.Update(MyDataset.TBHOTKEY_PROFILE)
                Me.lblSave.Visible = True
                Dim result As MsgBoxResult
                If USER_LANGUAGE = "de-DE" Then
                    result = MessageBox.Show("Wollen Sie die Änderungen im Hotkey-Profil auch in den Userprofilen vornehmen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Else
                    result = MessageBox.Show("Dow You want to update the userprofiles also with the changes in the profile?", "Confirmation required:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                End If
                If result = MsgBoxResult.Yes Then
                    Try
                        Dim update = "UPDATE TBHOTKEY_USER_PROFILE SET WD_SEARCH = '" & WD_SEARCHTextBox.Text & "', HOTKEY1 = '" & HOTKEY1ComboBox.Text & "', HOTKEY2 = '" & HOTKEY2TextBox.Text & "' WHERE HKPROFILE_ID = " & GUIDTextBox.Text
                        If ClassDatabase.Execute_non_Query(update, True) Then
                            If USER_LANGUAGE = "de-DE" Then
                                MsgBox("User-Profile erfolgreich aktualisiert!", MsgBoxStyle.Information)
                            Else
                                MsgBox("Userprofiles successfull updated!", MsgBoxStyle.Information)
                            End If
                        End If
                    Catch ex As Exception
                        MsgBox("Error in Refresh Userprofiles: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                    End Try
                End If
            Else
                Me.lblSave.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save My Profile: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If Not Me.WD_SEARCHTextBox.Text = "" Then
            Me.OFDWindreamsuche.FileName = Me.WD_SEARCHTextBox.Text
        End If

        If Me.OFDWindreamsuche.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.WD_SEARCHTextBox.Text = Me.OFDWindreamsuche.FileName
        End If
    End Sub

    Private Sub Fill_Rework(PATT_ID As Integer)
        Try
            Me.TBHOTKEY_PATTERNS_REWORKTableAdapter.Fill(Me.MyDataset.TBHOTKEY_PATTERNS_REWORK, PATT_ID)
        Catch ex As System.Exception
            MsgBox("Error in Load Rework-Step:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub


    Private Sub ListBoxPatterns_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBoxPatterns.SelectedIndexChanged
        If ListBoxPatterns.SelectedIndex <> -1 Then
            Fill_Rework(ListBoxPatterns.SelectedValue)
            tslbl_Hotkeywindow.Text = WINDOW_NAMETextBox.Text
            tslbl_HotkeySequence.Text = SEQUENCE_NUMBERTextBox.Text
        End If
    End Sub


    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Try
            TBHOTKEY_PATTERNS_REWORKBindingSource.EndEdit()
            If Me.MyDataset.TBHOTKEY_PATTERNS_REWORK.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox1.Text = Environment.UserName
                TBHOTKEY_PATTERNS_REWORKBindingSource.EndEdit()
                TBHOTKEY_PATTERNS_REWORKTableAdapter.Update(MyDataset.TBHOTKEY_PATTERNS_REWORK)
                Me.lblsavePatternsRework.Visible = True
            Else
                Me.lblsavePatternsRework.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save Reowrk Patterns: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub TBHOTKEY_PATTERNSBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBHOTKEY_PATTERNSBindingSource.AddingNew
        MyDataset.TBHOTKEY_PATTERNS_REWORK.ADDED_WHOColumn.DefaultValue = Environment.UserName
    End Sub
    Private Sub TYPEComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TYPEComboBox.SelectedIndexChanged
        If TYPEComboBox.SelectedIndex <> -1 Then
            Me.TEXT1TextBox.Visible = True
            Me.Text1Label.Visible = True
            Me.TEXT2TextBox.Visible = True
            Me.Text2Label.Visible = True
            Me.btnRegexTest.Visible = False

            TEXT1TextBox.Size = New Size(50, 22)
            lblHinweisRework1.Visible = False

            Me.FUNCTION1TextBox.Visible = False
            Me.FUNCTION2TextBox.Visible = False
            Me.Function1Label.Visible = False
            Me.Function2Label.Visible = False
            FUNCTION1TextBox.Size = New Size(111, 22)

            Select Case TYPEComboBox.Text
                Case "VBREPLACE"
                    Me.Text1Label.Text = "Old Value:"
                    Me.Text2Label.Text = "New Value:"

                Case "VBSPLIT"
                    Me.Text1Label.Text = "Split-Zeichen:"
                    lblHinweisRework1.Text = "(Zahl) - Achtung Nullbasierend: Erstes Vorkommen = '0'"
                    lblHinweisRework1.Visible = True
                    Me.Text2Label.Text = "Vorkommen:"
                Case "Regular Expression"
                    Me.Text1Label.Text = "Regular Expression:"
                    TEXT1TextBox.Size = New Size(400, 22)
                    Me.Text2Label.Visible = False
                    Me.TEXT2TextBox.Visible = False

                    Me.Function1Label.Text = "Test-String Regex:"
                    Me.FUNCTION1TextBox.Text = ""
                    FUNCTION1TextBox.Size = New Size(138, 22)
                    Me.FUNCTION1TextBox.Visible = True
                    Me.Function1Label.Visible = True
                    Me.btnRegexTest.Visible = True
            End Select
        End If
    End Sub
    Private Sub TBHOTKEY_PATTERNS_REWORKBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBHOTKEY_PATTERNS_REWORKBindingSource.AddingNew
        If ListBoxPatterns.SelectedIndex <> -1 Then
            MyDataset.TBHOTKEY_PATTERNS_REWORK.ADDED_WHOColumn.DefaultValue = Environment.UserName
            MyDataset.TBHOTKEY_PATTERNS_REWORK.HKPATTERN_IDColumn.DefaultValue = ListBoxPatterns.SelectedValue
        End If

    End Sub

    Private Sub GUIDTextBox_TextChanged(sender As Object, e As EventArgs) Handles GUIDTextBox.TextChanged
        If GUIDTextBox.Text <> "" Then
            Load_Patterns()
            Load_MatchPatterns()
        End If
    End Sub

    Private Sub GUIDTextBox2_TextChanged(sender As Object, e As EventArgs) Handles GUIDTextBox2.TextChanged
        If GUIDTextBox2.Text <> "" Then
            Fill_Rework(GUIDTextBox2.Text)
        End If
    End Sub

    Private Sub btnRegexTest_Click(sender As Object, e As EventArgs) Handles btnRegexTest.Click
        If Me.TEXT1TextBox.Text <> "" And FUNCTION1TextBox.Text <> "" Then
            Dim RegexList As New List(Of System.Text.RegularExpressions.Regex)
            Dim Regex As New System.Text.RegularExpressions.Regex(Me.TEXT1TextBox.Text, System.Text.RegularExpressions.RegexOptions.IgnoreCase)

            RegexList.Add(Regex)

            ' Email Absender und Empfänger
            Dim result = ClassPostprocessing.extractFromStringviaRE(FUNCTION1TextBox.Text, RegexList)
            If Not IsNothing(result) Then
                MsgBox("Das Ergebnis der Regular-Expression: '" & result.ToString & "'!", MsgBoxStyle.Information)
            Else
                MsgBox("Es konnte kein Ergebnis ermittelt werden!", MsgBoxStyle.Exclamation)
            End If

        End If


    End Sub
    Dim Control_ID As String
    Private Sub ListViewControls_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListViewControls.SelectedIndexChanged
        If Me.ListViewControls.SelectedItems.Count > 0 Then
            Control_ID = Me.ListViewControls.SelectedItems(0).SubItems(1).Text
            txtControl.Text = ListViewControls.SelectedItems(0).Text
            txtControl_Match.Text = ListViewControls.SelectedItems(0).Text
            txtValueMatch.Text = Me.ListViewControls.SelectedItems(0).SubItems(2).Text
            txtPattern.Text = ""
            If lblLinkadd.Visible Then
                ListBox_FormTitles.Enabled = False
            End If
        End If
    End Sub

    Private Sub chkboxshowfilledControlsOnly_Test_CheckedChanged(sender As Object, e As EventArgs) Handles chkboxshowfilledControlsOnly_Test.CheckedChanged
        If ListBox_MainWindows_Test.SelectedIndex <> -1 Then
            List_Controls(ListBox_MainWindows_Test.SelectedItem, 2)
        End If
    End Sub

    Private Sub chkboxshowfilledControlsOnly_CheckedChanged(sender As Object, e As EventArgs) Handles chkboxshowfilledControlsOnly.CheckedChanged
        If ListBox_FormTitles.SelectedIndex <> -1 Then
            List_Controls(ListBox_FormTitles.SelectedItem, 1)
        End If
    End Sub

    Private Sub btnadd_WindowMatch_Click(sender As Object, e As EventArgs) Handles btnadd_WindowMatch.Click
        Try
            Dim sql As String = "select max(guid) from tbhotkey_Profile where upper(name) =  Upper('" & txtProfilname.Text & "')"
            Dim kopf = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            If IsDBNull(kopf) Then
                TBHOTKEY_PROFILETableAdapter.Insert(txtProfilname.Text, "NONE", txtWDSearch.Text, cmbFunktionstaste.Text, txtKey.Text.ToUpper, ListBox_FormTitles.SelectedItem, Environment.UserName)
            Else
                TBHOTKEY_PROFILETableAdapter.cmdUpdate(txtProfilname.Text, "NONE", txtWDSearch.Text, cmbFunktionstaste.Text, txtKey.Text.ToUpper, ListBox_FormTitles.SelectedItem, Environment.UserName, kopf)
            End If
            lblSaveHotkey.Visible = True
            sql = "select max(guid) from tbhotkey_Profile where upper(name) =  Upper('" & txtProfilname.Text & "')"
            Dim id = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            If id > 0 Then
                TBHOTKEY_WINDOW_HOOKTableAdapter.Insert(id, txtControl_Match.Text, txtValueMatch.Text, Environment.UserName)
                lblMatchadd.Text = "Control-Matching " & txtControl_Match.Text & " || " & txtValueMatch.Text & " erfolgreich angelegt"
                lblMatchadd.Visible = True
                lblLinkadd.Visible = False
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in Add Control-Match:")
        End Try
    End Sub

    Private Sub tsbtnsave_pattern_Click(sender As Object, e As EventArgs) Handles tsbtnsave_pattern.Click
        Try
            TBHOTKEY_PATTERNSBindingSource.EndEdit()
            If Me.MyDataset.TBHOTKEY_PATTERNS.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox2.Text = Environment.UserName
                TBHOTKEY_PATTERNSBindingSource.EndEdit()
                TBHOTKEY_PATTERNSTableAdapter.Update(MyDataset.TBHOTKEY_PATTERNS)
                Me.lblSavePAttern.Visible = True
            Else
                Me.lblSavePAttern.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Save Patterns: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Sind Sie sicher dass Sie diesen Control-Match löschen wollen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Try
                TBHOTKEY_WINDOW_HOOKTableAdapter.Delete(GUIDTextBox3.Text)
                Load_MatchPatterns()
            Catch ex As Exception
                MsgBox("Error in Delete Control-Match: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnnewProfile.Click
        txtProfilname.Text = ""
        txtWDSearch.Text = ""
        cmbFunktionstaste.SelectedIndex = -1
        txtKey.Text = ""
        GroupBoxMainWindow.Visible = False
        GroupBox2_Controls.Visible = False
        ListBox_FormTitles.Enabled = True
        btnAddCopypasteConfig.Enabled = True
    End Sub

    Private Sub TEXT1TextBox_TextChanged(sender As Object, e As EventArgs) Handles TEXT1TextBox.TextChanged
        If TEXT1TextBox.Text = " " Then
            TEXT1TextBox.SelectAll()
            TEXT1TextBox.BackColor = Color.DarkOrange
            TEXT1TextBox.ForeColor = Color.White
        Else
            TEXT1TextBox.BackColor = Color.White
            TEXT1TextBox.ForeColor = Color.Black
        End If
    End Sub

    Private Sub frmHotKey_Add_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Form_loaded = True
        If GUIDTextBox.Text <> String.Empty Then
            GroupBoxPatterns.Visible = True
        End If

    End Sub

    Private Sub chklbUser_MouseEnter(sender As Object, e As EventArgs) Handles chklbUser.MouseEnter
        ToolTipController1.ShowHint("Rechtsklick für weitere Funktionen", "Hinweis:", DevExpress.Utils.ToolTipLocation.RightCenter)
    End Sub
    Private Sub chklbUser_MouseLeave(sender As Object, e As EventArgs) Handles chklbUser.MouseLeave
        ToolTipController1.HideHint()
    End Sub

    Private Sub btnAddCopypasteConfig_Click(sender As Object, e As EventArgs) Handles btnAddCopypasteConfig.Click
        Try
            lblLinkCopyPaste.Visible = False
            If txtcopypastePatter.Text = "" Then
                Exit Sub
            End If
            Dim sql As String = "select max(guid) from tbhotkey_Profile where upper(name) =  Upper('" & txtProfilname.Text & "')"
            Dim kopfid = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            If IsDBNull(kopfid) Then
                TBHOTKEY_PROFILETableAdapter.Insert(txtProfilname.Text, "COPYPASTE", txtWDSearch.Text, cmbFunktionstaste.Text, txtKey.Text.ToUpper, ListBox_FormTitles.SelectedItem, Environment.UserName)
            Else
                TBHOTKEY_PROFILETableAdapter.cmdUpdate(txtProfilname.Text, "COPYPASTE", txtWDSearch.Text, cmbFunktionstaste.Text, txtKey.Text.ToUpper, ListBox_FormTitles.SelectedItem, Environment.UserName, kopfid)
            End If
            lblSaveHotkey.Visible = True
            sql = "select max(guid) from tbhotkey_Profile where upper(name) =  Upper('" & txtProfilname.Text & "')"
            Dim id = ClassDatabase.Execute_Scalar(sql, MyConnectionString, True)
            If id > 0 Then
                TBHOTKEY_PATTERNSTableAdapter.Insert(id, txtcopypastePatter.Text, cmbCopyPasteFunction.Text, Environment.UserName, txtControl.Text)
                lblLinkCopyPaste.Text = "Pattern-Link " & cmbCopyPasteFunction.Text & " || " & txtcopypastePatter.Text & " erfolgreich angelegt"
                lblLinkCopyPaste.Visible = True
                btnAddCopypasteConfig.Enabled = False
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error in CopyPaste Add Pattern or Profile:")
        End Try
    End Sub

    Private Sub cmbCopyPasteFunction_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbCopyPasteFunction.SelectedIndexChanged

    End Sub

    Private Sub chklbUserProfile_MouseEnter(sender As Object, e As EventArgs) Handles chklbUserProfile.MouseEnter
        ToolTipController1.ShowHint("Rechtsklick für weitere Funktionen", "Hinweis:", DevExpress.Utils.ToolTipLocation.RightCenter)
    End Sub

    Private Sub chklbUserProfile_MouseLeave(sender As Object, e As EventArgs) Handles chklbUserProfile.MouseLeave
        ToolTipController1.HideHint()
    End Sub
End Class