'//////////////////////////////
'//    Date: 13/06/2016      //
'//  Programmed by LEKIM     //
'//////////////////////////////
'//////////////////////////////
'//    Date: 23/07/2018      //
'//   Continued by Jooli     //
'//     with my thanks       //
'//////////////////////////////
'Info:
'    Lekim (url)   https://foro.elhacker.net/buscador-t453843.0.html 

'Necessário : Microsoft Net.Framework 4.6.1 (x86 e x64 ) (minimo)  -App Roda em win(10):testado , win(7) ???

'COMO INSTALAR A  Aplicação :  clicar em setup.exe
'COMO MANUSEAR ESTE CÓDIGO :............. (Form totalmente em branco apena necessita das linhas de código)........
'1-Colocar o código no Form1 : no VS2017  Community por  ex  ( Abrir um form renomeando-o se necessário )
'    https://visualstudio.microsoft.com/pt-br/downloads/?rr=https%3A%2F%2Fwww.google.pt%2F
'2-Adicionar uma Pasta Ressources com todos os icons 
'       e ficheiros necessários... deverá  ser  necessário  ajustes  de linguagem
'       ou  criar  novos       https://icofx.ro/downloads.html
'       Download dos ficheiros : https://meocloud.pt/link/4376e935-42b6-47fe-b290-7d78902e3b6e/Ressources/ 
'3-Run & Enjoy

'Obs: Limitações de  momento :
'Temporização das notas por  teclado(s) ou pelo rato
'Inconcistencias  várias 
'1-Movimentos do rato accionam o mousemove indevidamente ..........RESOLVIDO ?
'2-Temporização das notas por input directo ........RESOLVIDO
'3-Reproduzir o imput directo ..........resolvido
'4-Temporização das notas tocadas por tecla ou pelo mouse ???????<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'5-Apagar as notas memorizadas ou seja as matrizes  de  suporte             Resolvido
'6-Introdução de figurinhas de arrasto até á pauta (resolvido +-) e das teclas ( labeis ) ....Resolvido<<<<<<<<<<<<
'7-Input directo de figurinhas (resolvido )
'8-A questão do progress_bar permanece um enigma não resolvido pela perca  do foco num segundo form <<<<<<<<<<<<<<<<<<<<
'................ Para evitar este problema, todos os threads de STA (single threaded apartment) devem utilizar 
'                 primitivas de espera de extração (tal como CoWaitForMultipleHandles) e gerar mensagens regularmente 
'                 durante operações de longa duração.'
'        Com a medição do desempenho  memória e cpu , logo no arranque , e  a introdução de um timer parece estar melhor
'        ....gera  as tais  mensagens  regularmente mas ....  ainda  não arranca  sem o mouse 
'9-Usar um lábel para anotações on run  .............. lblChords(12)  ................. Resolvido
'10-Dar um aspecto mais apelativo ao teclado e as pautas     <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'11-Apagar cada pauta individualmente <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'12-Redução do gasto de  memória   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'13-Rever ToolTips e idiomas  >>>>>>>>>>>>>>>>>   A  resolver
'14-Ao fim de inumeras tentativas lá consegui implementar um counter entre o mouse_down e o mouse_up em módulo próprio (Teclado Sup)
'15-A relação dos tempos das  notas e a designação atribuída aos  icons respectivos é feita com potencias de dois :
'           Dim TimeFactor As Integer = CInt(2 ^ (n - 1)) ' fórmula para obter um factor associado á nota musical (icon)
'           Dim NotaçãoIdeal As Integer = TimeFactor * Quartifusa
'           DesvioTemporal = CDec((Math.Abs(DuraçãoDaNota / NotaçãoIdeal)))
'           'Nota neste caso existe dois  valores para a precisão um inferior (1/Precisão) e o superior (Precisão)
'           Dim Precisão As Decimal = CDec(1.5)
'           Dim LimiteInFerior As Decimal = Math.Round(CDec(1 / Precisão), 2)
'               ......................................
'           CodificaçãoIcon = CInt(Quartifusa / FusaFactor) ' obtenção final da designaçao associada  á nota
'                onde quartifusa é a unidade mais pequena no tempo e também , numéricamente, a maior.
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> A Resolver   : Algo lento na progressão dos ticks ???????????????????
'Compassos : contas  ao longo do eixo dos XXX  ........>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>A RESOlVER

'
'Nota : No  final existe  uma  class NativeMethods que  contem algumas  subrotinas e modulos
'que  são  extremamente  importantes para  o  funcionameno  geral  da  app  (mouseevents etc)
'Coloquei   aqui   tambem  algumas  subs  á  experiencia e  outras que  são  apenas  esboços
'Têm  a  ver  com o  uso e aproveitamento   da  memória  como
'Class BaseClass : Implements IDisposable                                   >>>>>>>>>>>>>>  A  Rever
'******************************************************************************** 
'***********************************Programa própriamente  dito :

Option Strict On
Option Compare Binary
Option Infer On

Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Security
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.CompilerServices
Imports System.Drawing.Drawing2D
Imports System.IO

Public Class Form1 : Implements IDisposable
    'Desconheço se isto  está  a  funcar   -   o IDisposable

    Private RevisionX As String = "Versão 025"
    'Nota : O valor das  notas entre si, vai de 1(semibreve) á quartifusa que representa 1/128  avos da semibreve
    'Assim a  relação entre elas é :  1    1/2   1/4   1/8    1/16    1/32   1/64   1/128
    Public Rapidez As Integer = 256 ' Apoia-se na contagem dos ticks no timer atribuindo um salto maior ou menor (mais  eficaz)
    Public Andamento As Integer = 2 ' Define o intervalo - timer.interval (menos  eficaz)
    ' Nota:  Uma  maior  precisão leva a que  mais impulsos não sejam reconhecidos . Ao inves adultera-se a composição.
    Private Precisão As New Decimal '        0,6<Precisão<1,5'   Parece poder ficar  assim 
    Private ApresentaçãoBoolean As Boolean = False
    Private MostrarCódigo As Boolean = False
    Private lblMuscKey(61) As Label
    Private lblChordscKey(61) As Label
    Private lblInstruments(127) As Label
    Private lblOctave(5) As Label
    Public lblChords(12) As Label
    Private WithEvents FlLayPanel, FlLayPanel2 As New FlowLayoutPanel

    Private WithEvents ChordsComboBoxInstruments As New ComboBox()
    Private WithEvents SoloComboBoxInstruments As New ComboBox()
    Private lblTitle As New Label
    'Dim ttip, ttip2, ttip3, ttip4, ttip5, ttip6, ttip7, ttip8, ttip9, ttip10, ttip11 As New ToolTip
    Private numKeysBlack() As Integer =
        {2, 4, 7, 9, 11, 14, 16, 19, 21, 23, 26, 28, 31,
         33, 35, 38, 40, 43, 45, 47, 50, 52, 55, 57, 59}
    Private numKeysWhite() As Integer =
        {1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22,
         24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 41, 42,
         44, 46, 48, 49, 51, 53, 54, 56, 58, 60, 61}
    Private hMidiOut As IntPtr
    Private intMsg, intMsgChords As Integer
    Private Msg As NativeMethodsIII.MidiMsg

    Private Octave As Byte = 1 'Octave from where begins the first key of the musical keyboard
    Private TrueOct As New Integer ' Variável de introdução "manual" isto é  sem dependencias.... 
    ' Strings com as Notas Musicais
    Private SeteNotas() As String = {"", "DÓ", "RÉ", "MI", "FÁ", "SOL", "LÁ", "SI"}
    Private DozeNotasComSustenidos() As String = {"", "DÓ", "#DÓ",
        "RÉ", "#RÉ", "MI", "FÁ",
        "#FÁ", "SOL", "#SOL", "LÁ",
        "#LÁ", "SI"}
    Private DozeNotasComBemóis() As String = {"", "DÓ", "bRÉ", "RÉ", "bMI", "MI", "FÁ", "bSOL", "SOL", "bLÁ", "LÁ", "bSI", "SI"}
    'Acordes
    Private NamedChords() As String =
        {"Chors =0", "Maior", "Maior +", "Maior -", "Maior 6ª", "Maior 7ª", "Menor",
        "Menor +", "Menor -", "Menor 6ª", "Menor 7ª", "Anotações"}

    Private VerifyChordsExist As Boolean = False
    Private ChordsName, KeyChordsName As String

    Private ListKeyPress As New List(Of Integer)
    Private VolumeKey As Byte = 127 'min=0; max=127
    Private Instrument1InMemory As Integer
    Private Instrument2InMemory As Integer '= 0
    Private RelevantNotes1, RelevantNotes2, RelevantNotes3, RelevantNotes4,
        RelevantNotes5, RelevantNotes6, RelevantNotes7, RelevantNotes8,
        RelevantNotes9, RelevantNotes10, RelevantNotes11, RelevantNotes12 As Integer
    Private LblcomboInfo, LblInstrumInfo As New Label
    Private StrSoloInstrument, StrInstrument As String
    Private ModeKeysDown As String = "Solo" ' Or "Chords"  comuta a ação das teclas entre os  dois teclados
    Private ButtonSwitch1, ButtonSwitch2 As New Button
    Private Note, NoteChords, NoteTest As Byte
    Private NotaChordsName() As String
    'Pauta

    Public WithEvents PautaPictureBox As New PictureBox()
    '»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»   DATAGRID   DE   REGISTO   GERAL
    Private MemóriaPautaPanel As New FlowLayoutPanel
    'Acima temos  a  declaração da  caixa do  datagrid 
    Public WithEvents MemóriaPauta, DataShow As New DataGridView ' Elemento chave de preenchimento prévio no arranque 
    'da  aplicação e consulta posterior constante (Memória Pauta)  e que  fica  invisivel 
    '********************************************************************************************************
    '***** Notas com #  ********|  DÓ(1)   |   #DÓ(1) |  RÉ(1)   |  #RÉ(1)   .......   ColumnHeaders
    '********************************************************************************************************
    '*****     0                | 1        |  2       |  3       |   4     ......Numeração das Teclas (Max 61) e indices do datagriView
    '********************************************************************************************************
    '*****   Teclado Sup #      |  180     |  175     ...... Começa  em  cerca  de  2\3 da altura da pauta e  sobe
    '********************************************************************************************************
    '*****   Teclado Inf #      |  310     |  305     ...... Começa  em  cerca  de  3\3 da altura da pauta e  sobe até 1\3
    '********************************************************************************************************
    '***** Notas com Bemóis*****|  DÓ(1)   |   bRÉ(1)  |  RÉ(1)   |  bMI(1)   .......   New Row
    '********************************************************************************************************
    '*****   Teclado Sup b     |  180      |   175     ...... Começa  em  cerca  de  2\3 da altura da pauta e  sobe
    '********************************************************************************************************
    '*****   Teclado Inf b     |  310      |   305     ...... Começa  em  cerca  de  3\3 da altura da pauta e  sobe até 1\3
    '********************************************************************************************************
    '*****Nota  :   a numeração é  diferente nos  casos dos  sustenidos e dos bemóis 
    '               Esta  consulta  constante  pesa bastante no desempenho da  aplicação pelo que 
    '                     tentei reduzir todos  os  passos  ao  minimo sobretudo nos  acordes
    '                     Pelo que  nestes o processo de  consulta inicial:
    '                                  Tecla - (nº1 a 61)  -   NotaMusical   -   Posição Pauta
    '                     Reduzi  para  :
    '                                  Tecla - (nº1 a 61)  -   -   Posição Pauta 
    'Private StrYYY() As String
    Private NotaSolo, NotaChords As String
    Private TeclaSupIsClickid As Boolean = False 'Atributo para despistar falsos cliques
    Private TeclaInfIsClickid As Boolean = False
    Private AlturaDaPauta As Integer = 300
    Private ComprimentoDaPauta As Integer = 8000
    Private EspassamentoEntreNotas As Integer = 20
    Private WithEvents BitMapPauta As New Bitmap(ComprimentoDaPauta, AlturaDaPauta)
    '**************Matriz Memória dos bitmaps para a construção da musica
    'MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
    '**************Permite por  ex  voltar  atrás , apagar até  50???  vezes
    Dim MemMáxima As Integer = 50 ' 20 ' Redução para evitar mais  custos  de  memória
    Private BitmapMemPautaSup(MemMáxima) As Bitmap ' O indice é  indexado ao  valor  da  (coordenadaX - valor Inicial)/20
    Private BitmapMemPautaInf(MemMáxima) As Bitmap
    Private WithEvents GoOnSup, GoBackSup, GoOnInf, GoBackInf As New Button ' Para apagar  isto é mudar  de  bitmap
    Private CorrecçãoAdaptativa As New Integer '?????
    Private MemPautaSup As New Integer  ' Parametro  essencial  neste  contexto que  depende das coodenadas X 
    Private MemPautaInf As New Integer  ' Parametro  essencial  neste  contexto que  depende das coodenadas X 
    'Private WithEvents BitMapNota As New Bitmap(24, 32)
    Private CoordenadaYSup, CoordenadaYInf, CoordenadaXSup, CoordenadaXInf As New Integer
    'MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
    'Memorização dos  bitmaps EDIÇÃO MANUAL  para poder  apagar - ATÉ  50  Vezes  *******************************
    Private MemMaxManual As Integer = 50 '20 'Reduzi 50
    Private BitmapMemPautaManual(MemMaxManual) As Bitmap ' 0  indice terá  a  ver  com  as  utilizações
    Private IndiceMemPautaManual As Integer = 0
    Private WithEvents ManualClearBtn, ManualRedrawBtn, ManualReset As New Button

    Dim LabelInfo, LabelInfo2 As New Label
    Dim TextInput, TextInput2 As New TextBox
    '»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»  POSIÇÂO   NA   PAUTA - EIXO DOS YYY

    Dim PSup() As String = {"Piano Superior", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0,
                             250", "246", "242", "238", "234", "230", "226", "222", "218", "214", "210", "206", "202", "198,
                             194", "190", "186", "182", "178", "174", "170", "166", "162", "158", "154", "150", "146", "142,
                             138", "134", "130", "126", "122", "118", "114", "110", "106", "102", "98", "94", "90", "86", "82,
                             78", "74", "70", "66", "62", "58", "54", "50", "46", "42", "38", "34", "30", "26", "22", "18", "14", "10,
                             6", "2", "0", "0", "0", "0", "0", "0", "0", "0", "0"}

    Dim PInf() As String = {"Piano Inferior", "250", "246", "242", "238", "234", "230", "226", "222", "218", "214", "210", "206", "202,
                             198", "194", "190", "186", "182", "178", "174", "170", "166", "162", "158", "154", "150,
                             146", "142", "138", "134", "130", "126", "122", "118", "114", "110", "106", "102", "98,
                             94", "90", "86", "82", "78", "74", "70", "66", "62", "58", "54", "50", "46", "42", "38", "34,
                             30", "26", "22", "18", "14", "10", "6", "2", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0,
                             0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"}
    '"Notas :",
    Dim OrdemDasNotasComSustenidos() As String = {"Acidentes = # :", "DÓ(1)", "#DÓ(1)", "RÉ(1)", "#RÉ(1)", "MI(1)", "FÁ(1)", "#FÁ(1)",
                            "SOL(1)", "#SOL(1)", "LÁ(1)", "#LÁ(1)", "SI(1)", "DÓ(2)", "#DÓ(2)", "RÉ(2)", "#RÉ(2)",
                            "MI(2)", "FÁ(2)", "#FÁ(2)", "SOL(2)", "#SOL(2)", "LÁ(2)", "#LÁ(2)", "SI(2)", "DÓ(3)",
                            "#DÓ(3)", "RÉ(3)", "#RÉ(3)", "MI(3)", "FÁ(3)", "#FÁ(3)", "SOL(3)", "#SOL(3)", "LÁ(3)",
                            "#LÁ(3)", "SI(3)", "DÓ(4)", "#DÓ(4)", "RÉ(4)", "#RÉ(4)", "MI(4)", "FÁ(4)", "#FÁ(4)",
                            "SOL(4)", "#SOL(4)", "LÁ(4)", "#LÁ(4)", "SI(4)", "DÓ(5)", "#DÓ(5)", "RÉ(5)", "#RÉ(5)",
                            "MI(5)", "FÁ(5)", "#FÁ(5)", "SOL(5)", "#SOL(5)", "LÁ(5)", "#LÁ(5)", "SI(5)", "DÓ(6)",
                            "#DÓ(6)", "RÉ(6)", "#RÉ(6)", "MI(6)", "FÁ(6)", "#FÁ(6)", "SOL(6)", "#SOL(6)", "LÁ(6)",
                            "#LÁ(6)", "SI(6)", "DÓ(7)", "#DÓ(7)", "RÉ(7)", "#RÉ(7)", "MI(7)", "FÁ(7)", "#FÁ(7)",
                            "SOL(7)", "#SOL(7)", "LÁ(7)", "#LÁ(7)", "SI(7)", "DÓ(8)", "#DÓ(8)", "RÉ(8)", "#RÉ(8)",
                            "MI(8)", "FÁ(8)", "#FÁ(8)", "SOL(8)", "#SOL(8)", "LÁ(8)", "#(LÁ8)", "SI(8)"}

    Dim OrdemDasNotasComBemóis() As String = {"Acidentes = Bemóis :", "DÓ(1)", "bRÉ(1)", "RÉ(1)", "bMI(1)", "MI(1)", "FÁ(1)", "bSOL(1)",
                            "SOL(1)", "bLÁ(1)", "LÁ(1)", "bSI(1)", "SI(1)", "DÓ(2)", "bRÉ(2)", "RÉ(2)", "bMI(2)",
                            "MI(2)", "FÁ(2)", "bSOL(2)", "SOL(2)", "bLÁ(2)", "LÁ(2)", "bSI(2)", "SI(2)", "DÓ(3)",
                            "bRÉ(3)", "RÉ(3)", "bMI(3)", "MI(3)", "FÁ(3)", "bSOL(3)", "SOL(3)", "bLÁ(3)", "LÁ(3)",
                            "bSI(3)", "SI(3)", "DÓ(4)", "bRÉ(4)", "RÉ(4)", "bMI(4)", "MI(4)", "FÁ(4)", "bSOL(4)",
                            "SOL(4)", "bLÁ(4)", "LÁ(4)", "bSI(4)", "SI(4)", "DÓ(5)", "bRÉ(5)", "RÉ(5)", "bMI(5)",
                            "MI(5)", "FÁ(5)", "bSOL(5)", "SOL(5)", "bLÁ(5)", "LÁ(5)", "bSI(5)", "SI(5)", "DÓ(6)",
                            "bRÉ(6)", "RÉ(6)", "bMI(6)", "MI(6)", "FÁ(6)", "bSOL(6)", "SOL(6)", "bLÁ(6)", "LÁ(6)",
                            "bSI(6)", "SI(6)", "DÓ(7)", "bRÉ(7)", "RÉ(7)", "bMI(7)", "MI(7)", "FÁ(7)", "bSOL(7)",
                            "SOL(7)", "bLÁ(7)", "LÁ(7)", "bSI(7)", "SI(7)", "DÓ(8)", "bRÉ(8)", "RÉ(8)", "bMI(8)",
                            "MI(8)", "FÁ(8)", "bSOL(8)", "SOL(8)", "bLÁ(8)", "LÁ(8)", "bSI(8)", "SI(8)"}

    Private Acidentes As String = "Sustenidos" 'Or "Bemóis" ' Terá de haver um swicht button para alterar manualmente
    'Ajustes na  colocação das Notas na  Pauta  sse  necessário
    Private CorrecçãoYPautaI, CorrecçãoYPautaS As Integer ' Permite ajustes na  altura - eixo dos YYY
    'NOTA  :   O  numero  das  colunas  se  diferente  inviabiliza imediatamente estes  objectos  
    Dim DimColunas As Integer = OrdemDasNotasComSustenidos.Length
    Dim DimPSup As Integer = PSup.Length
    Dim DimPInf As Integer = PInf.Length
    Private ColCount As Integer = OrdemDasNotasComSustenidos.Length
    ' Para verificaçÃO e  colocação dos  acidentes  em pauta
    Private AcidSustenido, AcidBemol As Boolean
    Private WithEvents SusOrBemois, BemoisOrSus As New Button
    '»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»» ICONS
    'Preparar a  colecção de icons
    Dim IcoSize As Size = CType(New Point(48, 64), Drawing.Size)
    Dim IconsCollection As New Collection From {My.Resources._000wSSSus, My.Resources._000wSSBem, My.Resources._000wSSBequadro,
                       My.Resources._001nCSSemiBreve, My.Resources._002nCSMinima, My.Resources._004nCSSeMinima,
                       My.Resources._008nCSColcheia, My.Resources._016nCSSemiColcheia,
                       My.Resources._032nCSFusa, My.Resources._064nCSSemiFusa, My.Resources._128nCSQuartiFusa,
                       My.Resources._001bCSSemiBreve, My.Resources._002bCSMinima, My.Resources._004bCSSeMinima,
                       My.Resources._008bCSColcheia, My.Resources._016bCSSemiColcheia,
                       My.Resources._032bCSFusa, My.Resources._064bCSSemiFusa, My.Resources._128bCSQuartiFusa,
                       My.Resources._001_CSSemiBreve, My.Resources._002_CSMinima, My.Resources._004_CSSeMinima,
                       My.Resources._008_CSColcheia, My.Resources._016_CSSemiColcheia,
                       My.Resources._032_CSFusa, My.Resources._064_CSSemiFusa, My.Resources._128_CSQuartiFusa,
                       My.Resources._001pSSPausa, My.Resources._002pSSPausa, My.Resources._008pSSPausa,
                       My.Resources._016pSSPausa, My.Resources._032pSSPausa, My.Resources._064pSSPausa,
                       My.Resources._000xSSClaveDeFa, My.Resources._000xSSClaveDeSol24x48,
                       My.Resources._000cSS24CompassoBinario, My.Resources._000cSS34CompassoTernario, My.Resources._000cSS44CompassoQuaternario,
                       My.Resources._000zSSBarraFim, My.Resources._000lSSLigacao, My.Resources._000lSSLigacaoU}
    Private IconsCount As Integer = IconsCollection.Count
    'Private ObjIsSelected As Boolean = False
    Private ObjList As New List(Of Icon) From {My.Resources._000wSSSus, My.Resources._000wSSBem, My.Resources._000wSSBequadro,
                       My.Resources._001nCSSemiBreve, My.Resources._002nCSMinima, My.Resources._004nCSSeMinima,
                       My.Resources._008nCSColcheia, My.Resources._016nCSSemiColcheia,
                       My.Resources._032nCSFusa, My.Resources._064nCSSemiFusa, My.Resources._128nCSQuartiFusa,
                       My.Resources._001bCSSemiBreve, My.Resources._002bCSMinima, My.Resources._004bCSSeMinima,
                       My.Resources._008bCSColcheia, My.Resources._016bCSSemiColcheia,
                       My.Resources._032bCSFusa, My.Resources._064bCSSemiFusa, My.Resources._128bCSQuartiFusa,
                       My.Resources._001_CSSemiBreve, My.Resources._002_CSMinima, My.Resources._004_CSSeMinima,
                       My.Resources._008_CSColcheia, My.Resources._016_CSSemiColcheia,
                       My.Resources._032_CSFusa, My.Resources._064_CSSemiFusa, My.Resources._128_CSQuartiFusa,
                       My.Resources._001pSSPausa, My.Resources._002pSSPausa, My.Resources._008pSSPausa,
                       My.Resources._016pSSPausa, My.Resources._032pSSPausa, My.Resources._064pSSPausa,
                       My.Resources._000xSSClaveDeFa, My.Resources._000xSSClaveDeSol24x48,
                       My.Resources._000cSS24CompassoBinario, My.Resources._000cSS34CompassoTernario, My.Resources._000cSS44CompassoQuaternario,
                       My.Resources._000zSSBarraFim, My.Resources._000lSSLigacao, My.Resources._000lSSLigacaoU}
    'Nome dos objectos e ou das colunas
    Private IconNames() As String = {"Sustenido", "Bemól", "Bequadro", "SemiBreve", "Minima", "SeMinima", "Colcheia",
                       "SemiColcheia", "Fusa", "SemiFusa", "QuartiFusa", "bSemiBreve", "bMinima", "bSeMinima", "bColcheia",
                       "bSemiColcheia", "bFusa", "bSemiFusa", "bQuartiFusa", "#SemiBreve", "#Minima", "#SeMinima", "#Colcheia",
                       "#SemiColcheia", "#Fusa", "#SemiFusa", "#QuartiFusa",
                       "Pausa_1", "Pausa_1_2", "Pausa_1_8", "Pausa_1_16", "Pausa_1_32", "Pausa_1_64",
                       "ClaveDeFá", "ClaveDeSol", "CompassoBinário", "CompassoTernário", "CompassoQuaternário",
                       "Barra_Fim", "Ligação", "LigaçãoU"}
    'Codificação das notas 
    Private IconCodeNames() As String = {"_000wSSSus", "_000wSSBem", "_000wSSBequadro",
                       "_001nCSSemiBreve", "_002nCSMinima", "_004nCSSeMinima", "_008nCSColcheia", "_016nCSSemiColcheia",
                       "_032nCSFusa", "_064nCSSemiFusa", "_128nCSQuartiFusa",
                        "_001bCSSemiBreve", "_002bCSMinima", "_004bCSSeMinima", "_008bCSColcheia", "_016bCSSemiColcheia",
                       "_032bCSFusa", "_064bCSSemiFusa", "_128bCSQuartiFusa",
                       "_001#CSSemiBreve", "_002#CSMinima", "_004#CSSeMinima", "_008#CSColcheia", "_016#CSSemiColcheia",
                        "_032#CSFusa", "_064#CSSemiFusa", "_128#CSQuartiFusa",
                       "_001pSSPausa", "_002pSSPausa", "_008pSSPausa", "_016pSSPausa", "_032pSSPausa", "_064pSSPausa",
                       "_000xSSClaveDeFa", "_000xSSClaveDeSol24x48",
                       "_000cSS24CompassoBinário", "_000cSS34CompassoTernário", "_000cSS44CompassoQuaternário",
                       "_000zSSBarraFim", "_000lSSLigação", "_000lSSLigaçãoU"}

    'Caracteristicas pretendidas para as imagens (icons) nomeadamente  a  defenição da imagem a  32bites
    Private IconsList As New ImageList With {.ImageSize = IcoSize, .ColorDepth = ColorDepth.Depth32Bit, .TransparentColor = Color.White}

    Dim i As New Integer

    'Tratamento  dos icons para  a  pauta  -  manual    DRAG DROP *****************************************
    'Mostroário das notas , acidentes etc***********************************************************************

    Private WithEvents LabelNewNote As New Label
    Private WithEvents FlNotePanel As New FlowLayoutPanel
    Private CharNumber As Integer = IconsCollection.Count ' Colecção dos  icons
    Private CharLabel(CharNumber) As Label ' Irão conter as notas etc
    Private MyIndex As New Integer

    'Clonar o bitmap para arrasto
    Private ImgNotaCurrente As Bitmap '= CType(ImgNotaCurrenteCópy.Clone, Bitmap)
    Private IsClicked As Boolean = False
    'Private CharImgList(IconsCount) As ImageList
    Private CharImgList As New ImageList

    'Arrasto para  a  pauta 
    Private NewPt, Start, PtLabel As Point
    Private WithEvents InfoNoteLaBel As New Label 'With {.Location.PointToClient(Offset(PtLabel.X - Start.X, PtLabel.Y - Start.Y))}
    Private MyCharName As String
    Private RetornaNomeDaNota As String
    Private Coordy, NotaFinalNoDrop, ColocaçãoGuiadaDaNota, NumItensAdicionados As New Integer

    'Memorização da Pauta em ARRAY  na sub CharLabel_DragDrop
    Private MatNotasDragDrop(NumItensAdicionados) As String ' = MyCharName - 
    Private MatPosDragDrop(NumItensAdicionados) As Point '= Coord X
    Private MatSomDragDrop(NumItensAdicionados) As Integer ' NotaFinalNoDrop 
    Private MatIndexDragDrop(NumItensAdicionados) As Integer 'CharLabel(Index)

    'Acessar ao  Código previamente colocado manualmente numa rtb
    Private CodeRichTextBox As New RichTextBox 'Para apresentações informativas inclusive o código

    'Colocar  um   menu
    Private MeuMenuStrip As New MenuStrip() With {.AllowMerge = True, .AutoSize = True, .Name = "MeuMenu",
        .DefaultDropDownDirection = ToolStripDropDownDirection.Default, .Visible = True,
        .Dock = DockStyle.Top, .RenderMode = ToolStripRenderMode.Professional, .Stretch = True}

    'Colocar um novo Form para  visualizar o Loading inicial.....
    'PROGRESS BAR   ..........  ENIGMA »»»»» ?????
    Private WithEvents frmProgressBar As New Form With {.AutoSize = True} ', .ActiveControl = ActiveForm}
    'Declaração da progressBar que é um control (mais facil  de  implementar  )
    Private WithEvents MyProgressBar As New ProgressBar With {.Dock = DockStyle.Top, .Width = 500, .Height = 10,
       .Style = ProgressBarStyle.Blocks, .Minimum = 0, .Maximum = 500, .[Step] = 75, .Parent = frmProgressBar}
    Private CountLoops As Integer = 1
    Private CountSteps As Integer

    Private PautaRichTextBox As New RichTextBox ' A PAUTA
    'Vários
    Private UltimaNotaMusical As Integer ' Para abafar o  som da  nota =  MatSomDragDrop(i)
    Private Compasso As Integer
    Private OpçãoLigação As Boolean
    Private Ligação As New Rectangle
    Private EspaçoAcidentes As Integer = 50 'Espaço no 1º compasso  destinado  a colocar os  sustenidos ou os  bemóis
    Private AcidentePermanente, AcidenteIsolado As String
    Private Silencio As Integer
    'Temporização do click nas teclas
    Private WithEvents TimerTeclasSup As New Timer With {.Interval = 1 * Andamento, .Enabled = False}
    'Private ImpulsoInicial, FinalDoImpulso As Integer
    Private DuraçãoDoImpulso As Integer ' = CInt(DateAndTime.DateDiff(DateInterval.Second, FinalDoImpulso, ImpulsoInicial))
    'Afixaçºao da nota respectiva na pauta ( NOTA: terá de se fazer sempre uma  aproximação visto que a temporização das notas é sempre metade da anterior )
    'Assim tem-se se a SemiBreve valer 1 :  SemiBreve (1),Minima(1/2),SeMinima(1/4),Colcheia(1/8).....
    Private Marcar As Boolean = False
    Private Indíce As Integer ' Indice associado á coleção de icons para permitir copiar o icon para a pauta
    Private CodificaçãoIcon As Integer ' Código inscrito no nome do icon relativo ao tempo de duração num compasso
    Private DesvioTemporal As Decimal ' Desviu para o tempo ideal de cada notação musical
    Private DesignaTeclas As String ' Para encontrar os icons com acidentes # ou Bemóis
    'Nova Coleção de Icons para as teclas
    Dim IconsTeclasCollection As New Collection From {My.Resources._001nCSSemiBreve, My.Resources._002nCSMinima, My.Resources._004nCSSeMinima,
                       My.Resources._008nCSColcheia, My.Resources._016nCSSemiColcheia,
                       My.Resources._032nCSFusa, My.Resources._064nCSSemiFusa, My.Resources._128nCSQuartiFusa,
                       My.Resources._001bCSSemiBreve, My.Resources._002bCSMinima, My.Resources._004bCSSeMinima,
                       My.Resources._008bCSColcheia, My.Resources._016bCSSemiColcheia,
                       My.Resources._032bCSFusa, My.Resources._064bCSSemiFusa, My.Resources._128bCSQuartiFusa,
                       My.Resources._001_CSSemiBreve, My.Resources._002_CSMinima, My.Resources._004_CSSeMinima,
                       My.Resources._008_CSColcheia, My.Resources._016_CSSemiColcheia,
                       My.Resources._032_CSFusa, My.Resources._064_CSSemiFusa, My.Resources._128_CSQuartiFusa}
    Dim IconsTeclasCodeNames() As String = {"_001nCSSemiBreve", "_002nCSMinima", "_004nCSSeMinima",
                       "_008nCSColcheia", "_016nCSSemiColcheia",
                       "_032nCSFusa", "_064nCSSemiFusa", "_128nCSQuartiFusa",
                       "_001bCSSemiBreve", "_002bCSMinima", "_004bCSSeMinima",
                       "_008bCSColcheia", "_016bCSSemiColcheia",
                       "_032bCSFusa", "_064bCSSemiFusa", "_128bCSQuartiFusa",
                       "_001_CSSemiBreve", "_002_CSMinima", "_004_CSSeMinima",
                       "_008_CSColcheia", "_016_CSSemiColcheia",
                       "_032_CSFusa", "_064_CSSemiFusa", "_128_CSQuartiFusa"}
    Dim IconsTeclas As Integer = IconsTeclasCodeNames.Count

    'Bonecada para arrastar......................... por escolha do utilizador ( miniaturas automáticas )
    'Hierarquia:.............................
    Private WithEvents Bonecada As New Form With {.AutoSize = True} ', .ActiveControl = ActiveForm}
    Private WithEvents BonecoFlLayPanel As New FlowLayoutPanel With {.Parent = Bonecada}

    Dim BonecoSize As Size = CType(New Point(128, 128), Drawing.Size)
    Dim BonecoCollection As New Collection From {My.Resources.Boneco0, My.Resources.Boneco1, My.Resources.Boneco2, My.Resources.Boneco3, My.Resources.Boneco4, My.Resources.Boneco5, My.Resources.Boneco6}
    Private BonecosCount As Integer = BonecoCollection.Count
    Private BonecoList As New List(Of Image) From {My.Resources.Boneco0, My.Resources.Boneco1, My.Resources.Boneco2, My.Resources.Boneco3, My.Resources.Boneco4, My.Resources.Boneco5, My.Resources.Boneco6}
    Private BonecoLabel(BonecosCount) As Label
    'Private WithEvents Bonecos As New Label With {.Parent = BonecoFlLayPanel, .Tag = BonecoLabel.Clone}
    Private ImgBonecoCurrente As Bitmap
    Private MyIndexII As New Integer

    ' Avaliação de Memória e CPU
    '  Em Modulo próprio

#Region "Me Load"
    '    <mdaConfig>
    '  <assistants>
    '    <contextSwitchDeadlock />
    '  </assistants>
    '</mdaConfig>
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        'FORM  PRINCIPAL  **************************************
        On Error GoTo Erros
        'Me.Name = "SongWriter"
        'Teste para os icons -  Verificação de erros
        If IconsCollection.Count <> IconNames.Count Then
            'Teste inicial 
            MsgBox("A colecção de itens " & IconsCollection.Count & " e a matriz com os seus  nomes divergem " & IconNames.Count)
        End If
        If IconsTeclasCollection.Count <> IconsTeclasCodeNames.Count Then
            'Teste inicial 
            MsgBox("A colecção de itens " & IconsTeclasCollection.Count & " e a matriz com os seus  nomes divergem " & IconsTeclasCodeNames.Count)
        End If
        'Só mostrar  a  aplicação depois  de totalmente estar na  memória
        Me.AllowTransparency = True
        'Me.SuspendLayout()
        Application.EnableVisualStyles()
        Me.Visible = False  '  Esconder o  formulário principal até o load estar  completo
        'Declaração de Não existencia de controles (Forms) filho frmProgressBar
        Me.IsMdiContainer = False
        'ProgressBar para assegurar que não haja "ContextSwitchDeadlock" no inicio da  app
        ' ***********'Visionar o andamento na progress 1
        ContruçãoDaProgressBarEmNovoForm(sender, e)
        If Not True Then frmProgressBar.Activate()
        frmProgressBar.PerformAutoScale() 'To get focus to the  second  form
        'Sendo que  os  acessos  seguintes  seráo  efectuados   por  um  sub 'ProBarProgression()
        ProBarProgression(sender, e)
        'Implementação De Menu
        ImplementaçãoDeMenuStrip()

        MyProgressBar.PerformStep() 'Substitui o primeiro accesso ao form e à progressbar por um  comando  directo

        '»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»Configuração do form principal»»»»»»»»»»»»»»»»»»»»»»»»»
        ConfiguraçãoDoFormPrincipal()
        'Criar um painel de deslizamento horizontal que suporta varias RichTextBox
        PainelDeDeslizamentoHorizontalSuperior()

        PainelDeDeslizamentoHorizontalInferior()
        ' ***********'Visionar o andamento na progress 2
        ProBarProgression(sender, e) '*******************************************************

        frmProgressBar.PerformAutoScale() 'To get focus to the  second  form

        ConstruçãoDeVáriosObjectos()

        ' ***********'Visionar o andamento na progress 3
        ProBarProgression(sender, e) '*******************************************************

        '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
        ''Construção da caixa  exterior Para o datagrid principal e que fica invisivel
        ' Construção  de  uma  tabela  escrita para consulta de posição na pauta
        ' Um DataGridView chamado MemóriaPauta para consulta em tempo de execussão
        '***************Construção total do DataGridView
        ConstruçãoDoMotorPrincipal()
        VisualizaçãoDoMotorPrincipal()
        ' ***********'Visionar o andamento na progress 4
        ProBarProgression(sender, e) '*******************************************************

        CreateMusicalKeyBoard() 'Os dois  pianos  
        CreateChordsKeyBoard()
        'Permite  deslocar  as  oitavas no teclado
        CreateOctaveButtons()
        'Permite escolher as tonalidades 
        CreateChordsButtons()
        ' ***********'Visionar o andamento na progress 5
        ProBarProgression(sender, e) '*******************************************************

        'Permite escolher os instrumentos
        CreateComboBoxSoloInstruments()
        CreateComboBoxChordsInstruments()
        'Para permutar de piano e de input de teclado keyboard
        CreateButtonsSwicht()
        'Inicio da contruçao das linhas da pauta  e claves
        'Dimenção 300- espaço entre linhas 10- Oitavas .....

        'Visionanar o andamento na progress 6
        ProBarProgression(sender, e) '*******************************************************

        CreatePanelPautaWithPictureBox()

        ' ***********'Visionar o andamento na progress 7
        ProBarProgression(sender, e) '*******************************************************

        ConstruindoMemóriaPautaComSustenidos()

        AdicionandoLinhasMemóriaPautaComBemóis()
        '***********'Visionar o andamento na progress 8
        ProBarProgression(sender, e) '*******************************************************

        'Mostruário : labeis com icons transparentes ( notação das notas musicais ) para  edição manual da  pauta
        MostroárioMusical() 'Notas musicais  edição  manual   para  a pauta 

        '***********'Visionar o andamento na progress 9
        ProBarProgression(sender, e) '*******************************************************

        ComandosParaGerirEscritaNaPauta() ' Apagar, renovar até 20 vezes
        LoadTooltips() 'Informativo

        'How it Works
        NativeMethodsIII.midiOutOpen(hMidiOut,
                                  NativeMethodsIII.MIDI_MAPPER, CType(0, IntPtr),
                                        CType(0, IntPtr), NativeMethodsIII.CALLBACK_NULL)

        ApresentaçãoBoolean = True
        ApresentaçõesNaRichtextBox()

        '***********'Visionar o andamento na progress 10 ( ultimo  passo )
        ProBarProgression(sender, e) '*******************************************************

        If MyProgressBar.Value >= MyProgressBar.Maximum Then
            Memória.Tim1.Enabled = False
            MyProgressBar.Dispose()
            'Fechar o Form
            frmProgressBar.Close() ' fecha a form do  progrees  bar

            'Retomar o layout do  form  principal
            Me.ResumeLayout(False) 'Necessário
            Me.Visible = True ' No final  do  load  é  que  o  form  é  mostrado 
            CountLoops = 1 ' reseta  a contagem  dos  loops  iniciais ( no Load ) que não deve exceder um
            Me.VerticalScroll.Value = 0

        End If

        Exit Sub
Erros:
        MsgBox("Erro detectado no Load do projecto :    " & ErrorToString())

    End Sub

    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown

        If ListKeyPress.Contains(e.KeyCode) = True Then Exit Sub ' Key is already pressed
        If Key(e.KeyCode) = 0 Then Exit Sub ' : MsgBox("KeyCode Nulo   ...." & e.KeyValue)   'Key without function

        Dim KeyIndexChords As Integer
        If ModeKeysDown = "Solo" Or ModeKeysDown = "" Then ' Só Piano superior
            'Afixaçaõ em pauta
            DesignaçãoDaNotaPianoSup(CByte(KeySolo(e.KeyCode)))
            CoordenadaXSup = CoordenadaXSup + 20
            ObtençãoCoordenadaYSup(NotaSolo, CoordenadaXSup)
            PlayMusicalNote(CByte(KeySolo(e.KeyCode)), VolumeKey, Octave)

        ElseIf ModeKeysDown = "Chords" Then 'Só Piano inferior
            For I As Integer = 1 To 11
                If lblChords(I).BackColor = System.Drawing.Color.FromArgb(150, 150, 150) Then
                    KeyIndexChords = I
                    KeyChordsName = lblChords(KeyIndexChords).Text
                End If
            Next

            If KeyChordsName <> "" And KeyChordsName <> "Chors =0" Then
                VerifyChordsExist = True
                lblChordsWithKey_KeyDown(sender, e)

            ElseIf KeyChordsName <> "" And KeyChordsName = "Chors =0" Then
                VerifyChordsExist = False
                'Afixaçaõ em pauta
                DesignaçãoDaNotaPianoInf(CByte(KeyChords(e.KeyCode)))
                CoordenadaXInf = CoordenadaXInf + 20
                ObtençãoCoordenadaYInf(NotaChords, CoordenadaXInf)
                PlayMusicalChords(CByte(KeyChords(e.KeyCode)), VolumeKey, Octave)

            Else
                MsgBox("New Mystery... ")
            End If

        End If
        ListKeyPress.Add(e.KeyCode)
    End Sub

    Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp

        Dim KeyIndexChords As Integer

        If ModeKeysDown = "Solo" Then
            OffMusicalNote(CByte(KeySolo(e.KeyCode)), Octave)
            'Remover vestigios da tecla tocada nos  dois pianos
            ListKeyPress.Remove(e.KeyCode)
            Try
                If numKeysWhite.Contains(Msg.Note) And KeySolo(e.KeyCode) > 0 Then
                    lblMuscKey(Msg.Note).BackColor = Color.White
                ElseIf numKeysBlack.Contains(Msg.Note) And KeySolo(e.KeyCode) > 0 Then
                    lblMuscKey(Msg.Note).BackColor = Color.Black
                Else
                    ' MsgBox("Erro.... provavélmente Tecla  sem função")
                End If
            Catch ex As Exception
            End Try

        ElseIf ModeKeysDown = "Chords" Then
            For I As Integer = 1 To 11
                If lblChords(I).BackColor = System.Drawing.Color.FromArgb(150, 150, 150) Then
                    KeyIndexChords = I
                    KeyChordsName = lblChords(KeyIndexChords).Text
                End If
            Next
            'Mas se houver indicação para  acordes então 
            If KeyChordsName <> "" And KeyChordsName <> "Chors =0" Then
                VerifyChordsExist = True
                lblChordsWithKey_KeyUp(sender, e)
                'Mas se a  variável  Booleana  VerifyChordsExist = False então 
                'o teclado inferior pode  ser  usado na  mesma  mas apenas com teclas  simples  - sem acordes 
            ElseIf VerifyChordsExist = False Then
                OffMusicalNoteChords(CByte(KeyChords(e.KeyCode)), Octave)
            Else
                MsgBox("New ....Mystery")
            End If
            'Remover vestigios da tecla tocada nos  dois pianos
            ListKeyPress.Remove(e.KeyCode)
            Try
                If numKeysWhite.Contains(Msg.NoteChords) And KeyChords(e.KeyCode) > 0 Then
                    lblChordscKey(Msg.NoteChords).BackColor = Color.White
                ElseIf numKeysBlack.Contains(Msg.NoteChords) And KeyChords(e.KeyCode) > 0 Then
                    lblChordscKey(Msg.NoteChords).BackColor = Color.Black
                Else
                    ' MsgBox("Erro.... provavélmente Tecla  sem função")
                End If
            Catch ex As Exception
            End Try
        End If

    End Sub

#End Region

#Region "Load Vários objectos para a form principal  -  uma  questão  de  organização "

    Public Sub ConfiguraçãoDoFormPrincipal()

        ' Configura o titulo do formulário 
        Dim ApplicationTitle As String = System.IO.Path.GetFileNameWithoutExtension(My.Application.Info.AssemblyName) &
        "   " & RevisionX & "  By José oliveira   "

        'Configuração do form principal»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»
        With Me
            .AutoScroll = True
            .VerticalScroll.Enabled = True
            .HorizontalScroll.Visible = False
            .KeyPreview = True
            .BackColor = System.Drawing.Color.FromArgb(40, 40, 40)
            '.Size = CType(New Point(840, 625), Drawing.Size)
            .Size = CType(New Point(840, 575), Drawing.Size)
            .Text = ApplicationTitle
            .MaximizeBox = False
            .FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
            '.StartPosition = FormStartPosition.CenterScreen
            .SetBounds(CInt((Screen.PrimaryScreen.Bounds.Width - .Width) / 2),
            CInt((Screen.PrimaryScreen.Bounds.Height - .Height) / 2) - 50,
            .Width, .Height)
            .VerticalScroll.Value = 0
        End With

    End Sub

    ' Como Curiosidade ............................
    Function GetAssemblyFileVersion(ByVal MyVersion As String) As String
        Dim ProjectAssembly As Reflection.Assembly
        ProjectAssembly = Reflection.Assembly.GetExecutingAssembly()

        For Each attr As Attribute In ProjectAssembly.GetCustomAttributes(False)
            If TypeOf attr Is Reflection.AssemblyFileVersionAttribute Then
                Dim FileVerAttr As Reflection.AssemblyFileVersionAttribute = CType(attr, AssemblyFileVersionAttribute)
                MyVersion = FileVerAttr.Version
                Return MyVersion
            End If
        Next

        Throw New Reflection.TargetInvocationException(
        New KeyNotFoundException(
            "Cannot find custom attribute 'AssemblyFileVersionAttribute'"))
    End Function

    Public Sub PainelDeDeslizamentoHorizontalSuperior()
        'Crear um painel de deslizamento horizontal que se sobrepõe com a CodeRichTextBox
        'Dim FlLayPanel2 As New FlowLayoutPanel
        With FlLayPanel2
            .AutoScroll = True
            .VerticalScroll.Visible = False
            .HorizontalScroll.Enabled = True
            .HorizontalScroll.Visible = True
            .HorizontalScroll.SmallChange = 100
            .HorizontalScroll.LargeChange = 200
            .HorizontalScroll.Maximum = 10000
            .HorizontalScroll.Minimum = 0
            .BorderStyle = BorderStyle.FixedSingle
            .Location = New Point(5, Me.MainMenuStrip.Height) '- Me.VerticalScroll.Value)
            .Size = CType(New Point(800, 200), Drawing.Size)
            .FlowDirection = FlowDirection.TopDown
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            .Visible = False
        End With
        Me.Controls.Add(FlLayPanel2)
        FlLayPanel2.Contains(PautaRichTextBox)
        'Criar uma richtext embutida no FlLayPanel2 para visualização de pautas   
        With PautaRichTextBox
            .Clear()
            .BackColor = Color.Aquamarine
            .Height = AlturaDaPauta
            .Width = 8000
            '.Location = New Point(5 - FlLayPanel2.HorizontalScroll.Value, MainMenuStrip.Height - FlLayPanel2.VerticalScroll.Value)
            .Location = FlLayPanel2.Location
            .ScrollBars = RichTextBoxScrollBars.None
            .BorderStyle = BorderStyle.None
            .SelectionIndent = 1
            .Visible = False
        End With
        FlLayPanel2.Controls.Add(PautaRichTextBox)

        'Criar a richtext para apresentações por  exemplo esta  não  embutida 
        'Dim CodeRichTextBox As New RichTextBox
        With CodeRichTextBox
            .BackColor = Color.PaleGoldenrod
            .Clear()
            .Width = 1000
            .Height = 200
            .Location = New Point(5 - Me.HorizontalScroll.Value, 25 - Me.VerticalScroll.Value)
            .Font = New Font("Arial", 4, FontStyle.Bold)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BorderStyle = BorderStyle.FixedSingle
            .Multiline = True
            .Copy()
            .Paste()
            .ReadOnly = False
            .SelectionIndent = 10 ' Margin left
            .SelectionHangingIndent = 15
            .SelectionRightIndent = 5 ' Margin Rigth
            .ShowSelectionMargin = True
            .ScrollBars = RichTextBoxScrollBars.Both
            .AllowDrop = False
            .EnableAutoDragDrop = False
            .Visible = True
            .DetectUrls = True
            .WordWrap = False
        End With
        FlLayPanel2.Controls.Add(CodeRichTextBox)

        ' Criar Também aqui um espaço para apresentação de figurinhas para  arrastar - só aparecerá on demand
        '»»»»»»»»»»»»»»    Colocação das  imagens  nas labeis(i)
        With BonecoFlLayPanel       '"Construção de vários Labeis contendo IMagens para arrastar .bmp"
            .AutoScroll = True
            .VerticalScroll.Visible = False
            .HorizontalScroll.Enabled = True
            .HorizontalScroll.Visible = True
            .HorizontalScroll.SmallChange = 100
            .HorizontalScroll.LargeChange = 200
            .HorizontalScroll.Maximum = 10000
            .HorizontalScroll.Minimum = 0
            .BorderStyle = BorderStyle.FixedSingle
            .Location = New Point(5, Me.MainMenuStrip.Height) '- Me.VerticalScroll.Value)
            .Size = CType(New Point(800, 200), Drawing.Size)
            .FlowDirection = FlowDirection.TopDown
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            .Visible = False
        End With
        Me.Controls.Add(BonecoFlLayPanel)
        BonecoFlLayPanel.Contains(BonecoLabel(BonecosCount))
        For i = 0 To BonecosCount - 1
            BonecoLabel(i) = New Label
            With BonecoLabel(i)
                If i >= 0 Then
                    .Location = New Point(128 * (i - 1) + 5, 230)
                Else
                    .Location = New Point(+5, 230)
                End If
                .Size = BonecoSize
                .Tag = i
                .Image = CType(BonecoList(i).Clone, Image)
                .Name = BonecoCollection(i + 1).ToString
                .BackColor = Color.Transparent
                .BorderStyle = BorderStyle.Fixed3D

                .AutoEllipsis = True
                .Handle.Equals(BonecoLabel(i))

            End With

            BonecoFlLayPanel.Controls.Add(BonecoLabel(i))
            'Associar evento que  ocorre em run time e por iniciativa do USER
            AddHandler BonecoLabel(i).MouseDown, AddressOf BonecoFlLayPanel_MouseDown

        Next

    End Sub

    Public Sub PainelDeDeslizamentoHorizontalInferior()
        'Criar um painel de deslizamento horizontal
        'Dim FlLayPanel As New FlowLayoutPanel
        'On Error GoTo Erros

        With FlLayPanel
            .AutoScroll = True
            .VerticalScroll.Visible = False
            .HorizontalScroll.SmallChange = 20
            .HorizontalScroll.LargeChange = 500
            .HorizontalScroll.Minimum = 0
            .HorizontalScroll.Maximum = 8000
            .BorderStyle = BorderStyle.FixedSingle
            .Location = New Point(5, 305)
            .Size = CType(New Point(800, 245), Drawing.Size)

            .FlowDirection = FlowDirection.TopDown
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
        End With
        Me.Controls.Add(FlLayPanel)

        'Costrução da picture dentro do panel  ********************************************
        With PautaPictureBox()
            .Location = New Point(5, 305)
            .BackColor = Color.LightSkyBlue
            .Width = 8000
            .Height = AlturaDaPauta
            .BringToFront()
            .Font = New Font("Arial", 8, FontStyle.Bold)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BorderStyle = BorderStyle.FixedSingle
            .DoDragDrop(DrawMode.OwnerDrawVariable, DragDropEffects.All)
            .AllowDrop = True
            '.GetChildAtPoint(PtNotaOnScreen, 0)
            'AddHanlers to drag and Drop 
            'AddHandler .DragEnter, AddressOf MyNewMusicalNote_DragEnter
            'AddHandler .DragDrop, AddressOf MyNewMusicalNote_DragDrop
            'AddHandler .MouseUp, AddressOf MyNewMusicalNote_MouseUp
            'AddHandler .MouseDown, AddressOf MyNewMusicalNote_MouseMove
            ' AddHandler .MouseUp, New MouseEventHandler(AddressOf PautaPictureBox_MouseUp)
        End With
        'Adicionar picture ao form
        FlLayPanel.Controls.Add(PautaPictureBox)
    End Sub

    Public Sub ConstruçãoDeVáriosObjectos()
        With LabelInfo2
            .Size = CType(New Point(80, 20), Drawing.Size)
            .Location = New Point(150, 565)
            .Visible = False
            .ForeColor = Color.Black
            .BackColor = Color.Azure
            .Font = New Font("Verdana", 8, FontStyle.Bold)
            .TextAlign = ContentAlignment.MiddleCenter
            .Text = "?????"
        End With
        Me.Controls.Add(LabelInfo2)
        'Decisão sobre o modo de acidentar as notas *************
        'Permite trocar entre sustenidos e bemóis
        'Dim SusOrBemois As New Button
        With SusOrBemois
            .Size = CType(New Point(25, 20), Drawing.Size)
            .Location = New Point(240, 555)
            .Visible = True
            .ForeColor = Color.Black
            .BackColor = Color.Azure
            .Font = New Font("Verdana", 8, FontStyle.Bold)
            .TextAlign = CType(HorizontalAlignment.Center, ContentAlignment)
            '.AutoEllipsis = True
            .Text = "#"
        End With
        Me.Controls.Add(SusOrBemois)
        'AddHandler SusOrBemois.MouseClick, AddressOf SusOrBemois_Click
        'Dim BemoisOrSus As New Button
        With BemoisOrSus
            .Size = CType(New Point(25, 20), Drawing.Size)
            .Location = New Point(265, 555)
            .Visible = True
            .ForeColor = Color.Black
            .BackColor = Color.Azure
            .Font = New Font("Verdana", 8, FontStyle.Bold)
            .TextAlign = CType(HorizontalAlignment.Center, ContentAlignment)
            '.AutoEllipsis = True
            .Text = "b"
        End With
        Me.Controls.Add(BemoisOrSus)
        'AddHandler BemoisOrSus.MouseClick, AddressOf BemoisOrSus_Click
    End Sub

    Public Sub ConstruçãoDoMotorPrincipal() 'MemóriaPautaPanel
        ''Construção da caixa  exterior Para o datagrig principal e que fica invisivel
        'Dim MemóriaPautaPanel As New FlowLayoutPanel
        With MemóriaPautaPanel
            .AutoScroll = True
            .VerticalScroll.Visible = True
            .HorizontalScroll.Visible = True
            .BorderStyle = BorderStyle.FixedSingle
            .Size = CType(New Point(350, 100), Drawing.Size)
            .Location = New Point(15, 850) '(15, 1000) '
            .FlowDirection = FlowDirection.TopDown
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            .Visible = False '.Visible = True '
        End With
        Me.Controls.Add(MemóriaPautaPanel)
        'Dim MemóriaPauta As New DataGridView 
        With MemóriaPauta
            .Location = New Point(15, 850) '(15, 1000) '
            .Size = CType(New Point(10000, 200), Drawing.Size)
            .Rows.Clear()
            'Create an unbound DataGridView by declaring a column count.
            .ColumnCount = OrdemDasNotasComSustenidos.Length
            ' Set the column head style.
            .ColumnHeadersVisible = True
            Dim columnHeaderStyle As New DataGridViewCellStyle With {
                .BackColor = Color.Beige,
                .Font = New Font("Verdana", 8, FontStyle.Bold)
            }
            .ColumnHeadersDefaultCellStyle = columnHeaderStyle
            .Visible = False  '.Visible = True ' 
        End With
        MemóriaPautaPanel.Controls.Add(MemóriaPauta)
        '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
    End Sub

    Public Sub VisualizaçãoDoMotorPrincipal()
        'Talvez  ainda  seja  declarado no Load
        'Dim DataShow As New DataGridView
        FlLayPanel2.Contains(DataShow)
        With DataShow
            .BorderStyle = BorderStyle.FixedSingle
            .Size = CType(New Point(10000, 200), Drawing.Size)
            '.Location = New Point(0, 0)
            '.Location = New Point(5 - FlLayPanel2.HorizontalScroll.Value, MainMenuStrip.Height - FlLayPanel2.VerticalScroll.Value)
            .Location = FlLayPanel2.Location
            .ForeColor = Color.Black
            '.BackColor = Color.Aquamarine
            .Rows.Clear()
            'Create an unbound DataGridView by declaring a column count.
            .ColumnCount = MemóriaPauta.ColumnCount
            ' Set the column head style.
            .ColumnHeadersVisible = True
            Dim columnHeaderStyle As New DataGridViewCellStyle With {
                .BackColor = Color.Beige,
                .Font = New Font("Verdana", 8, FontStyle.Bold)
            }
            .ColumnHeadersDefaultCellStyle = columnHeaderStyle
            .Visible = False
        End With
        FlLayPanel2.Controls.Add(DataShow)
    End Sub

#End Region

#Region "On Closing"
    Private Sub SongWriter_OnClosing(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Closing
        'Assegura que  todos  os  processos  são  encerrados ....!?
        'My.Application.SaveMySettingsOnExit = True
        'If Not IsNothing(Note) Then OffMusicalNote(Note, Octave)
        'If Not IsNothing(NoteChords) Then OffMusicalNote(NoteChords, Octave)
        'If Not IsNothing(UltimaNotaMusical) Then OffMusicalNote(CByte(UltimaNotaMusical), Octave)
        My.Resources.ResourceManager.ReleaseAllResources()
        MyBase.Finalize()
        Me.Dispose()
        Me.Close()

        End
    End Sub
#End Region

#Region "ProgressBar em uma nova  form   -    New  Form"
    'Nota : Esta nova form Não pode  ser  MdiChild pois  - permanece invisivel ...
    'Pode haver problemas no inicio da  aplicação por  prossessos demorados sem  resposta daí a progressbar
    'Assistente para Depuração Gerenciada 'ContextSwitchDeadlock' : '
    'O CLR não conseguiu transitar do contexto COM 0x7b4f40 para o contexto COM 0x7b4dd0
    ' durante 60 segundos. O thread que possui o contexto/apartment de destino está 
    'provavelmente a efectuar uma espera de não geração ....
    'Para evitar este problema, todos os threads de STA (single threaded apartment) devem utilizar primitivas de espera de extração (tal como CoWaitForMultipleHandles) e gerar mensagens regularmente durante operações de longa duração.'

    Public Sub ContruçãoDaProgressBarEmNovoForm(ByVal sender As Object, ByVal e As EventArgs) Handles frmProgressBar.Load
        'Pus  de  parte tambem as 'Imports System.Threading.Thread 
        'Nota: Por vezes perde o  foco necessitando do movimento  do  mouse  sobre a form

        With frmProgressBar
            .Width = 650
            .Height = 50
            .Enabled = True
            .Visible = True
            .Location = New Point(Screen.PrimaryScreen.WorkingArea.Left,
                                  Screen.PrimaryScreen.WorkingArea.Top)
            .FormBorderStyle = FormBorderStyle.FixedSingle
            .Visible = True
            .UseWaitCursor = False
            .Validate()

        End With

        'frmProgressBar.Controls.Add()

        'Adding a progressBar to the new form
        With MyProgressBar
            .Dock = DockStyle.Top
            .Width = 500
            .Height = 10
            .Style = ProgressBarStyle.Blocks
            .Minimum = 0
            .Maximum = 500
            .Step = 75 ' dividiu-se  em  10 passos aleatóriamente
            .Value = 0
            .Visible = True
            .Enabled = True
            .Update()
            AddHandler .Validating, AddressOf ProBarProgression
            AddHandler .Layout, AddressOf ProBarProgression

        End With
        frmProgressBar.Controls.Add(MyProgressBar)
        'If Not True Then frmProgressBar.Activate()
    End Sub

    Public Sub ProBarProgression(ByVal sender As Object, ByVal e As EventArgs) Handles MyProgressBar.Validating, MyProgressBar.Layout
        On Error GoTo ProgressLostFocoError
        ' Medição Da Memória USADA
        'Tentativa de obter o gasto de memória
        Dim Tim1 As New Timer With {.Interval = 100, .Enabled = True}
        Dim cpu As New Integer
        Dim Perfor As New PerformanceCounter With {.[ReadOnly] = True, .CategoryName = "Processor", .CounterName = "% Processor Time", .InstanceName = "_Total"}
        Dim Tot As Integer = CInt(Val(My.Computer.Info.TotalPhysicalMemory) / 1024 / 1024)
        Dim Disponiv As Integer = CInt(Val(My.Computer.Info.AvailablePhysicalMemory) / 1024 / 1024)
        Dim Usada As Integer = Tot - Disponiv
        Dim Rate As Integer = CInt(Usada * 100 / Tot)
        With Tim1
            cpu = CInt(Perfor.NextValue)
            MyProgressBar.PerformStep() : CountSteps = CountSteps + 1
            MyProgressBar.FindForm()
            frmProgressBar.Text = "Loading...(IF NOT USE MOUSE)....  " & MyProgressBar.Value / 5 & " %" &
                "  Steps =  " & CountSteps & "    Loops : " & CountLoops & "   Memory Used !!! = " & Rate & " %"
            frmProgressBar.Update()
            MyProgressBar.Update()
            If MyProgressBar.Value >= MyProgressBar.Maximum Then
                CountLoops = CountLoops + 1

                Threading.Thread.Sleep(100) ' 1seg  =  1000
                Exit Sub

                'MsgBox(Err.Description & Err.LastDllError)
            Else

                frmProgressBar.Update()
                MyProgressBar.Update()
            End If
        End With

        Exit Sub
ProgressLostFocoError:
        MsgBox("Progress LostFoco Error :  " & Err.Description)
    End Sub

#End Region

#Region "Construção de vários Labeis contendo IMagens para arrastar .bmp"
    'que  ocorre em run time e por iniciativa do USER

    Private Sub BonecoFlLayPanel_MouseDown(ByVal Sender As Object, ByVal e As MouseEventArgs) Handles BonecoFlLayPanel.MouseDown
        'O papel do Sender aqui é  fundamental para garantir um indice para os lábeis
        'MsgBox(Sender.ToString)
        'Nota : O valor de E.x representa um novo referencial para o mouse em cada lábel pelo que não permite  distinguir entre eles 
        'MsgBox("A cord X do mouse é :  " & e.X & " ......O Index da figurinha é :  " & MyIndexII) 'CInt(Int(e.X / 132))
        'ASSIM DESTA FORMA SIMPLES obtem-se o indice 
        MyIndexII = Array.IndexOf(BonecoLabel, Sender)
        'SALVAR o bitmap numa  variável ..............
        If MyIndexII > 0 Then
            'ImgBonecoCurrente = CType(BonecoLabel(MyIndexII).Image.Clone, Bitmap)
            ' Miniaturas
            ImgBonecoCurrente = CType(BonecoLabel(MyIndexII).Image.GetThumbnailImage(64, 64, callback:=Nothing, callbackData:=IntPtr.Zero), Bitmap)
        End If

        If MyIndexII = 0 Then Call NovasFigurinhasPorInput()
    End Sub

    Private Sub NovasFigurinhasPorInput()
        On Error GoTo ErrorInput
        Dim Dial As New OpenFileDialog With {.FilterIndex = 1, .DefaultExt = "BitMap Files (*.bmp*)|*.bmp",
            .Filter = "BitMap Files (*.bmp*)|*.bmp|PNG Files (*.png*)|*.png|All files (*.*)|*.*", .ShowHelp = True,
            .AddExtension = True, .SupportMultiDottedExtensions = True, .Title = "New Image " & BonecoList.Count,
            .Multiselect = True, .Tag = TabSizeMode.Normal}
        Dim ResultDial As New DialogResult
        Dim FileName, MyPath, FullPath As String
        MyPath = Nothing ' Resetar variável
        Dim Respo As MsgBoxResult = MsgBox("Quer juntar mais figurinhas ?", MsgBoxStyle.YesNo, "Pode acrescentar fotos ou desenhos em formato de imagem !")
        If Respo = MsgBoxResult.Yes Then
            With Dial
                .CheckFileExists = True
                'Tentar evitar ficheiros não previstos ...não sei  se  funciona !
                If Not IsError(.Filter.OfType(Of Image)) Then
                    .GetType()
                    .FileName.FirstOrDefault
                    .DereferenceLinks = True
                    .CustomPlaces.FirstOrDefault
                    .ValidateNames = True
                    ResultDial = .ShowDialog()
                    .OpenFile()
                    MyPath = Dial.FileName

                Else
                    MsgBox("Ficheiro tipo errado...")
                End If

            End With
            If Not IsNothing(MyPath) Then
                If ResultDial = DialogResult.OK Then
                    FileName = Dial.SafeFileName
                    FullPath = MyPath '& "\" & FileName
                    BonecoCollection.Add(FullPath)
                    BonecoList.Add(Image.FromFile(FullPath))
                    ReDim BonecoLabel(BonecoList.Count - 1)
                    BonecoLabel(BonecoList.Count - 1) = New Label With {.Size = BonecoSize, .ImageAlign = ContentAlignment.MiddleCenter}
                    BonecoLabel(BonecoList.Count - 1).Image = BonecoList(BonecoList.Count - 1)
                    BonecoLabel(BonecoList.Count - 1).Update()
                    Call Redesenhar()
                    BonecoFlLayPanel.Refresh()
                    'MsgBox(BonecoList.Count)
                End If
            End If

        Else
            Exit Sub
        End If
        Exit Sub
ErrorInput:
        MsgBox("Erro nas Figurinhas :   " & Err.Description)
    End Sub

    Private Sub Redesenhar() Handles BonecoFlLayPanel.Validating

        BonecosCount = BonecoList.Count
        BonecoFlLayPanel.Contains(BonecoLabel(BonecosCount - 1))
        BonecoFlLayPanel.Controls.Clear()

        For i = 0 To BonecosCount - 1
            BonecoLabel(i) = New Label With {.Size = BonecoSize, .ImageAlign = ContentAlignment.MiddleCenter}
            With BonecoLabel(i)
                If i >= 0 Then
                    .Location = New Point(128 * (i - 1) + 5, 230)
                Else
                    .Location = New Point(+5, 230)
                End If
                .Size = BonecoSize
                .Tag = i
                .Image = CType(BonecoList(i).Clone, Image)
                .Name = BonecoCollection(i + 1).ToString
                .BackColor = Color.Transparent
                .BorderStyle = BorderStyle.Fixed3D

                .AutoEllipsis = False
                .Handle.Equals(BonecoLabel(i))

            End With

            BonecoFlLayPanel.Controls.Add(BonecoLabel(i))
            'Associar evento que  ocorre em run time e por iniciativa do USER
            AddHandler BonecoLabel(i).MouseDown, AddressOf BonecoFlLayPanel_MouseDown

        Next
    End Sub

#End Region

#Region "MenuStrip e Toolstrip  "

    Public Sub ImplementaçãoDeMenuStrip()
        On Error GoTo Erros
        'Private MeuMenuStrip As New MenuStrip() ' Declaração inicial - sem declaração prévia o menu não é  reconhecido
        'Private  ToolMenus As New ToolStrip()
        'Dim MeuMenuStrip As New MenuStrip With {.AllowMerge = True, .AutoSize = True}

        Dim ItemMenu0, ItemMenu1, ItemMenu2, ItemMenu3, ItemMenu4, ItemMenu5, ItemMenu6 As New ToolStripMenuItem ' With {.ForeColor = Color.Black, .BackColor = Color.Beige}
        ItemMenu1 = New ToolStripMenuItem("Arquivo", My.Resources._128nCSQuartiFusa.ToBitmap) ' , New EventHandler(AddressOf mnuItem1_Click)) ' Especificaçºao dos  itens e das subs
        ItemMenu2 = New ToolStripMenuItem("Editar", My.Resources._016bCSSemiColcheia.ToBitmap)
        ItemMenu3 = New ToolStripMenuItem("Mostrar", My.Resources._064_CSSemiFusa.ToBitmap)
        ItemMenu4 = New ToolStripMenuItem("Play", My.Resources._032_CSFusa.ToBitmap)
        ItemMenu5 = New ToolStripMenuItem("Andamento", My.Resources._016_CSSemiColcheia.ToBitmap)
        ItemMenu6 = New ToolStripMenuItem("CPU meter", My.Resources._000wSSSus.ToBitmap)
        'Adicionar controles ao form
        Me.MeuMenuStrip.Items.Add(ItemMenu1)
        Me.MeuMenuStrip.Items.Add(ItemMenu2)
        Me.MeuMenuStrip.Items.Add(ItemMenu3)
        Me.MeuMenuStrip.Items.Add(ItemMenu4)
        Me.MeuMenuStrip.Items.Add(ItemMenu5)
        Me.MeuMenuStrip.Items.Add(ItemMenu6)
        CType(ItemMenu1.DropDown, ToolStripDropDownMenu).ShowImageMargin = True
        CType(ItemMenu2.DropDown, ToolStripDropDownMenu).ShowImageMargin = True
        CType(ItemMenu3.DropDown, ToolStripDropDownMenu).ShowImageMargin = True
        CType(ItemMenu4.DropDown, ToolStripDropDownMenu).ShowImageMargin = False
        CType(ItemMenu5.DropDown, ToolStripDropDownMenu).ShowImageMargin = False
        CType(ItemMenu6.DropDown, ToolStripDropDownMenu).ShowImageMargin = False
        'SubItens
        Dim SubItemMenu1, SubItemMenu2, SubItemMenu3, SubItemMenu4, SubItemMenu5,
                      SubItemMenu6, SubItemMenu7, SubItemMenu8, SubItemMenu9, SubItemMenu10,
                      SubItemMenu11, SubItemMenu12, SubItemMenu13, SubItemMenu14, SubItemMenu15,
                      SubItemMenu16, SubItemMenu17, SubItemMenu18 As New ToolStripMenuItem '_
        'With {.ForeColor = Color.Black, .BackColor = Color.FloralWhite}
        SubItemMenu1 = New ToolStripMenuItem("Select ALL", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu1_Click))
        SubItemMenu2 = New ToolStripMenuItem("UNDO", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu2_Click))
        SubItemMenu3 = New ToolStripMenuItem("MostrarCódigo", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu3_Click))
        SubItemMenu4 = New ToolStripMenuItem("Notação Adicionada (Icons)", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu4_Click))
        SubItemMenu5 = New ToolStripMenuItem("Lento", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu5_Click))
        SubItemMenu6 = New ToolStripMenuItem("Copy", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu6_Click))
        SubItemMenu7 = New ToolStripMenuItem("REDO", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu7_Click))
        SubItemMenu8 = New ToolStripMenuItem("Matriz de consulta", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu8_Click))
        SubItemMenu9 = New ToolStripMenuItem("qq", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu9_Click))
        SubItemMenu10 = New ToolStripMenuItem("Intermédio", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu10_Click))
        SubItemMenu11 = New ToolStripMenuItem("Sair", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu11_Click))
        SubItemMenu12 = New ToolStripMenuItem("RESET", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu12_Click))
        SubItemMenu13 = New ToolStripMenuItem("Apresentação", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu13_Click))
        SubItemMenu14 = New ToolStripMenuItem("qq", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu14_Click))
        SubItemMenu15 = New ToolStripMenuItem("Rápido", My.Resources._000wSSBem.ToBitmap, New EventHandler(AddressOf SubItemMenu15_Click))
        SubItemMenu16 = New ToolStripMenuItem("Figurinhas", My.Resources.Boneco4, New EventHandler(AddressOf SubItemMenu16_Click))
        SubItemMenu17 = New ToolStripMenuItem("Iniciar", My.Resources._000wSSSus.ToBitmap, New EventHandler(AddressOf SubItemMenu17_Click))
        SubItemMenu18 = New ToolStripMenuItem("Parar", My.Resources._000wSSSus.ToBitmap, New EventHandler(AddressOf SubItemMenu18_Click))
        'Estabelecimento das  hierarquias
        ItemMenu1.DropDownItems.Add(SubItemMenu1) '----------------
        ItemMenu1.DropDownItems.Add(SubItemMenu6)
        ItemMenu1.DropDownItems.Add(SubItemMenu11)
        ItemMenu2.DropDownItems.Add(SubItemMenu2) '----------------
        ItemMenu2.DropDownItems.Add(SubItemMenu7)
        ItemMenu2.DropDownItems.Add(SubItemMenu12)
        ItemMenu3.DropDownItems.Add(SubItemMenu3) '----------------
        ItemMenu3.DropDownItems.Add(SubItemMenu8)
        ItemMenu3.DropDownItems.Add(SubItemMenu13)
        ItemMenu3.DropDownItems.Add(SubItemMenu16)
        ItemMenu4.DropDownItems.Add(SubItemMenu4) '----------------
        ItemMenu4.DropDownItems.Add(SubItemMenu9)
        ItemMenu4.DropDownItems.Add(SubItemMenu14)
        ItemMenu5.DropDownItems.Add(SubItemMenu5) '----------------
        ItemMenu5.DropDownItems.Add(SubItemMenu10)
        ItemMenu5.DropDownItems.Add(SubItemMenu15)
        ItemMenu6.DropDownItems.Add(SubItemMenu17)
        ItemMenu6.DropDownItems.Add(SubItemMenu18)
        Me.MainMenuStrip = MeuMenuStrip

        Me.Controls.Add(MainMenuStrip)

        Exit Sub
Erros:
        MsgBox("Erro detectado na sub ImplementaçãoDeMenuStrip :    " & ErrorToString())

    End Sub

    Private Sub SubItemMenu1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Seleccionar Tudo! ")
        If Visible = True Then CodeRichTextBox.SelectAll()
        If Visible = True Then PautaRichTextBox.SelectAll()
        If Visible = True Then DataShow.SelectAll()
    End Sub

    Private Sub SubItemMenu2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Vai Apagar a ultima Nota que colocou na pauta ...")
        ManualClearBtn_MouseClick(sender, e)
        NumItensAdicionados = NumItensAdicionados - 1
        MatNotasDragDrop.Last.Remove(NumItensAdicionados, 1)
        MatSomDragDrop.Last.Equals(0)
        MatPosDragDrop.Last.Equals(0)
    End Sub

    Private Sub SubItemMenu3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'MessageBox.Show("O código da App")
        MostrarCódigo = True
        Me.VerticalScroll.Value = 0
        BonecoFlLayPanel.Visible = False
        FlLayPanel2.Visible = True
        ApresentaçõesNaRichtextBox()

    End Sub

    Private Sub SubItemMenu4_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Vou tentar tocar os icons  que  adicionou manualmente  á pauta !...")
        'If Not IsNothing(DataShow) Then DataShow.Dispose() 'Libera o dataGrid
        Me.VerticalScroll.Value = 0
        PlayDragDrop()
        'MessageBox.Show("Se quizer ouvir  outra vez clique Retry ....")

    End Sub

    Private Sub SubItemMenu5_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Andamento Lento (Incremento de Variável  = 128")
        Andamento = 1
        Rapidez = 128
        Me.VerticalScroll.Value = 0
    End Sub

    Private Sub SubItemMenu6_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Copiar Àrea Selecionada para o Clipboard  ! ")
        If Visible = True Then CodeRichTextBox.Copy()
        If Visible = True Then PautaRichTextBox.Copy()
        If Visible = True Then DataShow.ClipboardCopyMode() = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
    End Sub

    Private Sub SubItemMenu7_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Refaz o que  apagou...")
        ManualRedrawBtn_MouseClick(sender, e)
        NumItensAdicionados = NumItensAdicionados + 1
        'MatNotasDragDrop.DefaultIfEmpty
        'MatPosYDragDrop.DefaultIfEmpty
        'MatPosXDragDrop.DefaultIfEmpty
    End Sub

    Private Sub SubItemMenu8_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'MessageBox.Show("Matriz de consulta")
        Me.VerticalScroll.Value = 0
        BonecoFlLayPanel.Visible = False
        FlLayPanel2.Visible = True
        DataGridSHOW() 'Auxiliar para visualização do motor disto tudo

    End Sub

    Private Sub SubItemMenu9_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Menu Item 1 Clicked")
        Me.VerticalScroll.Value = 0
    End Sub

    Private Sub SubItemMenu10_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Andamento normal (Incremento de Variável  = 256")
        Andamento = 2
        Rapidez = 256
        Me.VerticalScroll.Value = 0
    End Sub

    Private Sub SubItemMenu11_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Resp As DialogResult = MessageBox.Show("Deseja mesmo Sair ?...")
        If Resp = DialogResult.OK Then
            Me.Close()
            End
        Else
        End If
    End Sub

    Private Sub SubItemMenu12_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Apaga Tudo  ...Sem  Retorno  ...")
        ManualReset_MouseClick(sender, e)
        NumItensAdicionados = 0
        MatNotasDragDrop.DefaultIfEmpty
        MatSomDragDrop.DefaultIfEmpty
        MatPosDragDrop.DefaultIfEmpty
    End Sub

    Private Sub SubItemMenu13_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ApresentaçãoBoolean = True
        Me.VerticalScroll.Value = 0
        BonecoFlLayPanel.Visible = False
        FlLayPanel2.Visible = True
        ApresentaçõesNaRichtextBox()

    End Sub

    Private Sub SubItemMenu14_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Menu Item 3 Clicked")
        Me.VerticalScroll.Value = 0
    End Sub

    Private Sub SubItemMenu15_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        MessageBox.Show("Andamento Rápido (Incremento de Variável  = 512")
        Andamento = 4
        Rapidez = 512
        Me.VerticalScroll.Value = 0
    End Sub

    Private Sub SubItemMenu16_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        FlLayPanel2.Visible = False
        BonecoFlLayPanel.Visible = True
    End Sub

    Private Sub SubItemMenu17_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'Memória.TimerTim1(sender, e)
        Memória.Tim1.Enabled = True
        Memória.Tim1.Start()
    End Sub

    Private Sub SubItemMenu18_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Tim1.Stop()
    End Sub
#End Region

#Region "Medição do Tempo"
    'PARA O DRAG AND DROP<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    '          ******************************************************************************
    'Parece-me necessário colocar um numero inteiro (IN) de  dois(passa a três)  digitos (000)  no inicio do nome da nota a  efectuar o drag
    'Ex: 001#Semibreve,002nMinima,016bSemifusa
    'Este inteiro representa o factor a  dividir por 1 (a unidade  de  tempo de cada compasso) - (1\IN)
    'IN ´e o  Indice Nota  pré inscrito no name  da  mesma  
    'DN é a Duração Nota DN=1\IN
    'Como um compasso pode  ser binário,ternario etc e uma  semibreve  excede a  duração do  Compasso  binário por  ex
    'Assim a inscrição da nota no compasso em função do tempo em  segundos é DN=DC\IN  - DC-compasso 2\4 , 3\4,...
    'Se quizer-mos alterar o andamento tem de  se  alterar a duração do compasso  no  tempo ou  seja  em  DC
    'Um compasso  chegará  ao  fim  se  o  somatório das notas\acidentes  DN igualar DC   -  DN(1)+DN(2)+DN(3)+.....>=DC
    'DC = 1 seg (1000 ticks) ou o timer.interval    -   a=andamento escolhido em ticks
    'DCr= a*DC\1000  onde DCr é  a  duração real do compasso
    'O  excedente de uma  nota  transitará  para  o  compasso  seguinte  e será designada  por EDN
    'Portanto o Nome dos icons das notas e dos acidentes será _XXX(n,#,b,c,l,p,x,w,z)(CS,SS)Nome para normalizar a sua ID
    'Onde XXX = IN    -     n-significa nota normal sem acidentes   -   (CS,SS)- com e  sem som para diferenciar das pausas
    'o Traço _ é  necessário pois o compilador não aceita nomes dos icons com numeros no inicio da string
    'c =  compasso (introdução manual (por Drag Drop) ------l = ligações -------x = Claves  -----w= Acidentes ------ z = outros
    'Logo portanto tenho  de  redefinir todo o projecto................................... _XXX(n,#,b,c,l,p,x,w,z)(CS,SS)Nome
    'Começando pelo facto de ao escrever algo isso tenha de ser memorizado em uma matriz (para que depois se possa reproduzir facilmente)
    'Além dos dados já  referidos temos  ainda que determinar a  frequencia musical de cada  nota que pode  ser dada pelo 
    'número da tecla ou pelA LINHA DA PAUTA     , isto é pela coordenada y
    'Recordando a "fórmula" : PlayMusicalNote(CByte(Index), VolumeKey, Octave)
    'A implementação da duração de cada  nota 
    '1- Se conhecida  préviamente  ( ex : _001nCSSemibreve portanto situação de  drag&drop de icons)
    '----------------------------Threading.Thread.Sleep(Parametro)................Que não  é  mais  que  um  artificio
    '2- Se não é  conhecida  préviamente isto é se estiver  a  ser  tocada  por  teclas manualmente  (  situação  bem  mais  complicada)
    'ainda  me  parece  obscuro mas  deve  ter  a  ver com o  evento  down    ...   seguinte
    'NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, New System.IntPtr())
    'Portanto desconheço como dar a indicação da duração da nota para o PlayMusicalNote(CByte(Index), VolumeKey, Octave)
    'Mas isso é observável nitidamente com o acto de clicar mais ou menos  demoradamente

    'MatrizDasNotasAdicionadasManualmente é uma  matriz  de dados extraidos do nome das notas e do local do drop (na pauta)

    Private Sub MatrizDasNotasAdicionadasManualmente(ByVal MyCharName As String, ByVal NotaFinalNoDrop As Integer,
             ByVal Pos As Point, ByVal NumItensAdicionados As Integer, ByVal Index As Integer)
        On Error GoTo Erros

        If NumItensAdicionados > 0 Then ' Aumenta  a  dimensão da  matriz  conforme  necessário
            'Não  necessita do  preserve pois vai  conservando os  dados 
            'No  entanto isto não pode  ser  a  solução  final pelo  elevado  consumo  de  memória
            'Estes dados  tem  de  ser  escritos em  algum sitio fic Txt, datagrid ...
            'O  problema  é  que  são dados de diferentes  tipos....
            Array.Resize(Of String)(MatNotasDragDrop, NumItensAdicionados + 1)
            Array.Resize(Of Integer)(MatSomDragDrop, NumItensAdicionados + 1)
            Array.Resize(Of Point)(MatPosDragDrop, NumItensAdicionados + 1)
            Array.Resize(Of Integer)(MatIndexDragDrop, NumItensAdicionados + 1)
            'ReDim Preserve MatNotasDragDrop(NumItensAdicionados) ' = Array.CreateInstance(GetType(String), NumItensAdicionados)
            'ReDim Preserve MatPOsXDragDrop(NumItensAdicionados, 2)  'As Array = Array.CreateInstance(GetType(Integer), 1000, 2)
        End If

        If Mid(MyCharName, 6, 2) = "CS" Then ' CS significa simplesmete Com Som
            MatNotasDragDrop.SetValue(MyCharName, NumItensAdicionados)
            MatSomDragDrop.SetValue(NotaFinalNoDrop, NumItensAdicionados)
            MatPosDragDrop.SetValue(Pos, NumItensAdicionados)
            MatIndexDragDrop.SetValue(Index, NumItensAdicionados)
        End If
        If Mid(MyCharName, 5, 1) = "p" Then 'pausas
            MatNotasDragDrop.SetValue(MyCharName, NumItensAdicionados)
            ' MatSomDragDrop.SetValue(NotaFinalNoDrop, NumItensAdicionados)
            MatPosDragDrop.SetValue(Pos, NumItensAdicionados)
            MatIndexDragDrop.SetValue(Index, NumItensAdicionados)
        End If

        Exit Sub
Erros:
        MsgBox("Erro detectado na  sub MatrizDasNotasAdicionadasManualmente...." & ErrorToString())
    End Sub

    'Temporiza e toca cada nota  adicicionada manualmente pelo drag drop
    Private Sub TemporizaçãoDaNota(ByVal NotaFinalNoDrop As Integer, ByVal MyCharName As String)
        'Play  - nota : a duração de cada  nota  conseguiu-se por  meio  de  artificio
        'O Parametro é sugeito ao           Threading.Thread.Sleep(Parametro)
        'SE quizermos  incluir diferentes  andamentos  então será  andamento  X  parametro
        'A Temporização está contida e codificada na  string   MyCharName 
        UltimaNotaMusical = NotaFinalNoDrop
        If Mid(MyCharName, 6, 2) = "CS" Then ' CS significa simplesmete Com Som
            PlayMusicalNote(CByte(UltimaNotaMusical), VolumeKey, Octave)
            Dim DN As Integer = CInt(Val(Mid(MyCharName, 2, 3)))
            If IsNumeric(DN) And DN > 0 Then
                Dim Parametro As Integer = CInt(1000 * Andamento / DN)
                Threading.Thread.Sleep(Parametro)
                'Parar a nota musical
                OffMusicalNote(CByte(UltimaNotaMusical), Octave)
            End If
        Else
        End If
    End Sub

    'Temporiza as Pausas  adicicionadas manualmente pelo drag drop
    Private Sub TemporizaçãoDaPausa(ByVal NotaFinalNoDrop As Integer, ByVal MyCharName As String)
        'Play  - nota : a duração de cada  nota  conseguiu-se por  meio  de  artificio
        'O Parametro é sugeito ao           Threading.Thread.Sleep(Parametro)
        'SE quizermos  incluir diferentes  andamentos  então será  andamento  X  parametro
        'A Temporização está contida e codificada na  string   MyCharName 
        If Mid(MyCharName, 6, 2) = "SS" Then ' CS significa simplesmete Com Som
            UltimaNotaMusical = NotaFinalNoDrop
            'PlayMusicalNote(CByte(UltimaNotaMusical), VolumeKey, Octave)
            Dim DP As Integer = CInt(Val(Mid(MyCharName, 2, 3)))
            If IsNumeric(DP) And DP > 0 Then
                Dim Parametro As Integer = CInt(1000 * Andamento / DP)
                Threading.Thread.Sleep(Parametro)
                'Parar a nota musical
                'OffMusicalNote(CByte(UltimaNotaMusical), Octave)
            End If
        End If
    End Sub

    Private Sub PlayDragDrop()
        'IN ´e o  Indice Nota  pré inscrito no name  da  mesma  
        'DN é a Duração Nota DN=1\IN
        'Um compasso  chegará  ao  fim se  o  somatório das notas\acidentes  DN igualar DC   -  DN(1)+DN(2)+DN(3)+.....>=DC
        'DC = 1 seg (1000 ticks) ou o timer.interval    -   a=andamento escolhido em ticks
        'DCr= a*DC\1000  onde DCr é  a  duração real do compasso
        'Considerações iniciais
        '*************************************************
        'Play  - nota : a duração de cada  nota  conseguiu-se por  meio  de  artificio
        'O Parametro é sugeito ao           Threading.Thread.Sleep(Parametro)
        'SE quizermos  incluir diferentes  andamentos  então será  andamento  X  parametro
        'Visualizar a rich
        If FlLayPanel2.Visible = False Then FlLayPanel2.Visible = True
        If DataShow.Visible = True Then DataShow.Visible = False
        If CodeRichTextBox.Visible = True Then CodeRichTextBox.Visible = False
        If PautaRichTextBox.Visible = False Then PautaRichTextBox.Visible = True
        'Reconstruççao da  pauta Vazia - por  meio de bitmap e clipboard
        ReconstruçãoDaPautaVaziaParaRichText()
        'Declarações  locais
        Dim PlayClone As New Bitmap(PautaRichTextBox.Width, PautaRichTextBox.Height)
        Dim VolatilGraphics As Graphics = PautaRichTextBox.CreateGraphics()
        Dim PlayGraphics As Graphics = Graphics.FromImage(PlayClone) 'PautaRichTextBox.CreateGraphics

        'Construção do bitmap
        Me.VerticalScroll.Value = 0
        Dim RectPlayClone As New Rectangle(FlLayPanel2.Location, PautaRichTextBox.Size)
        PautaRichTextBox.DrawToBitmap(PlayClone, RectPlayClone)
        'Loop das Notas Gravadas
        For i As Integer = 0 To NumItensAdicionados
            'Declarações  locais Variáveis
            Dim PlayPt As New Point With {.X = MatPosDragDrop(i).X, .Y = MatPosDragDrop(i).Y}
            Dim ScreenPt As Point = PautaRichTextBox.PointToScreen(New Point(PlayPt.X, PlayPt.Y))
            'Mais uma  vez  o indice   do label para salvar o  dia
            Dim BitPlay As Bitmap = CType(CharLabel(MatIndexDragDrop(i)).Image, Bitmap)
            Dim DN As Integer = CInt(Val(Mid(MatNotasDragDrop(i), 2, 3))) ' Duração 
            UltimaNotaMusical = MatSomDragDrop(i)
            Dim MyCompositionNotes As String = MatNotasDragDrop(i)

            'REGISTO GRÀFICO.....................................................
            'Registo  em  pauta  novamente  -Prova dos nove ( apartir das matrizes unidimensionais)
            'Grafismo sobre  RichTextBox..................................
            'New bitmap com  as  mesmas dimensões da PautaPictureBox
            'Dim PlayClone As New Bitmap(PautaPictureBox.Width, PautaPictureBox.Height)
            With VolatilGraphics
                VolatilGraphics.DrawImage(BitPlay, PlayPt) ' Apenas no ecran - pode  eleminar-se  futuramente !!!
                Clipboard.SetImage(PlayClone)
            End With
            With PlayGraphics  ' manipula  o  bitmap
                Try
                    '.CopyFromScreen(ScreenPt, NewPt, BitPlay.Size)

                    ' PautaRichTextBox.DrawToBitmap(PlayClone, RectPlayClone)
                    PautaRichTextBox.Paste()
                    '.SetClip(VolatilGraphics)
                    '.Clip.GetRegionData()
                    ''PautaRichTextBox.AllowDrop = True
                    'PautaRichTextBox.Paste()
                    Application.DoEvents()
                    VolatilGraphics.Clip.Dispose()
                Catch ex As Exception
                Finally
                    If i = NumItensAdicionados Then
                        PlayGraphics.ResetClip()
                    End If
                End Try
            End With
            'SONORIZAÇÂOªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª
            'For i As Integer = 0 To NumItensAdicionados
            'Trabalhar o  som  e  a  duraçºao das  notas  e ou pausas
            If Mid(MyCompositionNotes, 6, 2) = "CS" Then ' CS significa simplesmete Com Som
                PlayMusicalNote(CByte(UltimaNotaMusical), VolumeKey, Octave)
                'Duraçaõ da  nota
                If IsNumeric(DN) And DN > 0 Then
                    Dim Parametro As Integer = CInt(1000 * Andamento / DN)
                    Threading.Thread.Sleep(Parametro)
                    OffMusicalNote(CByte(UltimaNotaMusical), Octave) 'Parar a nota musical

                End If
            ElseIf Mid(MyCompositionNotes, 6, 2) = "SS" Then
                'Duração da pausa
                If IsNumeric(DN) And DN > 0 Then
                    Dim Parametro As Integer = CInt(1000 * Andamento / DN)
                    Threading.Thread.Sleep(Parametro)
                End If
            End If

        Next

    End Sub

    'PARA AS TECLAS   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    '          ******************************************************************************TECLADO SUPERIOR
    'Aqui temos uma situação paricular em que o único factor que desconhecemos é a duração da nota 
    'Da mesma forma que  anteriormente paramos uma nota ao fim de um tempo denominado parametro 
    'Dim Parametro As Integer = CInt(1000 * Andamento / DN)
    '                Threading.Thread.Sleep(Parametro)
    'Neste caso o que queremos conhecer é DN ou a duração da  nota
    'Este Parametro é-nos  dado pelo TickCounts=TickCounts + 1 dentro do timer
    'Como 128 tcks representa uma  quartifusa ( a nota mais rápida ) todos os  multiplos de 128 representam as restantes notas
    'Até chegarmos á  semibreve 1024 = 128 * 8
    'A Formula usada para o reconhecimento do´código pré inscrito no nome dos icons , que representam as semifusas e etc é :
    '*************************************************************************************************************************
    'Determinação da codificação do icon pela  Duração da Nota
    'For n = 1 To 8
    '    Dim FusaFactor As Integer = CInt(2 ^ (n - 1)) ' fórmula para obter a designação associada  á nota 
    '    If Math.Abs(DuraçãoDaNota - n * Quartifusa) < Precisão Then
    '        CodificaçãoIcon = CInt(Quartifusa / FusaFactor) ' obtenção final da designaçao associada  á nota
    '        Exit For
    '    End If
    'Next n
    '' Ciclo sobre a coleção dos icons válidos para colocação em pauta
    'For j = 0 To IconsTeclasDim ' Dimensão da matriz 
    '    If CInt(Val(Mid(IconsTeclasCodeNames(j), 2, 3))) = CodificaçãoIcon And
    '        Mid(IconsTeclasCodeNames(j), 5, 3) = DesignaTeclas Then
    '        DesignaçãoDaNota = Mid(IconsTeclasCodeNames(j), 8)
    'etc.....
    '*************************************************************************************************************************
    'Portanto no primeiro loop for....Next  avalia-se com a Precisão que se queira um código o qual será usado no segundo loop
    'Para reconhecer qual o icon apropriado ou a notação musical mais próxima do que  se está a tocar pelo mouse. Ver Sub seguinte.........

    'Esta sub é uma das  mais importantes : nela atribui-se uma representação musical do que se vai tocando em tempo de execussão
    Private Sub PesquisarNota(ByVal DuraçãoDaNota As Integer)
        'On Error GoTo DuraçãoDaNotaFunctionError
        Dim DesignaçãoDaNota As String = ""
        Indíce = 0 ' manipula uma colecção .......... Colecções não têm indice ZERO
        'Dim Precisão As Integer = 8  (16)  32 mais rápido' Deve ser  declarada no inicio e associada  ao andamento
        Dim Quartifusa As Integer = 128 ' unidade mais pequena 
        Try
            Dim IconsTeclasDim As Integer = IconsTeclasCodeNames.Count - 1 'Determinar a dimensão 
            If DuraçãoDaNota > 0 And DuraçãoDaNota < (16384 + Precisão) Then 'Limitar á semibreve que vale 16384 ticks
                'Determinação da codificação do icon pela  Duração da Nota
                For n = 1 To 8 Step 1
                    Dim TimeFactor As Integer = CInt(2 ^ (n - 1)) ' fórmula para obter um factor associado á nota musical (icon)
                    Dim NotaçãoIdeal As Integer = TimeFactor * Quartifusa
                    DesvioTemporal = CDec((Math.Abs(DuraçãoDaNota / NotaçãoIdeal)))
                    'Nota neste caso existe dois  valores para a precisão um inferior (1/Precisão) e o superior (Precisão)
                    Dim Precisão As Decimal = CDec(1.5)
                    Dim LimiteInFerior As Decimal = Math.Round(CDec(1 / Precisão), 2)
                    If DesvioTemporal > LimiteInFerior And DesvioTemporal < Precisão Then
                        'Se estiver dentro dos limites 
                        CodificaçãoIcon = CInt(Quartifusa / TimeFactor) ' obtenção final da designaçao associada  á nota mais próxima
                        Exit For ' Ao  encontrar a primeira nestas limitações deve  sair
                    End If
                Next n
                ' Ciclo sobre a coleção dos icons válidos para colocação em pauta
                For j = 0 To IconsTeclasDim ' Dimensão da matriz 
                    If CInt(Val(Mid(IconsTeclasCodeNames(j), 2, 3))) = CodificaçãoIcon And
                        Mid(IconsTeclasCodeNames(j), 5, 3) = DesignaTeclas Then
                        DesignaçãoDaNota = Mid(IconsTeclasCodeNames(j), 8)
                        Indíce = j + 1
                        Marcar = True
                        Exit For
                    End If
                Next j
            ElseIf DuraçãoDaNota >= (16384) Then ' se  duração exceder a semibreve 
                CodificaçãoIcon = 1
                For i = 0 To IconsTeclasDim ' Dimensão da matriz 
                    If CInt(Val(Mid(IconsTeclasCodeNames(i), 2, 3))) = CodificaçãoIcon And
                        Mid(IconsTeclasCodeNames(i), 5, 3) = DesignaTeclas Then
                        DesignaçãoDaNota = Mid(IconsTeclasCodeNames(i), 8)
                        Indíce = i + 1
                        Marcar = True
                        Exit For
                    End If
                Next i
            ElseIf DuraçãoDaNota = 0 Then ' Caso particular da  quartifusa
                CodificaçãoIcon = 128
                For i = 0 To IconsTeclasDim ' Dimensão da matriz 
                    If CInt(Val(Mid(IconsTeclasCodeNames(i), 2, 3))) = CodificaçãoIcon And
                        Mid(IconsTeclasCodeNames(i), 5, 3) = DesignaTeclas Then
                        DesignaçãoDaNota = Mid(IconsTeclasCodeNames(i), 8)
                        Indíce = i + 1
                        Marcar = True
                        Exit For
                    End If
                Next i
            ElseIf DuraçãoDaNota < 0 Then
                'Exit Sub  ' por  precaução
            End If

        Catch Ex As Exception
            MsgBox(Ex.ToString)
        Finally
            If Not DesignaçãoDaNota = "" And Indíce > 0 And Indíce <= IconsTeclasCollection.Count Then
                'Pode prosseguir
                If Not Marcar = True Then Marcar = True 'Se a nota for encontrada marcar como válida
            Else
                'A nota não foi reconhecida : foi audivel mas não será trancrita para a pauta
                Marcar = False
            End If

        End Try
        '        Exit Sub
        'DuraçãoDaNotaFunctionError:
        '        MsgBox("Duração Da Nota Function Error :  " & ErrorToString())
    End Sub

    'MatrizDoQueSeVaiTocando é uma  matriz  de dados extraidos do que se tocar coma as teclas ou o mouse
    Private Sub MatrizDoQueSeVaiTocando()

    End Sub

#End Region

#Region "DataGridSHOW Visualização do  Motor Principal de consulta"
    Private Sub DataGridSHOW()
        On Error GoTo Erros

        If PautaRichTextBox.Visible = True Then PautaRichTextBox.Visible = False
        If CodeRichTextBox.Visible = True Then CodeRichTextBox.Visible = False
        'FlLayPanel2  foi  declarado invisivel e é  necessário  recolocá-lo  tb
        If FlLayPanel2.Visible = False Then FlLayPanel2.Visible = True
        BonecoFlLayPanel.Visible = False
        If DataShow.Visible = False Then DataShow.Visible = True
        ''Talvez  ainda  seja  declarado no Load
        ''Dim DataShow As New DataGridView
        'FlLayPanel2.Contains(DataShow)
        'With DataShow
        '    .BorderStyle = BorderStyle.FixedSingle
        '    .Size = CType(New Point(10000, 200), Drawing.Size)
        '    .Location = New Point(5, MainMenuStrip.Height)
        '    .ForeColor = Color.Black
        '    '.BackColor = Color.Aquamarine
        '    .Rows.Clear()
        '    'Create an unbound DataGridView by declaring a column count.
        '    .ColumnCount = MemóriaPauta.ColumnCount
        '    ' Set the column head style.
        '    .ColumnHeadersVisible = True
        '    Dim columnHeaderStyle As New DataGridViewCellStyle()
        '    columnHeaderStyle.BackColor = Color.Beige
        '    columnHeaderStyle.Font = New Font("Verdana", 8, FontStyle.Bold)
        '    .ColumnHeadersDefaultCellStyle = columnHeaderStyle
        '    .Visible = False
        'End With
        'FlLayPanel2.Controls.Add(DataShow)
        'Prenchimento das colunas da  grid
        For i = 0 To MemóriaPauta.ColumnCount - 1 ' OrdemDasNotasComSustenidos.Length - 1
            'Nomes  das  colunas - columnHeaders
            DataShow.Columns(i).Name = MemóriaPauta.Columns(i).Name 'OrdemDasNotasComSustenidos(i)
        Next
        With DataShow ' Datagrid de consulta no fundo  do  formulário

            For i = 0 To MemóriaPauta.ColumnCount - 1
                For j = 0 To MemóriaPauta.Rows.Count - 1
                    .Rows.Add()
                    .Rows(j).Cells.Item(i).Value = MemóriaPauta.Rows(j).Cells.Item(i).Value ' Datagrid Escondido
                Next j
            Next
        End With

        Exit Sub
Erros:
        MsgBox("Detectado Erro na Sub DataGridSHOW :  " & ErrorToString())
    End Sub

#End Region

#Region "Tentativa de gravar at runtime o meu código -  não  conseguido"
    'Seria  util para não  se  perder  acidentalmente......... 
    Public Sub ApresentaçõesNaRichtextBox()

        'Portanto  para  já  o  c+odigo  é  previamente  gravado numa richtext com o  ofice por  exemplo
        'E colocado na paSTA  RESSOURCES  e  daí tem-se  acesso  fácil
        'Esconder o  que  está no mesmo lugar da  rich
        If FlLayPanel2.Visible = False Then FlLayPanel2.Visible = True
        BonecoFlLayPanel.Visible = False
        If DataShow.Visible = True Then DataShow.Visible = False
        If PautaRichTextBox.Visible = True Then PautaRichTextBox.Visible = False
        'Visualizar a rich
        If CodeRichTextBox.Visible = False Then CodeRichTextBox.Visible = True

        If ApresentaçãoBoolean = True Then
            'CodeRichTextBox.SelectionIndent = 15
            CodeRichTextBox.Rtf = My.Resources.Apresentacao
            'CodeRichTextBox.Rtf = My.Resources.BitMapPauta.ToString
            ApresentaçãoBoolean = False

        ElseIf MostrarCódigo = True Then
            'CodeRichTextBox.SelectionIndent = 15
            CodeRichTextBox.Text = My.Resources.SongWriterCodigoV1023
            MostrarCódigo = False
        Else

        End If

        'AcessarLinhasDeCódigo()

    End Sub

#End Region

#Region "Tooltips and languages"
    Dim ttip, ttip2, ttip3, ttip4, ttip5, ttip6, ttip7, ttip8, ttip9, ttip10, ttip11,
        ttip12, ttip13, ttip14, ttip15, ttip16, ttip17 As New ToolTip

    Sub LoadTooltips()
        'As  traduções  ficam  para  depois............................ 
        On Error GoTo Erros
        '*****'Tooltips****************************************************************
        'NOTA  :  AQUI  trata-se  apenas  de  declarar  as  tooltips
        'Nas  subs  respectivas e colocar as tooltips  antes  de  adicionar o control senão  não  funcionam
        'EX:  ttip12.SetToolTip(GoOnSup, "Retomar Notas Apagadas - Piano Sup")
        '             Me.Controls.Add(GoOnSup)
        'Show a tooltip message
        ttip.AutoPopDelay = 2000
        ttip.InitialDelay = 1000
        ttip.ReshowDelay = 500
        For I As Integer = 1 To 5
            ttip.SetToolTip(Me.lblOctave(I), "Octavas")
        Next
        For I As Integer = 1 To 11
            ttip2.SetToolTip(Me.lblChords(I), "Acordes ...Teclado Inferior")
        Next
        ttip3.SetToolTip(ChordsComboBoxInstruments, "Instrumentos Para ...Teclado Inferior")
        'Another tooltip
        'ttip4.SetToolTip(FlLayPanel, "Instruments for - TOP piano")
        ttip5.SetToolTip(ButtonSwitch2, "Keys plays - TOP piano ")
        ttip6.SetToolTip(ButtonSwitch1, "Keys plays - Under piano ")
        ttip7.SetToolTip(SoloComboBoxInstruments, "Instrumentos  Para ...Teclado Superior")
        ttip8.SetToolTip(TextInput, "Input some correction for value of Y")
        ttip9.SetToolTip(TextInput, "Input some correction for Pianos ")
        ttip10.SetToolTip(SusOrBemois, "Choose Sustenidos for your music ")
        ttip11.SetToolTip(BemoisOrSus, "Choose Bemóis for your music ")
        'Buttons Apagar pauta
        ttip12.SetToolTip(GoOnSup, "Retomar Notas Apagadas - Pauta Sup")
        ttip13.SetToolTip(GoBackSup, "Apagar Notas  - Pauta Sup")
        ttip14.SetToolTip(GoOnInf, "Retomar Notas Apagadas - Pauta Inf")
        ttip15.SetToolTip(GoBackInf, "Apagar Notas  - Pauta Inf")
        ttip16.SetToolTip(ManualClearBtn, "Apagar Icons ")
        ttip17.SetToolTip(ManualRedrawBtn, "Reeditar Icons  ")
        Exit Sub
Erros:
        MsgBox("Erro detectado NameOf Sub LoadTooltips ...." & ErrorToString())
    End Sub
#End Region

#Region "Choose modality # or bemol"
    Private Sub SusOrBemois_Click(ByVal sender As Object, ByVal e As MouseEventArgs) Handles SusOrBemois.MouseClick
        If SusOrBemois.Visible = True Then
            ttip10.SetToolTip(SusOrBemois, "Choose Sustenidos for your music ")
            SusOrBemois.Text = "#" : SusOrBemois.BackColor = Color.Red
            Acidentes = "Sustenidos"
            BemoisOrSus.BackColor = Color.Azure
            MsgBox("Escolheu a Modalidade de " & Acidentes)
        End If

    End Sub
    Private Sub BemoisOrSus_Click(ByVal sender As Object, ByVal e As MouseEventArgs) Handles BemoisOrSus.MouseClick
        If BemoisOrSus.Visible = True Then
            ttip11.SetToolTip(BemoisOrSus, "Choose Bemóis for your music ")
            BemoisOrSus.Text = "b" : BemoisOrSus.BackColor = Color.Red
            Acidentes = "Bemóis"
            SusOrBemois.BackColor = Color.Azure
            MsgBox("Escolheu a Modalidade de " & Acidentes)
        End If
    End Sub
#End Region

#Region "Swicth Button"

    Sub CreateButtonsSwicht()
        'Para permutar de piano e de input de teclado keyboard
        Dim LabelInfo As New Label
        With LabelInfo
            .Text = "Computor KeyBoard Play Options"
            .Font = New Font("Arial", 8, FontStyle.Italic)
            '.Size = CType(New Point(150, 15), Drawing.Size)
            .Location = New Point(265, 580)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
            .TextAlign = ContentAlignment.MiddleCenter
            .AutoSize = True
        End With
        With ButtonSwitch1
            .Text = "Chords"
            .Font = New Font("Arial", 8, FontStyle.Regular)
            .Size = CType(New Point(50, 20), Drawing.Size)
            .Location = New Point(360, 560)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
            .TextAlign = ContentAlignment.MiddleCenter
            AddHandler .MouseDown, AddressOf ButtonSwitch1_MouseDown
            ' AddHandler .MouseEnter, AddressOf ButtonSwitch1_MouseEnter
            ' AddHandler .MouseLeave, AddressOf ButtonSwitch1_MouseLeave
        End With
        With ButtonSwitch2
            .Text = "Solo"
            .Font = New Font("Arial", 8, FontStyle.Regular)
            .Size = CType(New Point(50, 20), Drawing.Size)
            .Location = New Point(300, 560)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
            .TextAlign = ContentAlignment.MiddleCenter
            AddHandler .MouseDown, AddressOf ButtonSwitch2_MouseDown
            'AddHandler .MouseEnter, AddressOf ButtonSwitch2_MouseEnter
            'AddHandler .MouseLeave, AddressOf ButtonSwitch2_MouseLeave
        End With
        Me.Controls.Add(ButtonSwitch1)
        Me.Controls.Add(ButtonSwitch2)
        Me.Controls.Add(LabelInfo)
    End Sub
    Private Sub ButtonSwitch1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        ButtonSwitch2.BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
        ButtonSwitch1.BackColor = System.Drawing.Color.FromArgb(255, 20, 20)
        ModeKeysDown = "Chords"
        Note = Nothing
    End Sub
    Private Sub ButtonSwitch2_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        ButtonSwitch1.BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
        ButtonSwitch2.BackColor = System.Drawing.Color.FromArgb(255, 20, 20)
        ModeKeysDown = "Solo"
        NoteChords = Nothing
    End Sub

#End Region

#Region "Octave Buttons"
    Sub CreateOctaveButtons()
        Dim pOct As New Point(60, 565)
        Dim inc As Integer = 0
        For i = 1 To 5
            lblOctave(i) = New Label
            With lblOctave(i)
                .Text = CStr(i)
                .Font = New Font("Arial", 10, FontStyle.Bold)
                .Size = CType(New Point(20, 20), Drawing.Size)
                .BorderStyle = BorderStyle.FixedSingle
                .Location = New Point(pOct.X + inc, pOct.Y)
                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
                .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
                .TextAlign = ContentAlignment.MiddleCenter
                AddHandler .MouseDown, AddressOf lblOctave_MouseDown
                AddHandler .MouseEnter, AddressOf lblOctave_MouseEnter
                AddHandler .MouseLeave, AddressOf lblOctave_MouseLeave
            End With
            inc = inc + 19
            Me.Controls.Add(lblOctave(i))
        Next

        lblOctave(1).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
        lblOctave(1).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)

    End Sub
    Private Sub lblOctave_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
        For I As Integer = 1 To 5
            lblOctave(I).BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
            lblOctave(I).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
        Next
        lblOctave(Index).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
        lblOctave(Index).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)

        Octave = CByte(Index)
    End Sub
    Private Sub lblOctave_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
        Cursor = Cursors.Hand
    End Sub
    Private Sub lblOctave_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
        Cursor = Cursors.Default
    End Sub
#End Region

#Region "Chords Buttons"

    Sub CreateChordsButtons()
        Dim pOct As New Point(30, 800)
        Dim inc As Integer = 0
        For i = 1 To 12
            lblChords(i) = New Label
            With lblChords(i)
                .Text = NamedChords(i - 1)
                .Font = New Font("Arial", 8, FontStyle.Bold)
                .Size = CType(New Point(60, 30), Drawing.Size)
                .BorderStyle = BorderStyle.FixedSingle
                .Location = New Point(pOct.X + .Size.Width * (i - 1), pOct.Y) '(pOct.X + inc, pOct.Y)
                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
                .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
                .TextAlign = ContentAlignment.MiddleCenter

                AddHandler .MouseDown, AddressOf lblChords_MouseDown
                AddHandler .MouseEnter, AddressOf lblChords_MouseEnter
                AddHandler .MouseLeave, AddressOf lblChords_MouseLeave
            End With
            'inc = inc + 19
            Me.Controls.Add(lblChords(i))
        Next

        lblChords(1).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
        lblChords(1).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
        lblChords(12).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
        lblChords(12).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
        lblChords(12).Size = CType(New Point(100, 30), Drawing.Size)
    End Sub
    Private Sub lblChords_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim IndexChords As Integer = Array.IndexOf(lblChords, sender)
        'Dim ChordsName As New String
        For I As Integer = 1 To 11
            lblChords(I).BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
            lblChords(I).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
        Next
        lblChords(IndexChords).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
        lblChords(IndexChords).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
        ChordsName = lblChords(IndexChords).Text
        If ChordsName <> "" And ChordsName <> "Chors =0" Then
            VerifyChordsExist = True
        Else
            VerifyChordsExist = False
        End If

    End Sub
    Private Sub lblChords_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim IndexChords As Integer = Array.IndexOf(lblChords, sender)
        Cursor = Cursors.Hand
    End Sub
    Private Sub lblChords_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim IndexChords As Integer = Array.IndexOf(lblChords, sender)
        Cursor = Cursors.Default
    End Sub

#End Region

#Region "Memória escrita das notas e da sua posição em pauta - numa grid (Motor desta  App)"

    Public Sub ConstruindoMemóriaPautaComSustenidos()

        On Error GoTo Erros

        'A  solução foi prédeterminar o numero de colunas e declara-lo no inicio 

        For i = 0 To ColCount - 1
            'Nomes  das  colunas - columnHeaders
            MemóriaPauta.Columns(i).Name = OrdemDasNotasComSustenidos(i)
        Next

        'Notas explicativas :

        'Determinação da posição das notas na pauta
        'De notar que apenas temos 15 linhas por cada piano para a notação musical
        'Isto significa que , com os  espaços entre linhas , teremos lugar para 30 notas sensivelmente
        'Como apenas interessam as notas naturais (7) teremos aproximadamente 
        'Ap.  4  oitavas (28)
        'Escolhemos as oitavas centrais mais usadas - a 2ª  a 3ª  a 4ª  e a 5ª
        'Para as  outras terá  de  haver um simblo (inscrito NA PAUTA ) significando que esta ou aquela nota
        'pertencem a oitavas distintas por  ex   1ª oitava  etc
        'Nota  :   A VARIÁVEL  PRINCIPAL  DIZ  RESPEITO AO EIXO DOS YYY
        'PORQUE  A OUTRA  VARIÁVEL  NO  EIXO DOS  xxx  SERÁ  INPUT DA  ENTRADA  DE  DADOS 
        'Então a primeira nota que  atribuiremos será o Lá(1) na posição ----sem posição começa em dó 

        'Set Rows                                    

        Dim StrYYYPianoSuperior(ColCount - 1) As String ' Esta string matriz vai transportar so valores - PosY
        Dim StrYYYPianoInferior(ColCount - 1) As String ' Esta string matriz vai transportar so valores - PosY

        Dim ELI As Integer = CInt(AlturaDaPauta / 30) 'EspaçamentoLinhas
        Dim UmTerço As Integer = CInt(AlturaDaPauta / 3) 'Area de sobreposição
        Dim DoisTerços As Integer = CInt(2 * AlturaDaPauta / 3 - 2 * ELI) 'Area de sobreposição 
        'com correcção de inicio  (- 2 * ELI)
        Dim AltPauta As Integer = AlturaDaPauta + (1 * ELI \ 2) ' Ajuste inicial Teclado Inferior
        ' Correcção inicial : +(1 * ELI \ 2) - O  sinal (+) obriga  a  descer na  pauta
        Dim CoordenadasYTotais(ColCount - 1) As Short
        Dim PSup As String = Nothing : Dim PInf As String = Nothing

        For c = 1 To ColCount - 1
            'Teclado Superior  
            Dim OitavaAnterior As Integer
            Dim ParamY As Short
            Dim DeltaY As Short = CShort(ELI / 2 * (ParamY - 1))
            Dim DetectaOitava As String = Mid(OrdemDasNotasComSustenidos(c), 4, 1)
            If Mid(OrdemDasNotasComSustenidos(c), 1, 1) = "#" Then
                DetectaOitava = Mid(OrdemDasNotasComSustenidos(c), 5, 1)
            End If
            'Caso Particular do sol
            If Mid(OrdemDasNotasComSustenidos(c), 1, 3) = "SOL" Then
                DetectaOitava = Mid(OrdemDasNotasComSustenidos(c), 5, 1)
            End If
            If Mid(OrdemDasNotasComSustenidos(c), 1, 4) = "#SOL" Then
                DetectaOitava = Mid(OrdemDasNotasComSustenidos(c), 6, 1)
            End If
            If IsNumeric(CInt(Val(DetectaOitava))) Then
                Dim Oit As Integer = CInt(Val(DetectaOitava))
                OitavaAnterior = Oit - 1
            End If
            'Inicio dos  IFFFFFFs 
            If c = CInt(1 + 12 * OitavaAnterior) Or c = CInt(2 + 12 * OitavaAnterior) Then
                ParamY = CShort(1 + 7 * OitavaAnterior) 'Dó  e  #Dó
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(3 + 12 * OitavaAnterior) Or c = CInt(4 + 12 * OitavaAnterior) Then
                ParamY = CShort(2 + 7 * OitavaAnterior) ''Ré e " Ré
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(5 + 12 * OitavaAnterior) Then
                ParamY = CShort(3 + 7 * OitavaAnterior) 'Mi
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(6 + 12 * OitavaAnterior) Or c = CInt(7 + 12 * OitavaAnterior) Then
                ParamY = CShort(4 + 7 * OitavaAnterior) 'Fá e #Fá
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(8 + 12 * OitavaAnterior) Or c = CInt(9 + 12 * OitavaAnterior) Then
                ParamY = CShort(5 + 7 * OitavaAnterior) 'Sol e #Sol
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(10 + 12 * OitavaAnterior) Or c = CInt(11 + 12 * OitavaAnterior) Then
                ParamY = CShort(6 + 7 * OitavaAnterior) 'Lá e #Lá
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(12 + 12 * OitavaAnterior) Then
                ParamY = CShort(7 + 7 * OitavaAnterior) 'Si
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If

            If CoordenadasYTotais(c) < 0 Or CoordenadasYTotais(c) > DoisTerços Then
                CoordenadasYTotais(c) = -5 'Invisivel
            End If
            StrYYYPianoSuperior(c) = CType(CoordenadasYTotais(c), String)
            StrYYYPianoSuperior(0) = "Piano Superior-#Y" 'Nome do ROW
            PSup = PSup & CoordenadasYTotais(c) & ","

        Next

        For c = 1 To ColCount - 1
            'Teclado Inferior
            '
            Dim OitavaAnterior As Integer
            Dim ParamY As Short
            Dim DeltaY As Short = CShort(ELI / 2 * (ParamY - 1))
            Dim DetectaOitava As String = Mid(OrdemDasNotasComSustenidos(c), 4, 1)
            If Mid(OrdemDasNotasComSustenidos(c), 1, 1) = "#" Then
                DetectaOitava = Mid(OrdemDasNotasComSustenidos(c), 5, 1)
            End If
            'Caso Particular do sol
            If Mid(OrdemDasNotasComSustenidos(c), 1, 3) = "SOL" Then
                DetectaOitava = Mid(OrdemDasNotasComSustenidos(c), 5, 1)
            End If
            If Mid(OrdemDasNotasComSustenidos(c), 1, 4) = "#SOL" Then
                DetectaOitava = Mid(OrdemDasNotasComSustenidos(c), 6, 1)
            End If
            If IsNumeric(CInt(Val(DetectaOitava))) Then
                Dim Oit As Integer = CInt(Val(DetectaOitava))
                OitavaAnterior = Oit - 1
            End If

            'Inicio dos  IFFFFFFs 
            If c = CInt(1 + 12 * OitavaAnterior) Or c = CInt(2 + 12 * OitavaAnterior) Then
                ParamY = CShort(1 + 7 * OitavaAnterior) 'Dó  e  #Dó
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(3 + 12 * OitavaAnterior) Or c = CInt(4 + 12 * OitavaAnterior) Then
                ParamY = CShort(2 + 7 * OitavaAnterior) ''Ré e " Ré
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(5 + 12 * OitavaAnterior) Then
                ParamY = CShort(3 + 7 * OitavaAnterior) 'Mi
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(6 + 12 * OitavaAnterior) Or c = CInt(7 + 12 * OitavaAnterior) Then
                ParamY = CShort(4 + 7 * OitavaAnterior) 'Fá e #Fá
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(8 + 12 * OitavaAnterior) Or c = CInt(9 + 12 * OitavaAnterior) Then
                ParamY = CShort(5 + 7 * OitavaAnterior) 'Sol e #Sol
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(10 + 12 * OitavaAnterior) Or c = CInt(11 + 12 * OitavaAnterior) Then
                ParamY = CShort(6 + 7 * OitavaAnterior) 'Lá e #Lá
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(12 + 12 * OitavaAnterior) Then
                ParamY = CShort(7 + 7 * OitavaAnterior) 'Si
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If

            If CoordenadasYTotais(c) < UmTerço Or CoordenadasYTotais(c) > AlturaDaPauta Then
                CoordenadasYTotais(c) = CShort(AltPauta + 5) 'Invisivel
            End If
            StrYYYPianoInferior(c) = CType(CoordenadasYTotais(c), String)
            StrYYYPianoInferior(0) = "Piano Inferior-#Y" 'Nome do ROW
            PInf = PInf & CoordenadasYTotais(c) & ","

        Next

        PSup = StrYYYPianoSuperior(0) & "," & PSup
        PInf = StrYYYPianoInferior(0) & "," & PInf

        'MsgBox(InfoText.Text)

        '

        With MemóriaPauta
            .Rows.Add() ' Primeira  linha contendo a numeração das notas
            For i = 0 To ColCount - 1
                .Rows(0).Cells.Item(i).Value = i
                'Esta primeira linha vai  fazer a correspondencia entre a designação da nota e 
                'a numeração das teclas
            Next
            .Rows(0).Cells.Item(0).Value = "Enumeração"
            .AutoSize = True
            Dim RowHeaderStyle As New DataGridViewCellStyle With {
                .BackColor = Color.Beige,
                .Font = New Font("Verdana", 8, FontStyle.Bold)
            }
            .RowHeadersDefaultCellStyle = RowHeaderStyle
            .RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Sunken
            .Rows.Add(StrYYYPianoSuperior)  ' Pode usar-se apenas as linhas em vez da matriz
            '            '.Rows.Add("Piano Superior", 180, 180, 175, 175, 170, 165, 165, 160, 160, 155, 155, 150, 145, 145, 140, 140,
            '                      135, 130, 130, 125, 125, 120, 120, 115, 110, 110, 105, 105, 100, 95, 95, 90, 90, 85, 85, 80, 75,
            '                      75, 70, 70, 65, 60, 60, 55, 55, 50, 50, 45, 40, 40, 35, 35, 30, 25, 25, 20, 20, 15, 15, 10, 5, 5,
            '                      0, 0, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
            '                      -5, -5, -5, -5, -5, -5, -5, -5, -5)
            .Rows.Add(StrYYYPianoInferior)   ' Pode usar-se apenas as linhas em vez da matriz
            '.Rows.Add("Piano Inferior", 310, 310, 300, 300, 295, 290, 290, 285, 285, 280, 280, 275, 270, 270, 265, 265,
            '          260, 255, 255, 250, 250, 245, 245, 240, 235, 235, 230, 230, 225, 220, 220, 215, 215, 210, 210,
            '          205, 200, 200, 195, 195, 190, 185, 185, 180, 180, 175, 175, 170, 165, 165, 160, 160, 155, 150,
            '          150, 145, 145, 140, 140, 135, 130, 130, 125, 125, 120, 115, 115, 110, 110, 105, 105, 100, 310,
            '          310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
            '          310, 310, 310, 310)

            'If .ShowRowErrors = True Then MsgBox("Erro no preenchimento da Grid   " & ErrorToString())
        End With

        ' MemóriaPautaPanel.Controls.Add(MemóriaPauta)

        Exit Sub
Erros:
        MsgBox("Detectado Erro na Sub  ConstruindoMemóriaPautaComSustenidos:  " & ErrorToString())
    End Sub

    Public Sub AdicionandoLinhasMemóriaPautaComBemóis()
        'On Error Resume Next
        On Error GoTo Erros

        'O Data grid já  está  feito por  esta  altura pelo que se  trata de apenas adicionar uma linha
        'A String OrdemDasNotasComBemóis declarada no inicio foi prenchida manualmente a partir da sub anterior
        'e da  variável PianoStrBemóis  com um ponto  de  interrupção no RUN  da  app

        'Set New Row With names of Bemóis
        MemóriaPauta.Rows.Add()
        MemóriaPauta.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Raised
        For i = 0 To ColCount - 1
            'Preenchimento do row com as designações das notas correspondentes aos sustenidos mas em bemóis
            MemóriaPauta.Item(i, 3).Value = OrdemDasNotasComBemóis(i)

        Next

        'Determinação da posição das notas na pauta
        'De notar que apenas temos 15 linhas por cada piano para a notação musical
        'Isto significa que , com os  espaços entre linhas , teremos lugar para 30 notas sensivelmente
        'Como apenas interessam as notas naturais (7) teremos aproximadamente 
        'Ap.  4  oitavas (28)
        'Escolhemos as oitavas centrais mais usadas - a 2ª  a 3ª  a 4ª  e a 5ª
        'Para as  outras terá  de  haver um simblo (inscrito NA PAUTA ) significando que esta ou aquela nota
        'pertencem a oitavas distintas por  ex   1ª oitava  etc
        'Nota  :   A VARIÁVEL  PRINCIPAL  DIZ  RESPEITO AO EIXO DOS YYY
        'PORQUE  A OUTRA  VARIÁVEL  NO  EIXO DOS  xxx  SERÁ  INPUT DA  ENTRADA  DE  DADOS 
        'Então a primeira nota que  atribuiremos será o Lá(1) na posição ----sem posição começa em dó 

        Dim StrYYYPianoSuperior(ColCount - 1) As String ' Esta string matriz vai transportar so valores - PosY
        Dim StrYYYPianoInferior(ColCount - 1) As String ' Esta string matriz vai transportar so valores - PosY

        Dim ELI As Integer = CInt(AlturaDaPauta / 30) 'EspaçamentoLinhas
        Dim UmTerço As Integer = CInt(AlturaDaPauta / 3) 'Area de sobreposição
        Dim DoisTerços As Integer = CInt(2 * AlturaDaPauta / 3 - 2 * ELI) 'Area de sobreposição 
        'com correcção de inicio  (- 2 * ELI)
        Dim AltPauta As Integer = AlturaDaPauta + (1 * ELI \ 2) ' Ajuste inicial Teclado Inferior
        ' Correcção inicial : +(1 * ELI \ 2) - O  sinal (+) obriga  a  descer na  pauta
        Dim CoordenadasYTotais(ColCount - 1) As Short
        Dim PSup As String = Nothing : Dim PInf As String = Nothing

        'If IsNumeric(Val(TextInput2.Text)) Then
        '    Dim CorrecçãoYPauta As Integer = CInt(Val(TextInput2.Text))
        'Else
        '    TextInput2.Text = CType(0, String)
        'End If

        'Teclado Superior *****************************************************************************
        For c = 1 To ColCount - 1

            'DEclarações de contexto
            Dim OitavaAnterior As Integer
            Dim ParamY As Short
            Dim DeltaY As Short = CShort(ELI / 2 * (ParamY - 1))
            'Dectecção da oitava currente
            Dim DetectaOitava As String = Mid(OrdemDasNotasComBemóis(c), 4, 1)
            If Mid(OrdemDasNotasComBemóis(c), 1, 1) = "b" Then
                DetectaOitava = Mid(OrdemDasNotasComBemóis(c), 5, 1)
            End If
            'Caso Particular do sol
            If Mid(OrdemDasNotasComBemóis(c), 1, 3) = "SOL" Then
                DetectaOitava = Mid(OrdemDasNotasComBemóis(c), 5, 1)
            End If
            If Mid(OrdemDasNotasComBemóis(c), 1, 4) = "bSOL" Then
                DetectaOitava = Mid(OrdemDasNotasComBemóis(c), 6, 1)
            End If
            'Por  segurança verifica  se é uma  string  numérica
            If IsNumeric(CInt(Val(DetectaOitava))) Then
                Dim Oitb As Integer = CInt(Val(DetectaOitava))
                OitavaAnterior = Oitb - 1
            End If

            'Inicio dos  calculos  diferentes dos  sustenidos
            'Inicio dos  IFFFFFFs 
            If c = CInt(1 + 12 * OitavaAnterior) Then
                ParamY = CShort(1 + 7 * OitavaAnterior) 'Dó 
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(2 + 12 * OitavaAnterior) Or c = CInt(3 + 12 * OitavaAnterior) Then
                ParamY = CShort(2 + 7 * OitavaAnterior) ''Ré e " bRé
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(4 + 12 * OitavaAnterior) Or c = CInt(5 + 12 * OitavaAnterior) Then
                ParamY = CShort(3 + 7 * OitavaAnterior) 'Mi e bMI
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(6 + 12 * OitavaAnterior) Then
                ParamY = CShort(4 + 7 * OitavaAnterior) 'Fá 
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(7 + 12 * OitavaAnterior) Or c = CInt(8 + 12 * OitavaAnterior) Then
                ParamY = CShort(5 + 7 * OitavaAnterior) 'Sol e bSol
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(9 + 12 * OitavaAnterior) Or c = CInt(10 + 12 * OitavaAnterior) Then
                ParamY = CShort(6 + 7 * OitavaAnterior) 'Lá e bLá
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If
            If c = CInt(11 + 12 * OitavaAnterior) Or c = CInt(12 + 12 * OitavaAnterior) Then
                ParamY = CShort(7 + 7 * OitavaAnterior) 'Si   e  bSI
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(DoisTerços - DeltaY - CorrecçãoYPautaS)
            End If

            If CoordenadasYTotais(c) < 0 Or CoordenadasYTotais(c) > DoisTerços Then
                CoordenadasYTotais(c) = -5 'Invisivel
            End If
            StrYYYPianoSuperior(c) = CType(CoordenadasYTotais(c), String)
            StrYYYPianoSuperior(0) = "Piano Superior-bY" 'Nome do ROW
            PSup = PSup & CoordenadasYTotais(c) & ","

        Next
        'Teclado Inferior *************************************************************************************
        For c = 1 To ColCount - 1

            Dim OitavaAnterior As Integer
            Dim ParamY As Short
            Dim DeltaY As Short = CShort(ELI / 2 * (ParamY - 1))
            Dim DetectaOitava As String = Mid(OrdemDasNotasComBemóis(c), 4, 1)
            If Mid(OrdemDasNotasComBemóis(c), 1, 1) = "b" Then
                DetectaOitava = Mid(OrdemDasNotasComBemóis(c), 5, 1)
            End If
            'Caso Particular do sol
            If Mid(OrdemDasNotasComBemóis(c), 1, 3) = "SOL" Then
                DetectaOitava = Mid(OrdemDasNotasComBemóis(c), 5, 1)
            End If
            If Mid(OrdemDasNotasComBemóis(c), 1, 4) = "bSOL" Then
                DetectaOitava = Mid(OrdemDasNotasComBemóis(c), 6, 1)
            End If
            If IsNumeric(CInt(Val(DetectaOitava))) Then
                Dim Oit As Integer = CInt(Val(DetectaOitava))
                OitavaAnterior = Oit - 1
            End If

            'Inicio dos  IFFFFFFs 
            If c = CInt(1 + 12 * OitavaAnterior) Then
                ParamY = CShort(1 + 7 * OitavaAnterior) 'Dó  
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(2 + 12 * OitavaAnterior) Or c = CInt(3 + 12 * OitavaAnterior) Then
                ParamY = CShort(2 + 7 * OitavaAnterior) ''Ré e " bRé
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(4 + 12 * OitavaAnterior) Or c = CInt(5 + 12 * OitavaAnterior) Then
                ParamY = CShort(3 + 7 * OitavaAnterior) 'Mi e bMI
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(6 + 12 * OitavaAnterior) Then
                ParamY = CShort(4 + 7 * OitavaAnterior) 'Fá 
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(7 + 12 * OitavaAnterior) Or c = CInt(8 + 12 * OitavaAnterior) Then
                ParamY = CShort(5 + 7 * OitavaAnterior) 'Sol e bSol
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(9 + 12 * OitavaAnterior) Or c = CInt(10 + 12 * OitavaAnterior) Then
                ParamY = CShort(6 + 7 * OitavaAnterior) 'Lá e bLá
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If
            If c = CInt(11 + 12 * OitavaAnterior) Or c = CInt(12 + 12 * OitavaAnterior) Then
                ParamY = CShort(7 + 7 * OitavaAnterior) 'Si e bSI
                DeltaY = CShort(ELI / 2 * (ParamY - 1))
                CoordenadasYTotais(c) = CShort(AltPauta - DeltaY - CorrecçãoYPautaI)
            End If

            If CoordenadasYTotais(c) < UmTerço Or CoordenadasYTotais(c) > AlturaDaPauta Then
                CoordenadasYTotais(c) = CShort(AltPauta + 5) 'Invisivel
            End If
            StrYYYPianoInferior(c) = CType(CoordenadasYTotais(c), String)

            PInf = PInf & CoordenadasYTotais(c) & ","

        Next
        StrYYYPianoInferior(0) = "Piano Inferior-bY" 'Nome do ROW
        PSup = StrYYYPianoSuperior(0) & "," & PSup
        PInf = StrYYYPianoInferior(0) & "," & PInf

        With MemóriaPauta
            Dim RowHeaderStyle As New DataGridViewCellStyle With {
                .BackColor = Color.Beige,
                .Font = New Font("Verdana", 8, FontStyle.Bold)
            }
            .RowHeadersDefaultCellStyle = RowHeaderStyle
            .RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Sunken
            .Rows.Add(StrYYYPianoSuperior)  ' Pode usar-se apenas as linhas em vez da matriz
            '            '.Rows.Add("Piano Superior", 180, 180, 175, 175, 170, 165, 165, 160, 160, 155, 155, 150, 145, 145, 140, 140,
            '                      135, 130, 130, 125, 125, 120, 120, 115, 110, 110, 105, 105, 100, 95, 95, 90, 90, 85, 85, 80, 75,
            '                      75, 70, 70, 65, 60, 60, 55, 55, 50, 50, 45, 40, 40, 35, 35, 30, 25, 25, 20, 20, 15, 15, 10, 5, 5,
            '                      0, 0, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
            '                      -5, -5, -5, -5, -5, -5, -5, -5, -5)
            .Rows.Add(StrYYYPianoInferior)   ' Pode usar-se apenas as linhas em vez da matriz
            '.Rows.Add("Piano Inferior", 310, 310, 300, 300, 295, 290, 290, 285, 285, 280, 280, 275, 270, 270, 265, 265,
            '          260, 255, 255, 250, 250, 245, 245, 240, 235, 235, 230, 230, 225, 220, 220, 215, 215, 210, 210,
            '          205, 200, 200, 195, 195, 190, 185, 185, 180, 180, 175, 175, 170, 165, 165, 160, 160, 155, 150,
            '          150, 145, 145, 140, 140, 135, 130, 130, 125, 125, 120, 115, 115, 110, 110, 105, 105, 100, 310,
            '          310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
            '          310, 310, 310, 310)
            .AutoSize = True
            'If .ShowRowErrors = True Then MsgBox("Erro no preenchimento da Grid   " & ErrorToString())
        End With

        Exit Sub
Erros:
        MsgBox("Detectado Erro na Sub AdicionandoLinhasMemóriaPautaComBemóis :  " & ErrorToString())
    End Sub

#End Region

#Region "Comandos (buttons) para Mudar  de  bitmap  ...  Apagar ultimas  notas  ou  refazê-las"

    Sub ComandosParaGerirEscritaNaPauta()
        On Error GoTo Erros
        'Permite Apagar até 50 notas e refazer tudo novamente
        'Nota  por  enquanto a primeira  nota não  estou  conseguindo  apagar
        'Buttons para apagar as notas  ***************************************************
        Dim BitGoOn As New Bitmap(My.Resources.GoOnSup, New Size(40, 25))
        'BitGoOn.MakeTransparent()
        Dim BitGoBack As New Bitmap(My.Resources.GoBackSup, New Size(40, 25))
        'BitGoBack.MakeTransparent()
        Dim BitGoOnInf As New Bitmap(My.Resources.GoOnInf, New Size(40, 25))
        'BitGoOn.MakeTransparent()
        Dim BitGoBackInf As New Bitmap(My.Resources.GoBackInf, New Size(40, 25))
        'BitGoBack.MakeTransparent()

        Dim GoOnSup As New Button With {.Location = New Point(10, 550), .Size = New Size(40, 25),
               .Image = BitGoOn, .Visible = True, .Enabled = True, .Cursor = Cursors.Hand}
        ttip12.SetToolTip(GoOnSup, "Retomar Notas Apagadas - Piano Sup")
        Me.Controls.Add(GoOnSup)
        AddHandler GoOnSup.MouseDown, AddressOf GoOnSuP_MouseDown

        Dim GoBackSup As New Button
        With GoBackSup
            ttip13.SetToolTip(GoBackSup, "Apagar Notas  - Piano Sup")
            .Location = New Point(760, 550)
            .Size = New Size(40, 25)
            .Image = BitGoBack
            .Visible = True
            .Enabled = True
            .Cursor = Cursors.Hand
        End With
        Me.Controls.Add(GoBackSup)
        AddHandler GoBackSup.MouseDown, AddressOf GoBackSuP_MouseDown

        Dim GoOnInf As New Button With {.Location = New Point(10, 575), .Size = New Size(40, 25),
               .BackgroundImage = BitGoOnInf, .Visible = True, .Enabled = True, .Cursor = Cursors.Hand}
        ttip14.SetToolTip(GoOnInf, "Retomar Notas Apagadas - Piano Inf")
        Me.Controls.Add(GoOnInf)
        AddHandler GoOnInf.MouseDown, AddressOf GoOnInf_MouseDown

        Dim GoBackInf As New Button With {.Location = New Point(760, 575), .Size = New Size(40, 25),
               .BackgroundImage = BitGoBackInf, .Visible = True, .Enabled = True, .Cursor = Cursors.Hand}
        ttip15.SetToolTip(GoBackInf, "Apagar Notas  - Piano Inf")
        Me.Controls.Add(GoBackInf)
        AddHandler GoBackInf.MouseDown, AddressOf GoBackInf_MouseDown

        Exit Sub
Erros:
        MsgBox("Detectado um erro na  sub ComandosParaGerirEscritaNaPauta ..." & ErrorToString())
    End Sub

    Public Sub GoOnSuP_MouseDown(ByVal Sender As Object, ByVal e As MouseEventArgs) Handles GoOnSup.MouseDown
        'Situação  ascendente
        MemPautaSup = MemPautaSup + 1
        'ttip12.SetToolTip(GoOnSup, "Retomar Notas Apagadas - Piano Sup")
        If MemPautaSup < (MemMáxima - 1) And MemPautaSup >= 0 And (CoordenadaXSup >= 40 Or CoordenadaXInf >= 40) Then
            'Necessário   assegurar  que  a matriz já  está  prenchida
            'No  entanto deixa-se o limite superior sem nehuma  barreira
            'Só  há  problema se a  matriz estiver  vazia
            If CoordenadaXSup <= 7980 Then CoordenadaXSup = CoordenadaXSup + 20
            If CoordenadaXInf <= 7980 Then CoordenadaXInf = CoordenadaXInf + 20
            PautaPictureBox.BackgroundImage = BitmapMemPautaSup(MemPautaSup)
            lblChords(12).Text = "MemPautaSup= " & MemPautaSup
        Else
            MsgBox("Atingiu o limite  de memória .... Se continuar vai apagar os dados e reiniciá-la !")
        End If
    End Sub

    Public Sub GoBackSuP_MouseDown(ByVal Sender As Object, ByVal e As MouseEventArgs) Handles GoBackSup.MouseDown
        'Situação descendente
        MemPautaSup = MemPautaSup - 1
        'ttip13.SetToolTip(GoBackSup, "Apagar Notas  - Piano Sup")
        'Evitar o apagamento total da pauta 
        If MemPautaSup >= 0 And (CoordenadaXSup >= 40) Then
            If CoordenadaXSup > 40 Then CoordenadaXSup = CoordenadaXSup - 20
            If CoordenadaXInf > 40 Then CoordenadaXInf = CoordenadaXInf - 20
            PautaPictureBox.BackgroundImage = BitmapMemPautaSup(MemPautaSup)
            lblChords(12).Text = "MemPautaSup= " & MemPautaSup
        Else
            MsgBox("Atingiu o limite  minimo  da  PAUTA")
        End If
    End Sub

    Public Sub GoOnInf_MouseDown(ByVal Sender As Object, ByVal e As MouseEventArgs) Handles GoOnInf.MouseDown
        'Situação  ascendente
        MemPautaInf = MemPautaInf + 1
        'ttip14.SetToolTip(GoOnInf, "Retomar Notas Apagadas - Piano Inf")
        If MemPautaInf < (MemMáxima - 1) And MemPautaInf >= 0 And (CoordenadaXSup >= 40 Or CoordenadaXInf >= 40) Then
            'Necessário   assegurar  que  a matriz já  está  prenchida
            'No  entanto deixa-se o limite superior sem nehuma  barreira
            'Só  há  problema se a  matriz estiver  vazia
            If CoordenadaXSup <= 7980 Then CoordenadaXSup = CoordenadaXSup + 20
            If CoordenadaXInf <= 7980 Then CoordenadaXInf = CoordenadaXInf + 20
            PautaPictureBox.BackgroundImage = BitmapMemPautaInf(MemPautaInf)
            lblChords(12).Text = "MemPautaInf= " & MemPautaInf
        Else
            MsgBox("Atingiu o limite  superior  da  PAUTA")
        End If
    End Sub

    Public Sub GoBackInf_MouseDown(ByVal Sender As Object, ByVal e As MouseEventArgs) Handles GoBackInf.MouseDown
        'Situação  descendente
        MemPautaInf = MemPautaInf - 1
        'ttip15.SetToolTip(GoBackInf, "Apagar Notas  - Piano Inf")
        'Evitar o apagamento total da pauta 
        If MemPautaInf >= 0 And (CoordenadaXInf >= 40) Then
            If CoordenadaXSup > 40 Then CoordenadaXSup = CoordenadaXSup - 20
            If CoordenadaXInf > 40 Then CoordenadaXInf = CoordenadaXInf - 20
            PautaPictureBox.BackgroundImage = BitmapMemPautaInf(MemPautaInf)
            lblChords(12).Text = "MemPautaInf= " & MemPautaInf
        Else
            MsgBox("Atingiu o limite  minimo  da  PAUTA")
        End If
    End Sub

#End Region

#Region "Mostroário Para Manipulação manual das representações das notas para  a pauta"
    'Nota ainda  há  aqui muito  a  fazer no  acerto  do   drop
    Public Sub MostroárioMusical()
        Dim FlNotePanel As New FlowLayoutPanel ' Caixa com scroll
        With FlNotePanel
            .Location = New Point(5, 230)
            .Size = New Drawing.Size(800, 70)
            .AutoScroll = True
            .FlowDirection = FlowDirection.TopDown
            .VerticalScroll.Visible = False
            .HorizontalScroll.SmallChange = 50
            .HorizontalScroll.LargeChange = 100
            .BorderStyle = BorderStyle.FixedSingle
            .BackColor = Color.Beige
            .HorizontalScroll.Maximum = 2000
            .HorizontalScroll.Minimum = 0
            .AllowDrop = True
            .Contains(CharLabel(CharNumber))
        End With
        Me.Controls.Add(FlNotePanel)
        'Adicionar Dois buttons para apagar ou refazer a acção manual de acrescentar notas na pauta
        With ManualClearBtn
            .Text = "Undo"
            .Location = New Point(160, 575)
            .Visible = True
            .Size = New Drawing.Size(40, 20)
            .Font = New Font("Arial", 6, FontStyle.Bold)
            .FlatStyle = FlatStyle.Standard
            .BackColor = Color.CadetBlue
            .ForeColor = Color.DarkBlue
            .TextAlign = ContentAlignment.MiddleCenter
            .BringToFront()
            AddHandler .MouseClick, AddressOf ManualClearBtn_MouseClick
        End With
        Me.Controls.Add(ManualClearBtn)
        With ManualRedrawBtn
            .Text = "Redo"
            .Location = New Point(200, 575)
            .Visible = True
            .Size = New Drawing.Size(40, 20)
            .Font = New Font("Arial", 6, FontStyle.Bold)
            .FlatStyle = FlatStyle.Standard
            .BackColor = Color.Cyan
            .ForeColor = Color.DarkGreen
            .TextAlign = ContentAlignment.MiddleCenter
            .BringToFront()
            AddHandler .MouseClick, AddressOf ManualRedrawBtn_MouseClick
        End With
        Me.Controls.Add(ManualRedrawBtn)
        With ManualReset 'Recolocar a pauta vazia
            .Text = "RESET"
            .Location = New Point(180, 555)
            .Visible = True
            .Size = New Drawing.Size(40, 20)
            .Font = New Font("Arial", 6, FontStyle.Bold)
            .FlatStyle = FlatStyle.Standard
            .BackColor = Color.RoyalBlue
            .ForeColor = Color.DarkRed
            .TextAlign = ContentAlignment.MiddleCenter
            .BringToFront()
            AddHandler .MouseClick, AddressOf ManualReset_MouseClick
        End With
        Me.Controls.Add(ManualReset)

        PautaPictureBox.Controls.Add(InfoNoteLaBel) ' Nota  : adicionei o  lábel á picture que  contem a pauta
        'Adicionar um label() cuja imagem conterá um icon musical 
        'para seguir o cursor e informar qual a nota mais perto
        'Dim InfoNoteLaBel As New Label
        With InfoNoteLaBel
            '.Name = ""
            .Location = New Point '(160, 565)
            .Visible = False
            .Size = New Drawing.Size(50, 15)
            .Font = New Font("Arial", 8, FontStyle.Bold)
            .BorderStyle = BorderStyle.None
            .BackColor = Color.Transparent
            .ForeColor = Color.DarkBlue
            .TextAlign = ContentAlignment.MiddleCenter
            .BringToFront()
            'AddHandler .LocationChanged, AddressOf InfoNoteLaBel_Move
        End With
        PautaPictureBox.Controls.Add(InfoNoteLaBel) ' Nota  : adicionei o  lábel á picture que  contem a pauta

        'Preenchimento de  image list  
        'Dim CharImgList As New ImageList With {.ImageSize = New Size(12, 24), .ColorDepth = ColorDepth.Depth32Bit}
        '»»»»»»»»»»»»»»    Colocação das  imagens dos  icons nas labeis(i)
        'Dim CharNumber As Integer = IconsCollection.Count ' Colecção dos  icons
        For i = 0 To CharNumber - 1
            CharLabel(i) = New Label '  WithEvents e  cada  label contem uma  imagem (icon)
            With CharLabel(i)
                .Location = New Point(10 * (i - 1) + 5, 230)
                .Size = New Drawing.Size(36, 48)
                .Tag = i
                .Image = ObjList(i).ToBitmap
                .Name = IconCodeNames(i)
                .BackColor = Color.Transparent
                .BorderStyle = BorderStyle.Fixed3D
                'Using CharImgList '= New ImageList
                '    CharImgList.Images.Add(CharLabel(i).Image, Color.Transparent)
                '    CharImgList.Tag = i
                'End Using
                '.Container.Add(Me.FlNotePanel)
                .AutoEllipsis = True
                .Handle.Equals(Me.FlNotePanel)
            End With
            FlNotePanel.Controls.Add(CharLabel(i))

            AddHandler CharLabel(i).MouseDown, AddressOf CharLabel_MouseDown ' Inicia o DoDragDrop
            AddHandler CharLabel(i).MouseCaptureChanged, AddressOf CharLabel_MouseCaptureChanged
            AddHandler CharLabel(i).MouseLeave, AddressOf CharLabel_MouseLeave '
            AddHandler CharLabel(i).DragOver, AddressOf CharLabel_DragOver ' Gere label informativo
            AddHandler CharLabel(i).DragEnter, AddressOf CharLabel_DragEnter ' Gere  efeitos e permissões
            AddHandler CharLabel(i).DragDrop, AddressOf CharLabel_DragDrop ' Coloca  a nota  na  pauta e toca-a
            'AddHandler PautaPictureBox.MouseUp, New MouseEventHandler(AddressOf PautaPictureBox_MouseUp)

        Next

    End Sub

    Private Sub CharLabel_MouseDown(ByVal Sender As Object, ByVal e As MouseEventArgs) Handles FlNotePanel.MouseDown
        'Selecionar um dos labeis clicado e  obter o seu indice dentro nos labeis
        'MOST IMportant :   A obtenção  do  indice  ´passo  fundamental
        MyIndex = Array.IndexOf(CharLabel, Sender)
        'O Passo  acima devolve o indice do objecto clicado 
        MyCharName = CharLabel(MyIndex).Name
        Dim ImgNotaCurrenteCópy As New Bitmap(CType(CharLabel(MyIndex).Image, Bitmap))
        'Clonar o bitmap para arrasto
        Dim ImgNotaCurrente As Bitmap = CType(ImgNotaCurrenteCópy.Clone, Bitmap)
        IsClicked = True
        CharLabel(MyIndex).DoDragDrop(ImgNotaCurrente, DragDropEffects.Copy Or DragDropEffects.Move)
        'Nota:  Não consegui eliminar o possivel  drag exterior por  ex  de  caracteres da richtexbox

    End Sub

    Private Sub CharLabel_MouseCaptureChanged(Sender As Object, e As EventArgs) Handles PautaPictureBox.MouseUp
        'É no final do drop que  as  coisas  se  complicam  ainda  mais :  temporizar a nota  e  silenciá-la após
        'TemporizaçãoDaNota(NotaFinalNoDrop)
        'UltimaNotaMusical = NotaFinalNoDrop ' Para abafamentos  finais .....on  closing
        'OffMusicalNote(CByte(UltimaNotaMusical), Octave) ' já  incluido na  sub TemporizaçãoDaNota()
    End Sub

    Private Sub CharLabel_MouseLeave(Sender As Object, e As EventArgs)
        'Sempre que se perde o foco do mouse a variável reseta
        IsClicked = False
        'UltimaNotaMusical = NotaFinalNoDrop ' Para abafamentos  finais .....on  closing
        'OffMusicalNote(CByte(UltimaNotaMusical), Octave)
    End Sub

    Private Sub CharLabel_DragOver(ByVal Sender As Object, ByVal e As DragEventArgs) Handles PautaPictureBox.DragOver
        On Error GoTo Erros
        'Sender = My.Resources.Boneco1
        If Not e.Data.GetDataPresent(GetType(Bitmap)) = True Then
            e.Effect = DragDropEffects.None
            e.Effect = CType(DragAction.Cancel, DragDropEffects) ' DragAction.Cancel
            'MsgBox("Only Images are permited to Drag..." & e.Data.GetDataPresent([GetType].GetTypeInfo))
            Return
        ElseIf e.Effect = DragDropEffects.Move Then
            Dim NewPt As Point = PautaPictureBox.PointToClient(New Point(e.X - 5, e.Y - 16)) ' Colocação do Ponteiro
            Dim PtLabel As Point = PautaPictureBox.PointToClient(New Point(e.X + 20, e.Y)) 'Verificação do nome da nota
            Dim LabelLoc As Point = PautaPictureBox.PointToClient(New Point(e.X + 20, e.Y - 6)) ' Colocação do label
            Coordy = PtLabel.Y
            ' Dim RetornaNomeDaNota As String = Nothing
            'Dim StrComplementar As String = ImgNotaCurrente.Tag
            ''»»»»»»»»»»   AS  NOTAS Musicais ( incluindo os acidentes ) são multiplos  de  cinco no eixo dos YYY
            'Pelo que a cor  da  informação disponibilizada pelo label pode  mudar
            'è o lábel que transporta uma qualquer imagem que  se   queira arrastar
            With InfoNoteLaBel
                .Visible = True
                .Location = LabelLoc
                'Colocar aqui a escolha do user para arrasto
                If Not IsNothing(ImgBonecoCurrente) Then
                    .Image = ImgBonecoCurrente
                    .Size = ImgBonecoCurrente.Size
                    '.Update()
                Else
                    'Miniatura
                    '.Image = CType(My.Resources.Boneco6.GetThumbnailImage(64, 64, callback:=Nothing, callbackData:=IntPtr.Zero), Bitmap)
                    .Image = My.Resources.Boneco6
                    .Image.RotateFlip(RotateFlipType.Rotate180FlipY) 'My.Resources.Boneco6.RotateFlip(CType(RotateFlipType.Rotate180FlipX, RotateFlipType)) ' Default
                    .ImageAlign = ContentAlignment.MiddleLeft
                    .Size = New Drawing.Size(64, 64)
                    .Update()
                End If

                .BackColor = Color.Transparent
                .TextAlign = ContentAlignment.BottomCenter
                If Coordy Mod 5 = 0 Then
                    .ForeColor = Color.Red
                    'System.Media.SystemSounds.Exclamation.Play()
                    'Aqui mecanismo de reconhecimento do nome  da  nota - nova Function
                    Call ObtençãoDaNotaPelaCoordenada(Coordy, MyCharName)
                    .Text = RetornaNomeDaNota
                    'Thread.Sleep(10) 'Aguarda 1seg
                ElseIf Coordy Mod 5 < 3 Then
                    .ForeColor = Color.YellowGreen 'Permite visualizar mais tempo
                Else
                    'Resetar nome da nota
                    RetornaNomeDaNota = ""
                    '.Text = PtLabel.Y.ToString ' Isto  vai  atrasar os  calculos  a -  eliminar  futuramente
                End If
                .Update()
            End With

        End If
        Exit Sub
Erros:
        MsgBox("Detectado  Erro na Sub CharLabel_DragOver" & ErrorToString())

    End Sub

    Private Function ObtençãoDaNotaPelaCoordenada(ByVal CoordY As Integer, ByVal MyCharName As String) As Boolean
        On Error GoTo Erros
        'Coordy é a  coordenada no eixo dos  YYY   e  MyCharname  é a  designação da nota 
        'Aqui  entra-se com um valor  que  já é  multiplo de  cinco  e que  portanto  existe no data grid view
        'E  após  consulta  do  mesmo retorna o nome da nota ....
        With MemóriaPauta ' Datagrid de consulta no fundo  do  formulário e invisivel
            For i = 1 To .ColumnCount - 1
                'ATENÇão Os Acidentes #  ou  b(emóis)  tem  de  começar por #  ou  b na posição 5
                'Bem como as notas naturais que na posição 5 deve  figurar "n"
                'Na posição 6,7 se estiver CS ( com som )  então esse icon será tocado no drop sobre a pauta
                'Teclado Superior CoordY <=145 .............. Teclado Inf  CoordY <= 300
                'MsgBox("Nome do icon na Posição 5 = " & Mid(MyCharName, 5, 1) & "Posição 6,7 = " & Mid(MyCharName, 6, 2))
                If Mid(MyCharName, 5, 1) = "#" And Mid(MyCharName, 6, 2) = "CS" Then
                    If CoordY <= 145 Then 'Teclado Superior
                        If Val(MemóriaPauta.Rows(1).Cells(i).Value.ToString) = CoordY Then ' Numeração das teclas
                            If Mid(MemóriaPauta.Columns(i).Name, 1, 1) = "#" Then ' designação das mesmas 
                                RetornaNomeDaNota = MemóriaPauta.Columns(i).Name ' retorna  a  designação 
                                NotaFinalNoDrop = CInt(MemóriaPauta.Rows(0).Cells(i).Value.ToString) 'Som
                                ColocaçãoGuiadaDaNota = CInt(MemóriaPauta.Rows(1).Cells(i).Value.ToString) 'Pauta
                                Return True
                            End If
                        End If
                    End If
                    If CoordY > 145 Then  'Teclado Inferior
                        If Val(MemóriaPauta.Rows(2).Cells(i).Value.ToString) = CoordY Then
                            If Mid(MemóriaPauta.Columns(i).Name, 1, 1) = "#" Then
                                RetornaNomeDaNota = MemóriaPauta.Columns(i).Name
                                NotaFinalNoDrop = CInt(MemóriaPauta.Rows(0).Cells(i).Value.ToString)
                                ColocaçãoGuiadaDaNota = CInt(MemóriaPauta.Rows(2).Cells(i).Value.ToString)
                                Return True
                            End If
                        End If
                    End If
                End If
                If Mid(MyCharName, 5, 1) = "b" And Mid(MyCharName, 6, 2) = "CS" Then
                    If CoordY <= 145 Then
                        If Val(MemóriaPauta.Rows(4).Cells(i).Value.ToString) = CoordY Then
                            If Mid(MemóriaPauta.Rows(3).Cells(i).Value.ToString, 1, 1) = "b" Then
                                RetornaNomeDaNota = MemóriaPauta.Rows(3).Cells(i).Value.ToString
                                NotaFinalNoDrop = CInt(MemóriaPauta.Rows(0).Cells(i).Value.ToString)
                                ColocaçãoGuiadaDaNota = CInt(MemóriaPauta.Rows(4).Cells(i).Value.ToString)
                                Return True
                            End If
                        End If
                    End If
                    If CoordY > 145 Then
                        If Val(MemóriaPauta.Rows(5).Cells(i).Value.ToString) = CoordY Then
                            If Mid(MemóriaPauta.Rows(3).Cells(i).Value.ToString, 1, 1) = "b" Then
                                RetornaNomeDaNota = MemóriaPauta.Rows(3).Cells(i).Value.ToString
                                NotaFinalNoDrop = CInt(MemóriaPauta.Rows(0).Cells(i).Value.ToString)
                                ColocaçãoGuiadaDaNota = CInt(MemóriaPauta.Rows(5).Cells(i).Value.ToString)
                                Return True
                            End If
                        End If
                    End If
                End If

                If Mid(MyCharName, 5, 1) = "n" And Mid(MyCharName, 6, 2) = "CS" Then
                    If CoordY <= 145 Then
                        If Val(MemóriaPauta.Rows(1).Cells(i).Value.ToString) = CoordY Then
                            RetornaNomeDaNota = MemóriaPauta.Columns(i).Name
                            NotaFinalNoDrop = CInt(MemóriaPauta.Rows(0).Cells(i).Value.ToString)
                            ColocaçãoGuiadaDaNota = CInt(MemóriaPauta.Rows(1).Cells(i).Value.ToString)
                            Return True
                        End If
                    End If
                    If CoordY > 145 Then
                        If Val(MemóriaPauta.Rows(2).Cells(i).Value.ToString) = CoordY Then
                            RetornaNomeDaNota = MemóriaPauta.Columns(i).Name
                            NotaFinalNoDrop = CInt(MemóriaPauta.Rows(0).Cells(i).Value.ToString)
                            ColocaçãoGuiadaDaNota = CInt(MemóriaPauta.Rows(2).Cells(i).Value.ToString)
                            Return True
                        End If
                    End If
                End If
            Next i
        End With
        Return False
        Exit Function
Erros:
        MsgBox("Detectado  Erro na Function ObtençãoDaNotaPelaCoordenada" & ErrorToString())
    End Function

    Private Sub CharLabel_DragEnter(ByVal Sender As Object, ByVal e As DragEventArgs) Handles PautaPictureBox.DragEnter
        On Error GoTo Erros
        'Memoria do Primeiro bitmap Manual*****************************************************
        'If IndiceMemPautaManual = 0 Then
        '    BitmapMemPautaManual(IndiceMemPautaManual) = CType(PautaPictureBox.BackgroundImage, Bitmap)
        '    Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage)
        'End If
        Start = PautaPictureBox.PointToClient(New Point(e.X, e.Y))  '  Declarado  no  inicio como   private
        If Not e.Data.GetDataPresent(GetType(Bitmap)) = True Then
            e.Effect = DragDropEffects.None
            e.Effect = CType(DragAction.Cancel, DragDropEffects) ' DragAction.Cancel
            'MsgBox("Only Images are permited to Drag..." & e.Data.GetDataPresent([GetType].GetTypeInfo))
            Exit Sub
            'Return
            '
        ElseIf CBool(e.AllowedEffect And CType(DragDropEffects.Move = DragDropEffects.Move, DragDropEffects)) Then
            e.Effect = DragDropEffects.Move
            CharLabel_DragOver(Sender, e)
        ElseIf CBool(e.AllowedEffect And CType(DragDropEffects.Copy = DragDropEffects.Copy, DragDropEffects)) Then
            e.Effect = DragDropEffects.Copy
            CharLabel_DragOver(Sender, e)
        End If
        Exit Sub
Erros:
        MsgBox("Erro Detectado na  Sub CharLabel_DragEnter..." & ErrorToString())
    End Sub

    Private Sub CharLabel_DragDrop(ByVal Sender As Object, ByVal e As DragEventArgs) Handles PautaPictureBox.DragDrop
        ' On Error GoTo Erros
        ''Memoria do Primeiro bitmap Manual*****************************************************
        If IndiceMemPautaManual = 0 Then
            BitmapMemPautaManual(IndiceMemPautaManual) = CType(PautaPictureBox.BackgroundImage, Bitmap)
            'NumItensAdicionados = 0
        End If
        'MsgBox("Dados do e As DragEventArgs ..." & e.Data.ToString) ' ----------------não interessam
        'IMPORTANTE.......................................
        'No Drop há que retirar vários dados que tem a ver com o formato do nome das notas  _XXX(n,#,b,c,l,p,x,w,z)(CS,SS)Nome
        Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage)
        Dim GrPautaSupDrag As Graphics = Graphics.FromImage(BitMapPauta)
        Dim MouseMoveGraphics As Graphics = PautaPictureBox.CreateGraphics
        Dim ImgNotaCurrente As Bitmap = CType(CharLabel(MyIndex).Image, Bitmap)
        ' Os  valores  numéricos  (-5) e  (-16)  são  correcções á posteriori e completamente  empirico
        '  Bem  como  as   correcçoes  e ajustamentos  para o ecran
        Dim NewPt As Point = PautaPictureBox.PointToClient(New Point(e.X - 5, e.Y))
        'ColocaçãoGuiadaDaNota REPRESENTA A ULTIMA COORDENADA MULTIPLA DE CINCO PERCORRIDA PELO CURSOR 

        ''Ajustamento Automático no eixo dos YYY- 16 AjustamentoParaEcran
        Dim dY As Integer = NewPt.Y Mod 5  '  o  resto  da  divisão  que  representa  o  afastamento das notas
        ' em relação ao centro -'quer dos espaços  quer das  linhas
        Dim Desvio As Integer = NewPt.Y - ColocaçãoGuiadaDaNota ' Se Negativo o valor NewPt.Y deve  aumentar \ descer na pauta
        'Se dy = 0,1,2,3,4   maior que 2 então a coordenada  aproxima-se  mais  do valor a  seguir  e  vice versa

        'Corolário : Nota :  Se o desvio é Zero não necessita de ajustamento automático
        'Apenas necessita da afinação final de (-16)
        If Desvio > 0 And dY > 2 Then
            NewPt.Y = NewPt.Y + (5 - dY)
        ElseIf Desvio > 0 And dY <= 2 Then
            NewPt.Y = NewPt.Y - dY
        ElseIf Desvio < 0 And dY <= 2 Then
            NewPt.Y = NewPt.Y - dY
        ElseIf Desvio < 0 And dY > 2 Then
            NewPt.Y = NewPt.Y + (5 - dY)
        End If
        NewPt.Y = NewPt.Y - 16 'Afinação final

        'Terminado os cálculos de NewPt para a colocação da nota no ecranªªªªªªªªªªªªªªªªªªªªªªª
        'Começa os  calculos para a cópia para o bitmap do ecran para a picture box
        'Obtenção das  coordenadas  de  ecran ScreenPt
        Dim ScreenPt As Point = PautaPictureBox.PointToScreen(New Point(NewPt.X, NewPt.Y))

        'GRÀFICOS.....................................................
        With MouseMoveGraphics   ' Apenas no ecran - pode  eleminar-se  futuramente
            .DrawImage(ImgNotaCurrente, NewPt)
            Application.DoEvents()
            MouseMoveGraphics.Clip.Dispose()
        End With

        'O Try seguinte vai inscrever os ultimos  dados  na  picture (PautaPictureBox.BackgroundImage)
        'A partir do bitmap prévio e nao se apaga com o scroll do flow panel
        With GrPautaSupDrag
            Try
                .CopyFromScreen(ScreenPt, NewPt, ImgNotaCurrente.Size)

                ' Lixeira para o grafismo no ecran
                MouseMoveGraphics.Dispose()
                IsClicked = False
                InfoNoteLaBel.Visible = False 'Esconde o Label após o drop
                InfoNoteLaBel.BackColor = Color.Transparent

                PautaPictureBox.BackgroundImage = BitMapPauta
                'Application.DoEvents()
            Catch ex As Exception
            Finally
                GrPautaSupDrag.Dispose()
            End Try
        End With

        'Após o Drop toca a  nota respectiva   -Valor (NotaFinalNoDrop) retirado  de  CoordY na Function 
        'SEGUE_SE AGORA UMA PORÇÃO DE OPÇÕES CONSOANTE O CARACTER ESCOLHIDO NO DRAG & DROP
        'Tudo o  seguinte  depende apenas de uma  variável -MyCharName- então parece-me mais indicado uma instrução  Case 
        'Private ThreadTemporizaçãoDaNota As Threading.Thread
        Select Case Mid(MyCharName, 6, 2) = "CS"' CS significa simplesmete Com Som
            Case True
                ' PlayMusicalNote(CByte(NotaFinalNoDrop), VolumeKey, Octave)
                TemporizaçãoDaNota(NotaFinalNoDrop, MyCharName) 'Novo processo para tocar a nota 
                NumItensAdicionados = NumItensAdicionados + 1
                MatrizDasNotasAdicionadasManualmente(MyCharName, NotaFinalNoDrop, NewPt,
                                                     NumItensAdicionados, MyIndex)
                Exit Sub 'Select '(Sub??) ' Creio que estão todos os dados aqui....
        End Select
        Select Case Mid(MyCharName, 6, 2) = "SS"    'significa simplesmete SEM Som
            Case True 'Toca um  determinado  som
                PlayMusicalNote(CByte(60), VolumeKey, CByte(2)) 'Escolheu-se este som +- aleatoriamente
                'DENTRO DESTAS SS EXISTEM VÁRIAS  OUTRAS OPÇÕES OS  COMPASSOS POR  EX:

                'Novos Loops  select case 
                Select Case Mid(MyCharName, 5, 1) = "c"
                    Case True
                        Compasso = CInt(Mid(MyCharName, 8, 2))
                        NumItensAdicionados = NumItensAdicionados + 1
                        MatrizDasNotasAdicionadasManualmente(MyCharName, NotaFinalNoDrop, NewPt,
                                                             NumItensAdicionados, MyIndex)
                        'SS Elimina-se o som de NotaFinalNoDrop
                End Select
                Select Case Mid(MyCharName, 5, 1) = "l"
                    Case True
                        OpçãoLigação = True 'Precisamos  de  dois pontos um é  claramente  o NewPt
                        NumItensAdicionados = NumItensAdicionados + 1
                        MatrizDasNotasAdicionadasManualmente(MyCharName, NotaFinalNoDrop, NewPt,
                                                             NumItensAdicionados, MyIndex)
                End Select
                '  sustenidos, bemóis  e  bequadros como acidentes permanentes  ou  isolados
                Select Case Mid(MyCharName, 5, 1) = "W"
                    Case NewPt.X <= EspaçoAcidentes ' quando são colocadas no inicio do 1º compasso
                        If Mid(MyCharName, 8, 3) = "Bem" Then AcidentePermanente = "Bemól"
                        If Mid(MyCharName, 8, 3) = "Sus" Then AcidentePermanente = "Sustenido"
                        NumItensAdicionados = NumItensAdicionados + 1
                        MatrizDasNotasAdicionadasManualmente(MyCharName, NotaFinalNoDrop, NewPt,
                                                             NumItensAdicionados, MyIndex)

                    Case NewPt.X > EspaçoAcidentes ' quando são colocadas no inicio do 1º compasso
                        If Mid(MyCharName, 8, 3) = "Bem" Then AcidenteIsolado = "Bemól"
                        If Mid(MyCharName, 8, 3) = "Sus" Then AcidenteIsolado = "Sustenido"
                        If Mid(MyCharName, 8, 3) = "Beq" Then AcidenteIsolado = "Bequadro"
                        NumItensAdicionados = NumItensAdicionados + 1
                        MatrizDasNotasAdicionadasManualmente(MyCharName, NotaFinalNoDrop, NewPt,
                                                             NumItensAdicionados, MyIndex)

                End Select
                Select Case Mid(MyCharName, 5, 1) = "p"  'pausas
                'Silencio = CInt(Val(Mid(MyCharName, 2, 3)))
                    Case True
                        TemporizaçãoDaPausa(NotaFinalNoDrop, MyCharName)
                        NumItensAdicionados = NumItensAdicionados + 1
                        MatrizDasNotasAdicionadasManualmente(MyCharName, NotaFinalNoDrop, NewPt,
                                                         NumItensAdicionados, MyIndex)

                End Select
        End Select

        ''Memoria do ultimo bitmap *****************************************************
        If IndiceMemPautaManual >= 0 And IndiceMemPautaManual <= 9 Then
            IndiceMemPautaManual = IndiceMemPautaManual + 1
            Call SubMemPautaManual(IndiceMemPautaManual)
        End If

        '        Exit Sub
        'Erros:
        '        MsgBox("Erro Detectado na  Sub CharLabel_DragDrop..." & ErrorToString())
    End Sub

    Private Sub SubMemPautaManual(ByVal IndiceMemPautaManual As Integer)
        On Error GoTo Erros

        If IndiceMemPautaManual <= 9 Then
            'BitmapMemPautaManual(IndiceMemPautaManual).UnlockBits()
            BitmapMemPautaManual(IndiceMemPautaManual) = CType(PautaPictureBox.BackgroundImage, Bitmap)
        ElseIf IndiceMemPautaManual > 9 Then
            IndiceMemPautaManual = 0
        End If
        Exit Sub
Erros:
        MsgBox("Erro Detectado na  Sub SubMemPautaManual..." & ErrorToString())
    End Sub

    Private Sub ManualClearBtn_MouseClick(ByVal Sender As Object, ByVal e As EventArgs) Handles ManualClearBtn.MouseClick
        On Error GoTo Erros
        If IndiceMemPautaManual > 0 Then
            IndiceMemPautaManual = IndiceMemPautaManual - 1
            PautaPictureBox.BackgroundImage = BitmapMemPautaManual(IndiceMemPautaManual)
        ElseIf IndiceMemPautaManual < 0 Then
            MsgBox("Não Tem mais nada  em  memória...")
        End If
        Exit Sub
Erros:
        MsgBox("Erro Detectado na  Sub ManualClearBtn_MouseClick..." & ErrorToString())
    End Sub

    Private Sub ManualRedrawBtn_MouseClick(ByVal Sender As Object, ByVal e As EventArgs) Handles ManualRedrawBtn.MouseClick
        On Error GoTo Erros
        If IndiceMemPautaManual <= 9 Then
            IndiceMemPautaManual = IndiceMemPautaManual + 1
            PautaPictureBox.BackgroundImage = BitmapMemPautaManual(IndiceMemPautaManual)
        ElseIf IndiceMemPautaManual > 9 Then
            MsgBox("Atingiu o limite da  memória...")
        End If
        Exit Sub
Erros:
        MsgBox("Erro Detectado na  Sub ManualRedrawBtn_MouseClick..." & ErrorToString())
    End Sub

    Private Sub ManualReset_MouseClick(ByVal Sender As Object, ByVal e As EventArgs) Handles ManualReset.MouseClick
        On Error GoTo Erros
        Dim Resp As MsgBoxResult
        Resp = MsgBox("Se Clicar em OK vai resetar o conteudo da pauta !", MsgBoxStyle.OkCancel, "OK para apagar - Cancel para sair")
        If Resp = MsgBoxResult.Cancel Then
            Exit Sub
        ElseIf Resp = MsgBoxResult.Ok Then
            ReconstruçãoDaPautaVazia()
        Else
        End If
        Exit Sub
Erros:
        MsgBox("Erro Detectado na  Sub ManualReset_MouseClick..." & ErrorToString())
    End Sub

#End Region

#Region "Aquisição da Designação da nota"

    Public Function DesignaçãoDaNotaPianoSup(ByVal PautaNoteSup As Byte) As Boolean
        On Error GoTo Erros
        'Rotina  destinada a obter a designaçºao das teclas tocadas - solo  ou  no piano  superior
        'Vai buscar isso ao DataGridView
        Dim NotaIndex As Integer = CInt(PautaNoteSup)
        Dim NoteIndexFind As Integer
        Dim NomeDaNotaPianoSup As String = Nothing
        If Acidentes = "Sustenidos" Then
            For Each CellSup As DataGridViewCell In MemóriaPauta.Rows(0).Cells
                NoteIndexFind = CellSup.ColumnIndex
                If NoteIndexFind = NotaIndex Then
                    NomeDaNotaPianoSup = MemóriaPauta.Columns(NoteIndexFind).Name.ToString
                    NotaSolo = NomeDaNotaPianoSup
                    'MsgBox("Tocou a nota :  " & NotaSolo)
                    Return True
                End If
            Next
        End If
        If Acidentes = "Bemóis" Then
            For Each CellInf As DataGridViewCell In MemóriaPauta.Rows(0).Cells
                NoteIndexFind = CellInf.ColumnIndex
                If NoteIndexFind = NotaIndex Then
                    NomeDaNotaPianoSup = MemóriaPauta.Rows(3).Cells.Item(NoteIndexFind).Value.ToString
                    NotaSolo = NomeDaNotaPianoSup
                    'MsgBox("Tocou a nota :  " & NotaChords)
                    Return True
                End If
            Next
        End If
        Exit Function
Erros:
        MsgBox("Detectado Erro na Function Designação da Nota  ....." & ErrorToString())
    End Function

    Public Function DesignaçãoDaNotaPianoInf(ByVal PautaNoteSup As Byte) As Boolean
        On Error GoTo Erros
        'Rotina  destinada a obter a designaçºao das teclas tocadas - solo  ou  no piano  superior
        'Vai buscar isso ao DataViewGrid
        'Rotina  destinada a obter a designaçºao das teclas tocadas - solo  ou  no piano  superior
        'Vai buscar isso ao DataViewGrid
        Dim NotaIndex As Integer = CInt(PautaNoteSup)
        Dim NoteIndexFind As Integer
        Dim NomeDaNotaPianoSup As String = Nothing
        If Acidentes = "Sustenidos" Then
            For Each CellInf As DataGridViewCell In MemóriaPauta.Rows(2).Cells
                NoteIndexFind = CellInf.ColumnIndex
                If NoteIndexFind = NotaIndex Then
                    NomeDaNotaPianoSup = MemóriaPauta.Columns(NoteIndexFind).Name.ToString
                    NotaChords = NomeDaNotaPianoSup
                    ' MsgBox("Tocou a nota :  " & NotaChords)
                    Return True
                End If
            Next
        End If
        If Acidentes = "Bemóis" Then
            For Each CellInf As DataGridViewCell In MemóriaPauta.Rows(2).Cells
                NoteIndexFind = CellInf.ColumnIndex
                If NoteIndexFind = NotaIndex Then
                    NomeDaNotaPianoSup = MemóriaPauta.Rows(3).Cells.Item(NoteIndexFind).Value.ToString
                    NotaChords = NomeDaNotaPianoSup
                    'MsgBox("Tocou a nota :  " & NotaChords)
                    Return True
                End If
            Next
        End If
        Exit Function
Erros:
        MsgBox("Detectado Erro na Function Designação da Nota  ....." & ErrorToString())
    End Function

    Public Function DesignaçãoDaNotaPianoInfChords(ByVal PautaNoteChords1 As Byte, ByVal PautaNoteChords2 As Byte, ByVal PautaNoteChords3 As Byte, ByVal PautaNoteChords4 As Byte) As Boolean
        On Error GoTo Erros
        'Rotina  destinada a obter a designaçºao das teclas tocadas - nos acordes Piano Inferior
        'Vai buscar isso ao DataViewGrid

        Dim NotaIndex() As Integer = {CInt(PautaNoteChords1), CInt(PautaNoteChords2), CInt(PautaNoteChords3), CInt(PautaNoteChords4)}
        Dim NoteIndexFind As Integer
        Dim i As Integer
        'A Cada   PautaNoteChords1,2,3,4  As Byte irá  corresponder uma NotaChordsName(i) As string
        If Acidentes = "Sustenidos" Then
            For Each CellInf As DataGridViewCell In MemóriaPauta.Rows(2).Cells
                NoteIndexFind = CellInf.ColumnIndex
                For i = 1 To 4
                    If NoteIndexFind = NotaIndex(i) Then
                        NotaChordsName(i) = MemóriaPauta.Columns(NoteIndexFind).Name.ToString
                    End If
                    MsgBox("Tocou a nota :  " & NotaChordsName(i))
                Next i

                Return True

            Next
        End If
        If Acidentes = "Bemóis" Then
            For Each CellInf As DataGridViewCell In MemóriaPauta.Rows(2).Cells
                NoteIndexFind = CellInf.ColumnIndex
                For i = 1 To 4
                    If NoteIndexFind = NotaIndex(i) Then
                        NotaChordsName(i) = MemóriaPauta.Rows(2).Cells.Item(NoteIndexFind).Value.ToString
                    End If
                    MsgBox("Tocou a nota :  " & NotaChordsName(i))
                Next i

                Return True

            Next
        End If
        Exit Function
Erros:
        MsgBox("Detectado Erro na Function Designação da Nota  ....." & ErrorToString())
    End Function

#End Region

#Region "Desenho da Pauta"

    Public Sub CreatePanelPautaWithPictureBox()

        'Construção do BitMap
        'Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage, ComprimentoDaPauta, AlturaDaPauta)
        Dim BitMapPauta As New Bitmap(ComprimentoDaPauta, AlturaDaPauta)
        BitMapPauta.MakeTransparent()

        'Dim RectPautaTotal As New Rectangle(PautaPictureBox.Location.X, PautaPictureBox.Location.Y,
        'PautaPictureBox.Width, PautaPictureBox.Height)

        Dim GrPauta As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPauta
            Try
                'Construção das 10 Linhas 
                Dim ELS As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'EspaçamentoLinhasSuperiores
                Dim ELI As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'EspaçamentoLinhasInferiores
                Dim ISup As Integer = CInt((PautaPictureBox.Height / 6)) ' Inicio das Superiores
                Dim IInf As Integer = CInt((2.5 * PautaPictureBox.Height / 6)) ' Inicio das Inferiores

                'Horizontais
                Dim X1, X2, Y1, Y2 As Integer
                Dim CoordenadasYTotais(100) As Decimal
                Dim CoordenadaYdasLinhas(30) As Integer
                For i = 1 To 30
                    X1 = 15
                    X2 = PautaPictureBox.Width - 15
                    Dim Fonte As Font = New Font("Arial", 6, FontStyle.Regular)
                    Dim FonteDim As Integer = Fonte.Height
                    If i <= 5 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                      brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 5 And i <= 10 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 10 And i <= 15 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1
                        'If i <= 15 Then CoordenadaYdasLinhasSuperiores(i) = Y1

                    ElseIf i > 15 And i <= 20 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 20 And i <= 25 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 25 And i <= 30 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    End If
                Next

                'Verticais
                For j = 0 To PautaPictureBox.Width Step 200
                    X1 = 15 + j
                    X2 = X1
                    Y1 = CoordenadaYdasLinhas(6)
                    Y2 = CoordenadaYdasLinhas(25)
                    If j = 0 Or j = PautaPictureBox.Width Then
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawLine(Pens.Black, X1 + 1, Y1, X2 + 1, Y2)
                    Else
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                    End If
                Next

                'Claves
                GrPauta.CompositingQuality = CompositingQuality.HighQuality
                'Declaração dos ficheiros originais
                Dim ClaveSolDimH As Integer = My.Resources._000xSSClaveDeSol24x48.Height
                Dim ClaveSolDimW As Integer = My.Resources._000xSSClaveDeSol24x48.Width
                Dim ClaveFáDimH As Integer = My.Resources._000xSSClaveDeFa.Height
                Dim ClaveFáDimW As Integer = My.Resources._000xSSClaveDeFa.Width

                Dim PtClaveSol As New Point(CInt(15), CInt(CoordenadaYdasLinhas(9) - ClaveSolDimH / 2))
                Dim SzClaveSol As New Size(ClaveSolDimW, ClaveSolDimH)
                Dim RectClaveSol As New Rectangle(PtClaveSol, SzClaveSol)
                'Para Obter transparencia nos icons
                'Dim BitTempSol As New Bitmap(My.Resources.Clave_de_sol_32x48.ToBitmap)
                'BitTempSol.MakeTransparent()
                'GrPauta.DrawImage(BitTempSol, RectClaveSol)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeSol24x48, RectClaveSol)

                Dim PtClaveFá As New Point(CInt(15), CInt(CoordenadaYdasLinhas(22) - ClaveFáDimH / 2))
                Dim SzClaveFá As New Size(ClaveFáDimW, ClaveFáDimH)
                Dim RectClaveFá As New Rectangle(PtClaveFá, SzClaveFá)
                'Para Obter transparencia nos icons
                'Dim BitTempFá As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTempFá.MakeTransparent()
                'GrPauta.DrawImage(BitTempFá, RectClaveFá)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeFa, RectClaveFá)

                'Para Obter transparencia nos icons - não necessário se os icons já tiverem essa propriedade
                'Como é o caso dos que fiz
                'Dim BitTemp As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTemp.MakeTransparent()
                'Gr.DrawImage(BitTemp, PtClaveFá)

                'Coordenada do inicio da musica
                CoordenadaXSup = 20 : CoordenadaXInf = 20
                'Imagem a reter no background da picture
                PautaPictureBox.BackgroundImage = BitMapPauta
            Catch ex As Exception
            Finally
                'BitMapPauta.Save(My.Resources.ResourceManager.GetString(My.Resources.PautaBmp.ToString))
                .Dispose()
            End Try
        End With

        'Associar o bitmap á picture
        BitMapPauta = CType(PautaPictureBox.BackgroundImage, Bitmap)
        'Associar a pauta original como primeiro bitmap das matrizes de bitmaps de memória do que se vai teclando

        BitmapMemPautaSup(0) = BitMapPauta ' Para memória futura
        BitmapMemPautaInf(0) = BitMapPauta
    End Sub

    Private Sub ReconstruçãoDaPautaVazia()

        'REConstrução do BitMap

        Dim BitMapPauta As New Bitmap(ComprimentoDaPauta, AlturaDaPauta)
        BitMapPauta.MakeTransparent()

        'Dim RectPautaTotal As New Rectangle(PautaPictureBox.Location.X, PautaPictureBox.Location.Y,
        '                                    PautaPictureBox.Width, PautaPictureBox.Height)

        Dim GrPauta As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPauta
            Try
                'Construção das 10 Linhas 
                Dim ELS As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'EspaçamentoLinhasSuperiores
                Dim ELI As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'EspaçamentoLinhasInferiores
                Dim ISup As Integer = CInt((PautaPictureBox.Height / 6)) ' Inicio das Superiores
                Dim IInf As Integer = CInt((2.5 * PautaPictureBox.Height / 6)) ' Inicio das Inferiores

                'Horizontais
                Dim X1, X2, Y1, Y2 As Integer
                Dim CoordenadasYTotais(100) As Decimal
                Dim CoordenadaYdasLinhas(30) As Integer
                For i = 1 To 30
                    X1 = 15
                    X2 = PautaPictureBox.Width - 15
                    Dim Fonte As Font = New Font("Arial", 6, FontStyle.Regular)
                    Dim FonteDim As Integer = Fonte.Height
                    If i <= 5 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                      brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 5 And i <= 10 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 10 And i <= 15 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1
                        'If i <= 15 Then CoordenadaYdasLinhasSuperiores(i) = Y1

                    ElseIf i > 15 And i <= 20 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 20 And i <= 25 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 25 And i <= 30 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    End If
                Next

                'Verticais
                For j = 0 To PautaPictureBox.Width Step 200
                    X1 = 15 + j
                    X2 = X1
                    Y1 = CoordenadaYdasLinhas(6)
                    Y2 = CoordenadaYdasLinhas(25)
                    If j = 0 Or j = PautaPictureBox.Width Then
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawLine(Pens.Black, X1 + 1, Y1, X2 + 1, Y2)
                    Else
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                    End If
                Next

                'Claves
                GrPauta.CompositingQuality = CompositingQuality.HighQuality
                'Declaração dos ficheiros originais
                Dim ClaveSolDimH As Integer = My.Resources._000xSSClaveDeSol24x48.Height
                Dim ClaveSolDimW As Integer = My.Resources._000xSSClaveDeSol24x48.Width
                Dim ClaveFáDimH As Integer = My.Resources._000xSSClaveDeFa.Height
                Dim ClaveFáDimW As Integer = My.Resources._000xSSClaveDeFa.Width

                Dim PtClaveSol As New Point(CInt(15), CInt(CoordenadaYdasLinhas(9) - ClaveSolDimH / 2))
                Dim SzClaveSol As New Size(ClaveSolDimW, ClaveSolDimH)
                Dim RectClaveSol As New Rectangle(PtClaveSol, SzClaveSol)
                'Para Obter transparencia nos icons
                'Dim BitTempSol As New Bitmap(My.Resources.Clave_de_sol_32x48.ToBitmap)
                'BitTempSol.MakeTransparent()
                'GrPauta.DrawImage(BitTempSol, RectClaveSol)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeSol24x48, RectClaveSol)

                Dim PtClaveFá As New Point(CInt(15), CInt(CoordenadaYdasLinhas(22) - ClaveFáDimH / 2))
                Dim SzClaveFá As New Size(ClaveFáDimW, ClaveFáDimH)
                Dim RectClaveFá As New Rectangle(PtClaveFá, SzClaveFá)
                'Para Obter transparencia nos icons
                'Dim BitTempFá As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTempFá.MakeTransparent()
                'GrPauta.DrawImage(BitTempFá, RectClaveFá)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeFa, RectClaveFá)

                'Para Obter transparencia nos icons - não necessário se os icons já tiverem essa propriedade
                'Como é o caso dos que fiz
                'Dim BitTemp As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTemp.MakeTransparent()
                'Gr.DrawImage(BitTemp, PtClaveFá)

                'Coordenada do inicio da musica
                CoordenadaXSup = 20 : CoordenadaXInf = 20
                'Imagem a reter no background da picture
                PautaPictureBox.BackgroundImage = BitMapPauta
            Catch ex As Exception
                MsgBox(ex.ToString)
            Finally
                'BitMapPauta.Save(My.Resources.ResourceManager.GetString(My.Resources.PautaBmp.ToString))
                'Associar a pauta original como primeiro bitmap das matrizes de bitmaps de memória do que se vai teclando
                'BitmapMemPautaSup(0) = BitMapPauta ' Para memória futura
                'BitmapMemPautaInf(0) = BitMapPauta
                .Dispose()
            End Try
        End With

    End Sub

    Private Sub ReconstruçãoDaPautaVaziaParaRichText()

        'REConstrução do BitMap
        'Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage, ComprimentoDaPauta, AlturaDaPauta)
        Dim BitMapPauta As New Bitmap(ComprimentoDaPauta, AlturaDaPauta)
        BitMapPauta.MakeTransparent()

        'Dim RectPautaTotal As New Rectangle(PautaPictureBox.Location.X, PautaPictureBox.Location.Y,
        '                                    PautaPictureBox.Width, PautaPictureBox.Height)

        Dim GrPauta As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPauta
            Try
                'Construção das 10 Linhas 
                Dim ELS As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'EspaçamentoLinhasSuperiores
                Dim ELI As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'EspaçamentoLinhasInferiores
                Dim ISup As Integer = CInt((PautaPictureBox.Height / 6)) ' Inicio das Superiores
                Dim IInf As Integer = CInt((2.5 * PautaPictureBox.Height / 6)) ' Inicio das Inferiores

                'Horizontais
                Dim X1, X2, Y1, Y2 As Integer
                Dim CoordenadasYTotais(100) As Decimal
                Dim CoordenadaYdasLinhas(30) As Integer
                For i = 1 To 30
                    X1 = 15
                    X2 = PautaPictureBox.Width - 15
                    Dim Fonte As Font = New Font("Arial", 6, FontStyle.Regular)
                    Dim FonteDim As Integer = Fonte.Height
                    If i <= 5 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                      brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 5 And i <= 10 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 10 And i <= 15 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1
                        'If i <= 15 Then CoordenadaYdasLinhasSuperiores(i) = Y1

                    ElseIf i > 15 And i <= 20 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 20 And i <= 25 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 25 And i <= 30 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    End If
                Next

                'Verticais
                For j = 0 To PautaPictureBox.Width Step 200
                    X1 = 15 + j
                    X2 = X1
                    Y1 = CoordenadaYdasLinhas(6)
                    Y2 = CoordenadaYdasLinhas(25)
                    If j = 0 Or j = PautaPictureBox.Width Then
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawLine(Pens.Black, X1 + 1, Y1, X2 + 1, Y2)
                    Else
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                    End If
                Next

                'Claves
                GrPauta.CompositingQuality = CompositingQuality.HighQuality
                'Declaração dos ficheiros originais
                Dim ClaveSolDimH As Integer = My.Resources._000xSSClaveDeSol24x48.Height
                Dim ClaveSolDimW As Integer = My.Resources._000xSSClaveDeSol24x48.Width
                Dim ClaveFáDimH As Integer = My.Resources._000xSSClaveDeFa.Height
                Dim ClaveFáDimW As Integer = My.Resources._000xSSClaveDeFa.Width

                Dim PtClaveSol As New Point(CInt(15), CInt(CoordenadaYdasLinhas(9) - ClaveSolDimH / 2))
                Dim SzClaveSol As New Size(ClaveSolDimW, ClaveSolDimH)
                Dim RectClaveSol As New Rectangle(PtClaveSol, SzClaveSol)
                'Para Obter transparencia nos icons
                'Dim BitTempSol As New Bitmap(My.Resources.Clave_de_sol_32x48.ToBitmap)
                'BitTempSol.MakeTransparent()
                'GrPauta.DrawImage(BitTempSol, RectClaveSol)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeSol24x48, RectClaveSol)

                Dim PtClaveFá As New Point(CInt(15), CInt(CoordenadaYdasLinhas(22) - ClaveFáDimH / 2))
                Dim SzClaveFá As New Size(ClaveFáDimW, ClaveFáDimH)
                Dim RectClaveFá As New Rectangle(PtClaveFá, SzClaveFá)
                'Para Obter transparencia nos icons
                'Dim BitTempFá As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTempFá.MakeTransparent()
                'GrPauta.DrawImage(BitTempFá, RectClaveFá)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeFa, RectClaveFá)

                'Para Obter transparencia nos icons - não necessário se os icons já tiverem essa propriedade
                'Como é o caso dos que fiz
                'Dim BitTemp As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTemp.MakeTransparent()
                'Gr.DrawImage(BitTemp, PtClaveFá)

                'Coordenada do inicio da musica
                CoordenadaXSup = 20 : CoordenadaXInf = 20
                'Usando o clipboard
                Clipboard.SetImage(BitMapPauta)
                PautaRichTextBox.Paste()
            Catch ex As Exception
            Finally
                'BitMapPauta.Save(My.Resources.ResourceManager.GetString(My.Resources.PautaBmp.ToString))
                .Dispose()
            End Try
        End With
        '        Exit Sub
        'Erros:
        '        MsgBox("Erro Detectado na  Sub CreatePanelPautaWithPictureBox..." & ErrorToString())
    End Sub

    Public Sub CriarPautaSuperiorBitmap(ByVal Sender As Object, ByVal e As EventArgs)

        'Construção do BitMap
        Dim RectPautaTotal As New Rectangle(PautaPictureBox.Location.X, PautaPictureBox.Location.Y,
                PautaPictureBox.Width, PautaPictureBox.Height)
        Dim RectPautaSup As New Rectangle(PautaPictureBox.Location.X, PautaPictureBox.Location.Y,
                PautaPictureBox.Width, CInt(PautaPictureBox.Height / 2))
        Dim RectPautaInf As New Rectangle(PautaPictureBox.Location.X, PautaPictureBox.Location.Y + CInt(PautaPictureBox.Height / 2),
                PautaPictureBox.Width, CInt(PautaPictureBox.Height / 2))
        Dim BitMapPautaSup As New Bitmap(PautaPictureBox.BackgroundImage, ComprimentoDaPauta, CInt(AlturaDaPauta / 2))
        Dim BitMapPauta As New Bitmap(ComprimentoDaPauta, AlturaDaPauta, format:=Imaging.PixelFormat.Format32bppArgb)
        BitMapPauta.MakeTransparent()

        Dim GrPauta As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPauta
            Try
                'Construção das 10 Linhas 
                Dim ELS As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'Espaçamento Linhas Superiores
                Dim ELI As Integer = CInt((PautaPictureBox.Height / 6) / 5) 'Espaçamento Linhas Inferiores
                Dim ISup As Integer = CInt((PautaPictureBox.Height / 6)) ' Inicio das Superiores
                Dim IInf As Integer = CInt((2.5 * PautaPictureBox.Height / 6)) ' Inicio das Inferiores

                'Horizontais
                Dim X1, X2, Y1, Y2 As Integer
                Dim CoordenadasYTotais(100) As Decimal
                Dim CoordenadaYdasLinhas(30) As Integer
                For i = 1 To 30
                    X1 = 15
                    X2 = PautaPictureBox.Width - 15
                    Dim Fonte As Font = New Font("Arial", 6, FontStyle.Regular)
                    Dim FonteDim As Integer = Fonte.Height
                    If i <= 5 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                      brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 5 And i <= 10 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 10 And i <= 15 Then
                        Y1 = CInt(i * ELS) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                       brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1
                        'If i <= 15 Then CoordenadaYdasLinhasSuperiores(i) = Y1

                    ElseIf i > 15 And i <= 20 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 20 And i <= 25 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    ElseIf i > 25 And i <= 30 Then
                        Y1 = CInt(i * ELI) 'Com i= 1 a 1ª linha - ELS 
                        Y2 = Y1
                        GrPauta.DrawLine(Pens.WhiteSmoke, X1, Y1, X2, Y2)
                        GrPauta.DrawString(Str(Math.Abs(Val(i - 16))), font:=Fonte,
                                           brush:=Brushes.Brown, x:=-1, y:=CInt(Y1 - (FonteDim) / 2))
                        CoordenadaYdasLinhas(i) = Y1

                    End If
                Next

                'Verticais
                For j = 0 To PautaPictureBox.Width Step 200
                    X1 = 15 + j
                    X2 = X1
                    Y1 = CoordenadaYdasLinhas(6)
                    Y2 = CoordenadaYdasLinhas(25)
                    If j = 0 Or j = PautaPictureBox.Width Then
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                        GrPauta.DrawLine(Pens.Black, X1 + 1, Y1, X2 + 1, Y2)
                    Else
                        GrPauta.DrawLine(Pens.Black, X1, Y1, X2, Y2)
                    End If
                Next

                'Claves
                GrPauta.CompositingQuality = CompositingQuality.HighQuality
                'Declaração dos ficheiros originais
                Dim ClaveSolDimH As Integer = My.Resources._000xSSClaveDeSol24x48.Height
                Dim ClaveSolDimW As Integer = My.Resources._000xSSClaveDeSol24x48.Width
                Dim ClaveFáDimH As Integer = My.Resources._000xSSClaveDeFa.Height
                Dim ClaveFáDimW As Integer = My.Resources._000xSSClaveDeFa.Width

                Dim PtClaveSol As New Point(CInt(15), CInt(CoordenadaYdasLinhas(9) - ClaveSolDimH / 2))
                Dim SzClaveSol As New Size(ClaveSolDimW, ClaveSolDimH)
                Dim RectClaveSol As New Rectangle(PtClaveSol, SzClaveSol)
                'Para Obter transparencia nos icons
                'Dim BitTempSol As New Bitmap(My.Resources.Clave_de_sol_32x48.ToBitmap)
                'BitTempSol.MakeTransparent()
                'GrPauta.DrawImage(BitTempSol, RectClaveSol)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeSol24x48, RectClaveSol)

                Dim PtClaveFá As New Point(CInt(15), CInt(CoordenadaYdasLinhas(22) - ClaveFáDimH / 2))
                Dim SzClaveFá As New Size(ClaveFáDimW, ClaveFáDimH)
                Dim RectClaveFá As New Rectangle(PtClaveFá, SzClaveFá)
                'Para Obter transparencia nos icons
                'Dim BitTempFá As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTempFá.MakeTransparent()
                'GrPauta.DrawImage(BitTempFá, RectClaveFá)
                GrPauta.DrawIcon(My.Resources._000xSSClaveDeFa, RectClaveFá)

                'Para Obter transparencia nos icons - não necessário se os icons já tiverem essa propriedade
                'Como é o caso dos que fiz
                'Dim BitTemp As New Bitmap(My.Resources.Clave_de_Fá_32b32x48.ToBitmap)
                'BitTemp.MakeTransparent()
                'Gr.DrawImage(BitTemp, PtClaveFá)

                'Coordenada do inicio da musica
                CoordenadaXSup = 20 : CoordenadaXInf = 20
                'Imagem a reter no background da picture
                PautaPictureBox.BackgroundImage = BitMapPauta
            Catch ex As Exception
            Finally
                'BitMapPauta.Save(My.Resources.ResourceManager.GetString(My.Resources.PautaBmp.ToString))
                .Dispose()
            End Try
        End With

        'Associar o bitmap á picture
        BitMapPauta = CType(PautaPictureBox.BackgroundImage, Bitmap)
        'Associar a pauta original como primeiro bitmap das matrizes de bitmaps de memória do que se vai teclando

        BitmapMemPautaSup(0) = BitMapPauta ' Para memória futura
        BitmapMemPautaInf(0) = BitMapPauta
    End Sub

#End Region

#Region "Obtenção da coordenada Y através do nome da nota - DatagridView"
    Public Function ObtençãoCoordenadaYSup(ByVal NotaSolo As String, ByVal CoordenadaXSup As Integer) As Boolean
        'On Error Resume Next
        On Error GoTo Erros
        Dim NomeDaNotaPianoSup As String = Me.NotaSolo
        If Mid(NomeDaNotaPianoSup, 1, 1) = "#" Then
            AcidSustenido = True
        Else
            AcidSustenido = False
        End If
        If Mid(NomeDaNotaPianoSup, 1, 1) = "b" Then
            AcidBemol = True
        Else
            AcidBemol = False
        End If
        Dim NotasFind As String
        Dim NotaIndex As Integer
        If AcidSustenido = True And AcidBemol = False Then
            For Each ColumnsFind As DataGridViewColumn In MemóriaPauta.Columns
                NotasFind = ColumnsFind.Name
                If NotasFind = NomeDaNotaPianoSup Then
                    NotaIndex = ColumnsFind.Index
                    Dim CoordenadaY1 As Integer = CInt(MemóriaPauta.Rows(1).Cells.Item(NotaIndex).Value)
                    'MsgBox("Y =   " & CoordenadaY1)
                    'Segue para desenhar
                    'Para memória  "Privada" da posição
                    CoordenadaYSup = CoordenadaY1
                    ColocaçãoEmPautaWithPictureBoxPSup(CoordenadaXSup, CoordenadaY1, AcidSustenido, AcidBemol)
                    Return True
                End If
            Next
        End If
        If AcidBemol = True And AcidSustenido = False Then
            For Each Célula As DataGridViewCell In MemóriaPauta.Rows.Item(3).Cells
                NotasFind = Célula.Value.ToString
                If NotasFind = NomeDaNotaPianoSup Then
                    NotaIndex = Célula.ColumnIndex
                    Dim CoordenadaY1 As Integer = CInt(MemóriaPauta.Rows(4).Cells.Item(NotaIndex).Value)
                    'MsgBox("Y =   " & CoordenadaY1)
                    'Segue para desenhar
                    'Para memória  "Privada" da posição
                    CoordenadaYSup = CoordenadaY1
                    ColocaçãoEmPautaWithPictureBoxPSup(CoordenadaXSup, CoordenadaY1, AcidSustenido, AcidBemol)
                    Return True
                End If
            Next

        End If
        If AcidBemol = False And AcidSustenido = False Then  '  Por  defeito  sustenidos
            For Each ColumnsFind As DataGridViewColumn In MemóriaPauta.Columns
                NotasFind = ColumnsFind.Name
                If NotasFind = NomeDaNotaPianoSup Then
                    NotaIndex = ColumnsFind.Index
                    Dim CoordenadaY1 As Integer = CInt(MemóriaPauta.Rows(1).Cells.Item(NotaIndex).Value)
                    'MsgBox("Y =   " & CoordenadaY1)
                    'Segue para desenhar
                    'Para memória  "Privada" da posição
                    CoordenadaYSup = CoordenadaY1
                    ColocaçãoEmPautaWithPictureBoxPSup(CoordenadaXSup, CoordenadaY1, AcidSustenido, AcidBemol)
                    Return True
                End If
            Next

        End If
        Return False

        Exit Function
Erros:
        MsgBox("Detectado um erro na Function ObtençãoCoordenadaYSup...." & ErrorToString())
    End Function
    Private Function ObtençãoCoordenadaYInf(ByVal NotaChords As String, ByVal CoordenadaXInf As Integer) As Boolean
        'On Error Resume Next
        On Error GoTo Erros
        Dim NomeDaNotaPianoInf As String = Me.NotaChords
        If Mid(NomeDaNotaPianoInf, 1, 1) = "#" Then
            AcidSustenido = True
        Else
            AcidSustenido = False
        End If
        If Mid(NomeDaNotaPianoInf, 1, 1) = "b" Then
            AcidBemol = True
        Else
            AcidBemol = False
        End If
        Dim NotasFindChords As String
        Dim NotaIndexChords As Integer
        If AcidSustenido = True And AcidBemol = False Then
            For Each ColumnsFindChords As DataGridViewColumn In MemóriaPauta.Columns
                NotasFindChords = ColumnsFindChords.Name
                If NotasFindChords = NomeDaNotaPianoInf Then
                    NotaIndexChords = ColumnsFindChords.Index
                    Dim CoordenadaY2 As Integer = CInt(MemóriaPauta.Rows(2).Cells.Item(NotaIndexChords).Value)
                    'MsgBox("Y =   " & CoordenadaY2)
                    'Segue para desenhar
                    'Para memória  "Privada" da posição
                    CoordenadaYInf = CoordenadaY2
                    ColocaçãoEmPautaWithPictureBoxPInf(CoordenadaXInf, CoordenadaY2, AcidSustenido, AcidBemol)
                    Return True
                End If
            Next
        End If
        If AcidBemol = True And AcidSustenido = False Then
            For Each Célula As DataGridViewCell In MemóriaPauta.Rows.Item(3).Cells
                NotasFindChords = Célula.Value.ToString
                If NotasFindChords = NomeDaNotaPianoInf Then
                    NotaIndexChords = Célula.ColumnIndex
                    Dim CoordenadaY2 As Integer = CInt(MemóriaPauta.Rows(5).Cells.Item(NotaIndexChords).Value)
                    'MsgBox("Y =   " & CoordenadaY1)
                    'Segue para desenhar
                    'Para memória  "Privada" da posição
                    CoordenadaYInf = CoordenadaY2
                    ColocaçãoEmPautaWithPictureBoxPInf(CoordenadaXInf, CoordenadaY2, AcidSustenido, AcidBemol)
                    Return True
                End If
            Next
        End If
        If AcidBemol = False And AcidSustenido = False Then '  Por  defeito  sustenidos
            For Each ColumnsFind As DataGridViewColumn In MemóriaPauta.Columns
                NotasFindChords = ColumnsFind.Name
                If NotasFindChords = NomeDaNotaPianoInf Then
                    NotaIndexChords = ColumnsFind.Index
                    Dim CoordenadaY2 As Integer = CInt(MemóriaPauta.Rows(2).Cells.Item(NotaIndexChords).Value)
                    'MsgBox("Y =   " & CoordenadaY1)
                    'Segue para desenhar
                    'Para memória  "Privada" da posição
                    CoordenadaYInf = CoordenadaY2
                    ColocaçãoEmPautaWithPictureBoxPInf(CoordenadaXInf, CoordenadaY2, AcidSustenido, AcidBemol)
                    Return True
                End If
            Next

        End If
        Return False

        Exit Function
Erros:
        MsgBox("Detectado um erro na Function ObtençãoCoordenadaYInf...." & ErrorToString())

    End Function

    Private Function ObtençãoCoordenadaYInfChords(ByVal NotaChordsName As String(), ByVal CoordenadaXInf As Integer) As Boolean
        'On Error Resume Next
        On Error GoTo Erros
        Dim i As Integer
        For i = 1 To 4
            If Not IsNothing(NotaChordsName(i)) Then ' Existem acordes de três e de quatro notas
                Dim NomeDaNotaPianoInf As String = NotaChordsName(i)
                If Mid(NomeDaNotaPianoInf, 1, 1) = "#" Then
                    AcidSustenido = True
                Else
                    AcidSustenido = False
                End If
                If Mid(NomeDaNotaPianoInf, 1, 1) = "b" Then
                    AcidBemol = True
                Else
                    AcidBemol = False
                End If
                Dim NotasFindChords As String
                Dim NotaIndexChords As Integer
                If AcidSustenido = True And AcidBemol = False Then
                    For Each ColumnsFindChords As DataGridViewColumn In MemóriaPauta.Columns
                        NotasFindChords = ColumnsFindChords.Name
                        If NotasFindChords = NomeDaNotaPianoInf Then
                            NotaIndexChords = ColumnsFindChords.Index
                            Dim CoordenadaY2 As Integer = CInt(MemóriaPauta.Rows(1).Cells.Item(NotaIndexChords).Value)
                            'MsgBox("Y =   " & CoordenadaY2)
                            'Segue para desenhar
                            'Para memória  "Privada" da posição
                            CoordenadaYInf = CoordenadaY2
                            ColocaçãoEmPautaWithPictureBoxPInf(CoordenadaXInf, CoordenadaY2, AcidSustenido, AcidBemol)
                            Return True
                        End If
                    Next
                End If
                If AcidBemol = True And AcidSustenido = False Then
                    For Each Célula As DataGridViewCell In MemóriaPauta.Rows.Item(2).Cells
                        NotasFindChords = Célula.Value.ToString
                        If NotasFindChords = NomeDaNotaPianoInf Then
                            NotaIndexChords = Célula.ColumnIndex
                            Dim CoordenadaY2 As Integer = CInt(MemóriaPauta.Rows(1).Cells.Item(NotaIndexChords).Value)
                            'MsgBox("Y =   " & CoordenadaY1)
                            'Segue para desenhar
                            'Para memória  "Privada" da posição
                            CoordenadaYInf = CoordenadaY2
                            ColocaçãoEmPautaWithPictureBoxPInf(CoordenadaXInf, CoordenadaY2, AcidSustenido, AcidBemol)
                            Return True
                        End If
                    Next
                End If
                If AcidBemol = False And AcidSustenido = False Then
                    For Each ColumnsFind As DataGridViewColumn In MemóriaPauta.Columns
                        NotasFindChords = ColumnsFind.Name
                        If NotasFindChords = NomeDaNotaPianoInf Then
                            NotaIndexChords = ColumnsFind.Index
                            Dim CoordenadaY2 As Integer = CInt(MemóriaPauta.Rows(1).Cells.Item(NotaIndexChords).Value)
                            'MsgBox("Y =   " & CoordenadaY1)
                            'Segue para desenhar
                            'Para memória  "Privada" da posição
                            CoordenadaYInf = CoordenadaY2
                            ColocaçãoEmPautaWithPictureBoxPInf(CoordenadaXInf, CoordenadaY2, AcidSustenido, AcidBemol)
                            Return True
                        End If
                    Next
                End If
            End If
        Next i
        Return False

        Exit Function
Erros:
        MsgBox("Detectado um erro na Function ObtençãoCoordenadaYInfChords...." & ErrorToString())

    End Function
#End Region

#Region "Colocação em Pauta"

    Public Sub ColocaçãoEmPautaWithPictureBoxPSup(ByVal CoordenadaXSup As Integer, ByVal CoordenadaY1 As Integer, ByVal AcidSustenido As Boolean, ByVal AcidBemol As Boolean) 'Handles PautaRichTextBox.Paint
        'On Error GoTo Erros
        'ªªªªªªªªªªªªªªªªªªªªªªªSolução : escrever no  PictureBox.BackgroundImage através do bitmap
        'Existe um factor de correcção = ???  para já
        'Na richtext deve  dar  para  apagar  com o UNDO ????? mas......
        'Dim CorrectionIcon As Integer = 10 'CInt(Val(TextInput.Text))
        Dim NotaDimH As Integer = 48
        Dim NotaDimW As Integer = 24 'My.Resources._001nCSSemiBreve.Width
        Dim AcidenteH As Integer = My.Resources._000wSSSus.Height
        Dim PtNotaCurrente As New Point(CoordenadaXSup + EspassamentoEntreNotas, CInt(CoordenadaY1 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente As New Point(CoordenadaXSup + EspassamentoEntreNotas - 5, CInt(CoordenadaY1 - AcidenteH / 2)) '- CorrectionIcon))
        Dim SzNotaCurrente As New Size(24, 48) ', 32
        Dim SzAcidenteNotaCurrente As New Size(20, 20)
        Dim RectNotaCurrente As New Rectangle(PtNotaCurrente, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente As New Rectangle(AcidentePtNotaCurrente, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen As Point = RectNotaCurrente.Location
        'O indice  seguinte  basea-se na posição da CoordenadaXInf
        Dim IndiceSup As Integer = CInt((CoordenadaXSup - 40) / 20) ' BitmapMemPautaInf(IndiceInf)   AS  BITMAP 
        Dim IndiceSupMáx As Integer = EspassamentoEntreNotas * MemMáxima
        Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXSup / IndiceSupMáx))
        Dim CorrecçãoAdaptativa As Integer = CoordenadaXSup - (IndiceSupMáx * Iterator)
        'Alterações gráficas produzidas pelo teclado sup
        Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage)
        Dim GrPautaSup As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPautaSup ' Comtemplando  as três hipóteses
            Try
                .SmoothingMode = SmoothingMode.HighQuality
                .CompositingQuality = CompositingQuality.HighQuality
                If AcidSustenido = True And AcidBemol = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente)
                    .DrawIcon(CType(IconsTeclasCollection.Item(Indíce), Icon), RectNotaCurrente)
                    AcidSustenido = False
                End If
                If AcidBemol = True And AcidSustenido = False Then
                    GrPautaSup.DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente)
                    GrPautaSup.DrawIcon(CType(IconsTeclasCollection.Item(Indíce), Icon), RectNotaCurrente)
                    AcidBemol = False
                End If
                If AcidSustenido = False And AcidBemol = False Then
                    GrPautaSup.DrawIcon(CType(IconsTeclasCollection.Item(Indíce), Icon), RectNotaCurrente)
                End If
                Me.LabelInfo2.Text = CoordenadaXSup + 20 & "X" & CoordenadaY1 - NotaDimH / 2
                '================Memorização   pauta sup
                PautaPictureBox.BackgroundImage = BitMapPauta
                'O Indice O representa uma pauta virgem pelo que a sequencia de bitmaps aqui deve começar em 1
                If IndiceSup > 0 Then ' Assegura que não está fora da pauta
                    If IndiceSup < MemMáxima - 1 Then ' Primeiras notas até  mem maxima > 10, 20 ou 50 ... 
                        BitmapMemPautaSup(IndiceSup) = BitMapPauta
                        MemPautaSup = IndiceSup
                        'MsgBox("Atribuição de MemPautaSup = IndiceSup + 1  :  " & MemPautaSup)
                        'lblChords(12).Text = "MemPautaSupN= " & MemPautaSup
                    End If

                    If IndiceSup >= MemMáxima - 1 Then
                        'A ideia é reiniciar os bitmaps "memória" a partir do 1
                        'Sendo que o bitmap memória 0 passa a ser o anterior nº mem máxima
                        If MemPautaSup < MemMáxima - 1 Then
                            MemPautaSup = MemPautaSup + 1
                            BitmapMemPautaSup(MemPautaSup) = BitMapPauta
                            'Assegurar a correcção para o resto da pauta
                            'MemPautaSup = (CInt((CorrecçãoAdaptativa) / 20))
                            ' lblChords(12).Text = "MemPautaSupN= " & MemPautaSup
                        End If
                        If MemPautaSup = MemMáxima - 1 Then
                            BitmapMemPautaSup(0) = BitMapPauta
                            'PautaPictureBox.BackgroundImage = BitMapPauta
                            For i = 1 To BitmapMemPautaSup.Count - 1 ' Apagar a memória no bitmap
                                BitmapMemPautaSup(i) = Nothing
                            Next
                            'Assegurar a ocorrencia da  gravação apenas nas  transições
                            MemPautaSup = 0
                            'lblChords(12).Text = "MemPautaSupAZ= " & MemPautaSup
                        End If
                        'If MemPautaSup > MemMáxima - 1 Then
                        '    'MemPautaSup = MemPautaSup + 1
                        '    BitmapMemPautaSup(CInt((CorrecçãoAdaptativa) / 20)) = BitMapPauta
                        '    'Assegurar a correcção para o resto da pauta
                        '    MemPautaSup = (CInt((CorrecçãoAdaptativa) / 20))
                        '    lblChords(12).Text = "MemPautaSupA= " & MemPautaSup
                        'End If
                        'MsgBox("Atribuição de MemPautaSup = (CInt((CorrecçãoAdaptativa) / 20)  :  " & MemPautaSup)
                    End If
                End If
            Catch ex As Exception
                MsgBox(ex.ToString)
            Finally
                GrPautaSup.Dispose()
            End Try
        End With
        'Deslocamento do scroll
        If CoordenadaXSup > 500 Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXSup - 200
        End If
        If CoordenadaXInf < FlLayPanel.HorizontalScroll.Value Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf
        End If
        If CoordenadaXSup >= FlLayPanel.HorizontalScroll.Maximum Then
            Dim Resposta As MsgBoxResult = MsgBox("Chegou ao Final da Pauta . Quer começar de Novo ? ", MsgBoxStyle.OkCancel, "SE RESPONDER SIM VAI APAGAR A PAUTA")
            If Resposta = MsgBoxResult.Ok Then ReconstruçãoDaPautaVazia()
        End If
        'ªªªªªªªªªªªªªªªªªªªªªªªªª
        '        Exit Sub
        'Erros:
        '        MsgBox("Detectado um erro na Sub ColocaçãoEmPautaWithPictureBox...." & ErrorToString())
    End Sub

    Public Sub ColocaçãoEmPautaWithPictureBoxPInf(ByVal CoordenadaXInf As Integer, ByVal CoordenadaY2 As Integer, ByVal AcidSustenido As Boolean, ByVal AcidBemol As Boolean) 'Handles PautaRichTextBox.Paint
        'On Error GoTo Erros
        'Nesta hipótese vai-se  escrever uma nota do acorde  de cada vez o que me parece má  solução para os  acordes 
        'Pelo que esta  rotina  se  vai destinar  simplesmente  aos  solos
        'If ModeKeysDown <> "Chords" Or ModeKeysDown <> "" Then Exit Sub ' conj vazio por  precaução
        '**************************************************************

        Dim NotaDimH As Integer = My.Resources._001nCSSemiBreve.Height
        Dim NotaDimW As Integer = My.Resources._001nCSSemiBreve.Width
        Dim AcidenteH As Integer = My.Resources._000wSSSus.Height
        Dim PtNotaCurrente As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaY2 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaY2 - AcidenteH / 2)) '- CorrectionIcon))
        Dim SzNotaCurrente As New Size(24, 32)
        Dim SzAcidenteNotaCurrente As New Size(20, 20)
        Dim RectNotaCurrente As New Rectangle(PtNotaCurrente, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente As New Rectangle(AcidentePtNotaCurrente, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen As Point = RectNotaCurrente.Location
        'O indice  seguinte  basea-se na posição da CoordenadaXInf
        Dim IndiceInf As Integer = CInt((CoordenadaXInf - 40) / 20) ' BitmapMemPautaInf(IndiceInf)   AS  BITMAP 
        Dim IndiceInfMáx As Integer = EspassamentoEntreNotas * MemMáxima
        Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXInf / IndiceInfMáx))
        Dim CorrecçãoAdaptativa As Integer = CoordenadaXInf - (IndiceInfMáx * Iterator)
        'Alterações gráficas produzidas pelo teclado inf
        Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage)
        Dim GrPautaPInf As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPautaPInf ' Comtemplando  as três hipóteses
            Try
                .SmoothingMode = SmoothingMode.HighQuality
                .CompositingQuality = CompositingQuality.HighQuality
                If AcidSustenido = True And AcidBemol = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente)
                    AcidSustenido = False
                End If
                If AcidBemol = True And AcidSustenido = False Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente)
                    AcidBemol = False
                End If
                If AcidSustenido = False And AcidBemol = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente)
                End If
                Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaY2 - NotaDimH / 2

                '================Memorização   pauta INF
                PautaPictureBox.BackgroundImage = BitMapPauta
                'O Indice O representa uma pauta virgem pelo que a sequencia de bitmaps aqui deve começar em 1
                If IndiceInf > 0 Then ' Assegura que não está fora da pauta
                    If IndiceInf < MemMáxima - 1 Then ' Primeiras notas até  mem maxima > 10, 20 ou 50 ... 
                        BitmapMemPautaInf(IndiceInf) = BitMapPauta
                        MemPautaInf = IndiceInf
                        'MsgBox("Atribuição de MemPautaSup = IndiceSup + 1  :  " & MemPautaSup)
                        'lblChords(12).Text = "MemPautaInfN= " & MemPautaInf
                    End If
                    'Quando se  excede as primeiras notas memorizadas "mem maximo!
                    If IndiceInf >= MemMáxima - 1 Then
                        'A ideia é reiniciar os bitmaps "memória" a partir do 1
                        'Sendo que o bitmap memória 0 passa a ser o anterior nº mem máxima
                        If MemPautaInf < MemMáxima - 1 Then
                            MemPautaInf = MemPautaInf + 1
                            BitmapMemPautaInf(MemPautaInf) = BitMapPauta
                            'Assegurar a correcção para o resto da pauta
                            'MemPautaSup = (CInt((CorrecçãoAdaptativa) / 20))
                            'lblChords(12).Text = "MemPautaInfN= " & MemPautaInf
                        End If
                        If MemPautaInf = MemMáxima - 1 Then
                            BitmapMemPautaInf(0) = BitMapPauta
                            'PautaPictureBox.BackgroundImage = BitMapPauta
                            For i = 1 To BitmapMemPautaInf.Count - 1 ' Apagar a memória no bitmap
                                BitmapMemPautaInf(i) = Nothing
                            Next
                            'Assegurar a ocorrencia da  gravação apenas nas  transições
                            MemPautaInf = 0
                            'lblChords(12).Text = "MemPautaInfAZ= " & MemPautaInf
                        End If
                    End If
                End If

            Catch ex As Exception
                MsgBox(ex.ToString)
            Finally
                GrPautaPInf.Dispose()
            End Try
        End With
        'Deslocamento do scroll
        If CoordenadaXInf > 500 Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf - 200
        End If
        If CoordenadaXInf < FlLayPanel.HorizontalScroll.Value Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf
        End If
        If CoordenadaXInf >= FlLayPanel.HorizontalScroll.Maximum Then
            Dim Resposta As MsgBoxResult = MsgBox("Chegou ao Final da Pauta . Quer começar de Novo ? ", MsgBoxStyle.Question, "SE RESPONDER SIM VAI APAGAR A PAUTA")
            If Resposta = MsgBoxResult.Ok Then ReconstruçãoDaPautaVazia()
        End If
        'ªªªªªªªªªªªªªªªªªªªªªªªªª

        Exit Sub
Erros:
        MsgBox("Detectado um erro na Sub ColocaçãoEmPautaWithPictureBox...." & ErrorToString())
    End Sub

#End Region

#Region "Panel of Instruments"
    ''' <summary>
    ''' Create a panel of instruments
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub CreatePanelInstruments()
        FlLayPanel = New FlowLayoutPanel
        With FlLayPanel
            .AutoScroll = True
            .VerticalScroll.Visible = False
            .BorderStyle = BorderStyle.FixedSingle
            .Size = CType(New Point(808, 205), Drawing.Size)
            .Location = New Point(5, 50)
            .FlowDirection = FlowDirection.TopDown
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
        End With
        Me.Controls.Add(FlLayPanel)

        For I As Integer = 0 To lblInstruments.Count - 1
            lblInstruments(I) = New Label
            With lblInstruments(I)
                .Width = 155
                .Font = New Font("Arial", 8, FontStyle.Bold)
                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
                .BorderStyle = BorderStyle.FixedSingle
                .TextAlign = ContentAlignment.MiddleLeft

            End With
            FlLayPanel.Controls.Add(lblInstruments(I))
        Next (I)

        'Standard MIDI Patch Assignments 
        Dim strInstruments() As String =
            {"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
             "004 Rhodes(piano)", "005 Chorused(piano)", "006 Harpsichord", "007 Clavinet", "008 Celesta",
             "009 Glockenspiel", "010 Music(box)", "011 Vibraphone", "012 Marimba", "013 Xylophone", "014 Tubular(bells)",
             "015 Dulcimer", "016 Hammond(organ)", "017 Percussive(organ)", "018 Rock(organ)", "019 Church(organ)",
             "020 Reed(organ)", "021 Accordion", "022 Harmonica", "023 Tango(accordion)", "024 Acoustic guitar (nylon)",
             "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
             "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
             "032 Acoustic bass", "033 Electric bass (finger)", "034 Electric bass (pick)", "035 Fretless bass",
             "036 Slap bass 1", "037 Slap bass 2", "038 Synth bass 1", "039 Synth bass 2", "040 Violin",
             "041 Viola", "042 Cello", "043 Contrabass", "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp",
             "047 Timpani", "048 String ensemble 1", "049 String ensemble 2", "050 Synth.strings(1)", "051 Synth.strings(2)",
             "052 Choir(Aahs)", "053 Voice(Oohs)", "054 Synth(voice)", "055 Orchestra(hit)", "056 Trumpet", "057 Trombone",
             "058 Tuba", "059 Muted(trumpet)", "060 French(horn)", "061 Brass(section)", "062 Synth.brass(1)",
             "063 Synth.brass(2)", "064 Soprano sax", "065 Alto sax", "066 Tenor sax", "067 Baritone sax", "068 Oboe",
             "069 English horn", "070 Bassoon", "071 Clarinet", "072 Piccolo", "073 Flute", "074 Recorder",
             "075 Pan flute", "076 Bottle blow", "077 Shakuhachi", "078 Whistle", "079 Ocarina", "080 Lead 1 (square)",
             "081 Lead 2 (sawtooth)", "082 Lead 3 (calliope lead)", "083 Lead 4 (chiff lead)", "084 Lead 5 (charang)",
             "085 Lead 6 (voice)", "086 Lead 7 (fifths)", "087 Lead 8 (brass + lead)", "088 Pad 1 (new age)",
             "089 Pad 2 (warm)", "090 Pad 3 (polysynth)", "091 Pad 4 (choir)", "092 Pad 5 (bowed)", "093 Pad 6 (metallic)",
             "094 Pad 7 (halo)", "095 Pad 8 (sweep)", "096 FX 1 (rain)", "097 FX 2 (soundtrack)", "098 FX 3 (crystal)",
             "099 FX 4 (atmosphere)", "100 FX 5 (brightness)", "101 FX 6 (goblins)", "102 FX 7 (echoes)", "103 FX 8 (sci-fi)",
             "104 Sitar", "105 Banjo", "106 Shamisen", "107 Koto", "108 Kalimba", "119 Bagpipe", "110 Fiddle", "111 Shanai2",
             "112 Tinkle Bell", "113 Agogo", "114 Steel Drums", "115 Woodblock", "116 Taiko Drum", "117 Melodic Tom",
             "118 Synth Drum2", "119 Reverse Cymbal", "120 Guitar fret noise", "121 Breath noise", "122 Seashore",
             "123 Bird tweet", "124 Telephone ring", "125 Helicopter", "126 Applause", "127 Gunshot"}

        For i = 0 To 127
            lblInstruments(i).Text = strInstruments(i)
        Next
        For I As Integer = 0 To lblInstruments.Count - 1
            AddHandler lblInstruments(I).MouseDown, AddressOf lblInstruments_MouseDown
        Next

    End Sub
    Private Sub lblInstruments_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim Index As Integer = Array.IndexOf(lblInstruments, sender)
        For i = 0 To lblInstruments.Count - 1
            lblInstruments(i).BackColor = Color.Transparent
            lblInstruments(i).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)

        Next
        lblInstruments(Index).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
        lblInstruments(Index).ForeColor = System.Drawing.Color.FromArgb(0, 0, 0)

        Instrument1InMemory = Index
        ChangeInstrument(Instrument1InMemory)
    End Sub
#End Region

#Region "CreateComboBoxSoloInstruments()"
    ''' <summary>
    ''' Create a Combo Box of instruments
    ''' </summary>
    ''' <remarks></remarks>

    Public Sub CreateComboBoxSoloInstruments()
        '*****************Declared at START of sub
        'Dim ChordsComboBoxInstruments As New ComboBox()    
        'Dim LblcomboInfo, LblInstrumInfo As New Label
        ' Create  label info
        With LblcomboInfo
            .AutoSize = True 'Size = CType(New Point(50, 25), Drawing.Size)
            .Location = New Point(255, 565)
            .Font = New Font("Arial", 8, FontStyle.Bold)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BorderStyle = BorderStyle.FixedSingle
            .TextAlign = ContentAlignment.MiddleLeft
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            'Not necessary???
            .Visible = False
        End With
        ' Create  label info
        With LblInstrumInfo
            .AutoSize = True 'Size = CType(New Point(200, 25), Drawing.Size)
            .Location = New Point(250, 566)
            .Font = New Font("Arial", 8, FontStyle.Bold)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .BorderStyle = BorderStyle.FixedSingle
            .TextAlign = ContentAlignment.MiddleLeft
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            'Not necessary???
            .Visible = False
        End With
        'To fill combo items's
        'Note: These Instruments seem to me better for the chords but ...... may be other
        Dim SoloStrInstruments() As String =
                {"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
                 "004 Rhodes(piano)", "005 Chorused(piano)", "006 Harpsichord", "007 Clavinet", "008 Celesta",
                 "009 Glockenspiel", "010 Music(box)", "011 Vibraphone", "012 Marimba", "013 Xylophone", "014 Tubular(bells)",
                 "015 Dulcimer", "016 Hammond(organ)", "017 Percussive(organ)", "018 Rock(organ)", "019 Church(organ)",
                 "020 Reed(organ)", "021 Accordion", "022 Harmonica", "023 Tango(accordion)", "024 Acoustic guitar (nylon)",
                 "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
                 "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
                 "032 Acoustic bass", "033 Electric bass (finger)", "034 Electric bass (pick)", "035 Fretless bass",
                 "036 Slap bass 1", "037 Slap bass 2", "038 Synth bass 1", "039 Synth bass 2", "040 Violin",
                 "041 Viola", "042 Cello", "043 Contrabass", "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp",
                 "047 Timpani", "048 String ensemble 1", "049 String ensemble 2", "050 Synth.strings(1)", "051 Synth.strings(2)",
                 "052 Choir(Aahs)", "053 Voice(Oohs)", "054 Synth(voice)", "055 Orchestra(hit)", "056 Trumpet", "057 Trombone",
                 "058 Tuba", "059 Muted(trumpet)", "060 French(horn)", "061 Brass(section)", "062 Synth.brass(1)",
                 "063 Synth.brass(2)", "064 Soprano sax", "065 Alto sax", "066 Tenor sax", "067 Baritone sax", "068 Oboe",
                 "069 English horn", "070 Bassoon", "071 Clarinet", "072 Piccolo", "073 Flute", "074 Recorder",
                 "075 Pan flute", "076 Bottle blow", "077 Shakuhachi", "078 Whistle", "079 Ocarina", "080 Lead 1 (square)",
                 "081 Lead 2 (sawtooth)", "082 Lead 3 (calliope lead)", "083 Lead 4 (chiff lead)", "084 Lead 5 (charang)",
                 "085 Lead 6 (voice)", "086 Lead 7 (fifths)", "087 Lead 8 (brass + lead)", "088 Pad 1 (new age)",
                 "089 Pad 2 (warm)", "090 Pad 3 (polysynth)", "091 Pad 4 (choir)", "092 Pad 5 (bowed)", "093 Pad 6 (metallic)",
                 "094 Pad 7 (halo)", "095 Pad 8 (sweep)", "096 FX 1 (rain)", "097 FX 2 (soundtrack)", "098 FX 3 (crystal)",
                 "099 FX 4 (atmosphere)", "100 FX 5 (brightness)", "101 FX 6 (goblins)", "102 FX 7 (echoes)", "103 FX 8 (sci-fi)",
                 "104 Sitar", "105 Banjo", "106 Shamisen", "107 Koto", "108 Kalimba", "119 Bagpipe", "110 Fiddle", "111 Shanai2",
                 "112 Tinkle Bell", "113 Agogo", "114 Steel Drums", "115 Woodblock", "116 Taiko Drum", "117 Melodic Tom",
                 "118 Synth Drum2", "119 Reverse Cymbal", "120 Guitar fret noise", "121 Breath noise", "122 Seashore",
                 "123 Bird tweet", "124 Telephone ring", "125 Helicopter", "126 Applause", "127 Gunshot"}

        'ChordsComboBoxInstruments Properties and AutoComplete
        With SoloComboBoxInstruments
            .BeginUpdate()

            .AutoCompleteMode = CType(False, AutoCompleteMode)
            .MaxLength = 0
            .MaxDropDownItems = 30
            .CausesValidation = True
            .SelectedIndex = -1
            .DataSource = SoloStrInstruments
            .Size = CType(New Point(150, 50), Drawing.Size)
            .Location = New Point(450, 565)
            .Text = "Chords Instrument List"
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .ItemHeight = 50
            'DIRECT ASSOCIATION OF COMBOBox ITEMS
            '.Items.AddRange({"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
            ' "024 Acoustic guitar (nylon)", "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
            ' "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
            ' "032 Acoustic bass", "033 Electric bass (finger)", "040 Violin", "041 Viola", "042 Cello", "043 Contrabass",
            ' "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp"})
            .EndUpdate()
        End With
        'Associate new controls to form
        Me.Controls.Add(LblcomboInfo)
        Me.Controls.Add(LblInstrumInfo)
        Me.Controls.Add(SoloComboBoxInstruments)

        'Associate an event with the combobox that was defined as
        '**********************  Private WithEvents ChordsComboBoxInstruments As New ComboBox()

        'This allows in real time to detect a new instrument that is chosen
        AddHandler SoloComboBoxInstruments.TextChanged, AddressOf SoloComboBoxInstruments_TextChanged

        'Allows you to decrypt and undo entries of keyboard characters in the editable part of the ComboBox
        'It is also possible that you can block text editing in this sector but .... I did not find out!
        AddHandler SoloComboBoxInstruments.KeyPress, AddressOf SoloComboBoxInstruments_KeyPress
        AddHandler SoloComboBoxInstruments.KeyUp, AddressOf SoloComboBoxInstruments_KeyUp

        'Note : Other events (MouseDown or MouseMove ) do not function in this situation
        'because it reads the selected instrument only after ( in the second selection )
        'This take me a long time to understand
    End Sub

    Private Sub SoloComboBoxInstruments_KeyUp(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim HeaderText As String = "Solo Instrument List"
        If SoloComboBoxInstruments.Text <> HeaderText Or SoloComboBoxInstruments.Text <> StrSoloInstrument Then
            If StrSoloInstrument <> "" Then
                SoloComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                SoloComboBoxInstruments.SelectedText = StrSoloInstrument
            Else
                SoloComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                SoloComboBoxInstruments.SelectedText = HeaderText
            End If
        End If
    End Sub

    Private Sub SoloComboBoxInstruments_KeyPress(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim HeaderText As String = "Solo Instrument List"
        If SoloComboBoxInstruments.Text <> HeaderText Or SoloComboBoxInstruments.Text <> StrSoloInstrument Then
            If StrSoloInstrument <> "" Then
                SoloComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                SoloComboBoxInstruments.SelectedText = StrSoloInstrument
            Else
                SoloComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                SoloComboBoxInstruments.SelectedText = HeaderText
            End If
        End If
    End Sub

    Private Sub SoloComboBoxInstruments_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim HeaderText As String = "Solo Instrument List"
        Dim Editável As Boolean = False
        If SoloComboBoxInstruments.Text <> HeaderText Then
            For i = 0 To SoloComboBoxInstruments.Items.Count - 1
                If SoloComboBoxInstruments.Text = SoloComboBoxInstruments.Items.Item(i).ToString Then
                    Instrument1InMemory = CInt(Val(Mid(SoloComboBoxInstruments.Text.ToString, 1, 3)))
                    StrSoloInstrument = SoloComboBoxInstruments.Text
                    Instrument1InMemory = CInt(Val(Mid(StrSoloInstrument, 1, 3)))
                    ChangeInstrument(Instrument1InMemory)
                    'Verificação nos labeis
                    LblInstrumInfo.Text = StrSoloInstrument
                    LblcomboInfo.Text = Instrument2InMemory.ToString
                    Editável = True
                End If
            Next i
        ElseIf Editável = False Then
            SoloComboBoxInstruments.Text = HeaderText
        End If
    End Sub

#End Region

#Region "Combo Box of Chords Instruments"
    ''' <summary>
    ''' Create a Combo Box of instruments
    ''' </summary>
    ''' <remarks></remarks>

    Public Sub CreateComboBoxChordsInstruments()
        '*****************Declared at START of sub
        'Dim ChordsComboBoxInstruments As New ComboBox()    
        'Dim LblcomboInfo, LblInstrumInfo As New Label
        ' Create  label info
        'With LblcomboInfo
        '    .AutoSize = True 'Size = CType(New Point(50, 25), Drawing.Size)
        '    .Location = New Point(255, 265)
        '    .Font = New Font("Arial", 8, FontStyle.Bold)
        '    .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
        '    .BorderStyle = BorderStyle.FixedSingle
        '    .TextAlign = ContentAlignment.MiddleLeft
        '    .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
        '    'Not necessary???
        '    .Visible = False
        'End With
        '' Create  label info
        'With LblInstrumInfo
        '    .AutoSize = True 'Size = CType(New Point(200, 25), Drawing.Size)
        '    .Location = New Point(350, 265)
        '    .Font = New Font("Arial", 8, FontStyle.Bold)
        '    .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
        '    .BorderStyle = BorderStyle.FixedSingle
        '    .TextAlign = ContentAlignment.MiddleLeft
        '    .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
        '    'Not necessary???
        '    .Visible = False
        'End With
        'To fill combo items's
        'Note: These Instruments seem to me better for the chords but ...... may be other
        Dim ChordsStrInstruments() As String =
                {"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
                 "004 Rhodes(piano)", "005 Chorused(piano)", "006 Harpsichord", "007 Clavinet", "008 Celesta",
                 "009 Glockenspiel", "010 Music(box)", "011 Vibraphone", "012 Marimba", "013 Xylophone", "014 Tubular(bells)",
                 "015 Dulcimer", "016 Hammond(organ)", "017 Percussive(organ)", "018 Rock(organ)", "019 Church(organ)",
                 "020 Reed(organ)", "021 Accordion", "022 Harmonica", "023 Tango(accordion)", "024 Acoustic guitar (nylon)",
                 "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
                 "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
                 "032 Acoustic bass", "033 Electric bass (finger)", "034 Electric bass (pick)", "035 Fretless bass",
                 "036 Slap bass 1", "037 Slap bass 2", "038 Synth bass 1", "039 Synth bass 2", "040 Violin",
                 "041 Viola", "042 Cello", "043 Contrabass", "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp",
                 "047 Timpani", "048 String ensemble 1", "049 String ensemble 2", "050 Synth.strings(1)", "051 Synth.strings(2)",
                 "052 Choir(Aahs)", "053 Voice(Oohs)", "054 Synth(voice)", "055 Orchestra(hit)", "056 Trumpet", "057 Trombone",
                 "058 Tuba", "059 Muted(trumpet)", "060 French(horn)", "061 Brass(section)", "062 Synth.brass(1)",
                 "063 Synth.brass(2)", "064 Soprano sax", "065 Alto sax", "066 Tenor sax", "067 Baritone sax", "068 Oboe",
                 "069 English horn", "070 Bassoon", "071 Clarinet", "072 Piccolo", "073 Flute", "074 Recorder",
                 "075 Pan flute", "076 Bottle blow", "077 Shakuhachi", "078 Whistle", "079 Ocarina", "080 Lead 1 (square)",
                 "081 Lead 2 (sawtooth)", "082 Lead 3 (calliope lead)", "083 Lead 4 (chiff lead)", "084 Lead 5 (charang)",
                 "085 Lead 6 (voice)", "086 Lead 7 (fifths)", "087 Lead 8 (brass + lead)", "088 Pad 1 (new age)",
                 "089 Pad 2 (warm)", "090 Pad 3 (polysynth)", "091 Pad 4 (choir)", "092 Pad 5 (bowed)", "093 Pad 6 (metallic)",
                 "094 Pad 7 (halo)", "095 Pad 8 (sweep)", "096 FX 1 (rain)", "097 FX 2 (soundtrack)", "098 FX 3 (crystal)",
                 "099 FX 4 (atmosphere)", "100 FX 5 (brightness)", "101 FX 6 (goblins)", "102 FX 7 (echoes)", "103 FX 8 (sci-fi)",
                 "104 Sitar", "105 Banjo", "106 Shamisen", "107 Koto", "108 Kalimba", "119 Bagpipe", "110 Fiddle", "111 Shanai2",
                 "112 Tinkle Bell", "113 Agogo", "114 Steel Drums", "115 Woodblock", "116 Taiko Drum", "117 Melodic Tom",
                 "118 Synth Drum2", "119 Reverse Cymbal", "120 Guitar fret noise", "121 Breath noise", "122 Seashore",
                 "123 Bird tweet", "124 Telephone ring", "125 Helicopter", "126 Applause", "127 Gunshot"}

        'ChordsComboBoxInstruments Properties and AutoComplete
        With ChordsComboBoxInstruments
            .BeginUpdate()

            .AutoCompleteMode = CType(False, AutoCompleteMode)
            .MaxLength = 0
            .MaxDropDownItems = 30
            .CausesValidation = True
            .SelectedIndex = -1
            .DataSource = ChordsStrInstruments
            .Size = CType(New Point(150, 50), Drawing.Size)
            .Location = New Point(600, 565)
            .Text = "Chords Instrument List"
            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
            .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
            .ItemHeight = 50
            'DIRECT ASSOCIATION OF COMBOBox ITEMS
            '.Items.AddRange({"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
            ' "024 Acoustic guitar (nylon)", "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
            ' "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
            ' "032 Acoustic bass", "033 Electric bass (finger)", "040 Violin", "041 Viola", "042 Cello", "043 Contrabass",
            ' "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp"})
            .EndUpdate()
        End With
        'Associate new controls to form
        Me.Controls.Add(LblcomboInfo)
        Me.Controls.Add(LblInstrumInfo)
        Me.Controls.Add(ChordsComboBoxInstruments)

        'Associate an event with the combobox that was defined as
        '**********************  Private WithEvents ChordsComboBoxInstruments As New ComboBox()

        'This allows in real time to detect a new instrument that is chosen
        AddHandler ChordsComboBoxInstruments.TextChanged, AddressOf ChordsComboBoxInstruments_TextChanged

        'Allows you to decrypt and undo entries of keyboard characters in the editable part of the ComboBox
        'It is also possible that you can block text editing in this sector but .... I did not find out!
        AddHandler ChordsComboBoxInstruments.KeyPress, AddressOf ChordsComboBoxInstruments_KeyPress
        AddHandler ChordsComboBoxInstruments.KeyUp, AddressOf ChordsComboBoxInstruments_KeyUp

        'Note : Other events (MouseDown or MouseMove ) do not function in this situation
        'because it reads the selected instrument only after ( in the second selection )
        'This take me a long time to understand
    End Sub

    Private Sub ChordsComboBoxInstruments_KeyUp(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim HeaderText As String = "Chords Instrument List"
        If ChordsComboBoxInstruments.Text <> HeaderText Or ChordsComboBoxInstruments.Text <> StrInstrument Then
            If StrInstrument <> "" Then
                ChordsComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                ChordsComboBoxInstruments.SelectedText = StrInstrument
            Else
                ChordsComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                ChordsComboBoxInstruments.SelectedText = HeaderText
            End If
        End If
    End Sub

    Private Sub ChordsComboBoxInstruments_KeyPress(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim HeaderText As String = "Chords Instrument List"
        If ChordsComboBoxInstruments.Text <> HeaderText Or ChordsComboBoxInstruments.Text <> StrInstrument Then
            If StrInstrument <> "" Then
                ChordsComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                ChordsComboBoxInstruments.SelectedText = StrInstrument
            Else
                ChordsComboBoxInstruments.Text = ""
                'ChordsComboBoxInstruments.Select()
                ChordsComboBoxInstruments.SelectedText = HeaderText
            End If
        End If
    End Sub

    Private Sub ChordsComboBoxInstruments_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim HeaderText As String = "Chords Instrument List"
        Dim Editável As Boolean = False
        If ChordsComboBoxInstruments.Text <> HeaderText Then
            For i = 0 To ChordsComboBoxInstruments.Items.Count - 1
                If ChordsComboBoxInstruments.Text = ChordsComboBoxInstruments.Items.Item(i).ToString Then
                    Instrument2InMemory = CInt(Val(Mid(ChordsComboBoxInstruments.Text.ToString, 1, 3)))
                    StrInstrument = ChordsComboBoxInstruments.Text
                    Instrument2InMemory = CInt(Val(Mid(StrInstrument, 1, 3)))
                    ChangeInstrumentChords(Instrument2InMemory)
                    'Verificação nos labeis
                    LblInstrumInfo.Text = StrInstrument
                    LblcomboInfo.Text = Instrument2InMemory.ToString
                    Editável = True
                End If
            Next i
        ElseIf Editável = False Then
            ChordsComboBoxInstruments.Text = HeaderText
        End If
    End Sub

#End Region

#Region "AfixaçãoEmPauta AcordesTernários e Quaternários inscrição na pauta  de uma vez só"

    Private Function AfixaçãoEmPautaAcordesTernáriosEmBloco(ByVal Ternário1 As Integer, ByVal Ternário2 As Integer,
                                                      ByVal Ternário3 As Integer) As Boolean
        'Nota : Se  a  inscrição das notas for em bloco haverá menos  consumo  de bitmaps pauta e facilita posteriormente 
        'a designação da nota após determinado o tempo ( semibreve , colcheia, etc)
        'Ternário1..... significa o numero da tecla de 1 a 60 +-
        On Error GoTo Erros
        Dim k As Integer
        'O indice  seguinte  basea-se na posição da CoordenadaXInf
        Dim IndiceInf As Integer = CInt((CoordenadaXInf - 40) / 20) ' BitmapMemPautaInf(IndiceInf)   AS  BITMAP 
        Dim IndiceInfMáx As Integer = EspassamentoEntreNotas * MemMáxima
        Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXInf / IndiceInfMáx))
        Dim CorrecçãoAdaptativa As Integer = CoordenadaXInf - (IndiceInfMáx * Iterator)

        'If Not IsNothing(Ternário1) And Not IsNothing(Ternário2) And Not IsNothing(Ternário3) Then
        If Ternário1 > 0 And Ternário2 > 0 And Ternário3 > 0 Then
            'Obtenção das coordenadas YYY das três notas em #
            Dim CoordenadaYSusChords() As Integer = {CInt(MemóriaPauta.Rows(2).Cells.Item(Ternário1).Value),
                  CInt(MemóriaPauta.Rows(2).Cells.Item(Ternário2).Value),
                  CInt(MemóriaPauta.Rows(2).Cells.Item(Ternário3).Value)}
            'Obtenção das coordenadas YYY das três notas em bemóis
            Dim CoordenadaYBemChords() As Integer = {CInt(MemóriaPauta.Rows(5).Cells.Item(Ternário1).Value),
                  CInt(MemóriaPauta.Rows(5).Cells.Item(Ternário2).Value),
                  CInt(MemóriaPauta.Rows(5).Cells.Item(Ternário3).Value)}
            'Obtenção dos nomes  das três notas em #
            Dim NomeDaNotaPianoInfSusChords() As String = {MemóriaPauta.Columns(Ternário1).Name,
                  MemóriaPauta.Columns(Ternário2).Name,
                  MemóriaPauta.Columns(Ternário3).Name}
            'Obtenção dos nomes das três notas em bemóis
            Dim NomeDaNotaPianoInfBemChords() As String = {MemóriaPauta.Rows(3).Cells.Item(Ternário1).Value.ToString,
                  MemóriaPauta.Rows(3).Cells.Item(Ternário2).Value.ToString,
                  MemóriaPauta.Rows(3).Cells.Item(Ternário3).Value.ToString}

            'Iniciar pelo modo instituido pelo user
            Dim AcidSus() As Boolean = {Mid(NomeDaNotaPianoInfSusChords(0), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(1), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(2), 1, 1) = "#"}
            Dim AcidBem() As Boolean = {Mid(NomeDaNotaPianoInfBemChords(0), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(1), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(2), 1, 1) = "b"}
            ''Obtenção do valor booleano # para  as três notas
            If Acidentes = "Sustenidos" Or Acidentes = "" Then
                AcidSus = {Mid(NomeDaNotaPianoInfSusChords(0), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(1), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(2), 1, 1) = "#"}
                AcidBem = {False, False, False}
            End If
            If Acidentes = "Bemóis" Then
                ''Obtenção do valor booleano bemol para  as três notas
                AcidBem = {Mid(NomeDaNotaPianoInfBemChords(0), 1, 1) = "b",
                      Mid(NomeDaNotaPianoInfBemChords(1), 1, 1) = "b",
                      Mid(NomeDaNotaPianoInfBemChords(2), 1, 1) = "b"}
                AcidSus = {False, False, False}
            End If
            If Acidentes <> "Bemóis" And Acidentes <> "Sustenidos" And Acidentes <> "" Then
                MsgBox("Erro no modo de acidentar  as  notas ...click em -#- ou -b- ")
            End If

            'Desta forma eliminamos  a função de procura 
            'For Each Célula As DataGridViewCell In MemóriaPauta.Rows.Item(0).Cells
            'Existem acordes de três e de quatro notas - Neste caso tratamos  só três
            'Enviar dados para inscrição na pauta  -----------------------------------------------
            ColocaçãoEmBlocoDosAcordesTernários(CoordenadaXInf, CoordenadaYSusChords(0), AcidSus(0), AcidBem(0),
                  CoordenadaYSusChords(1), AcidSus(1), AcidBem(1), CoordenadaYSusChords(2), AcidSus(2), AcidBem(2))

        Else
            Return False
        End If

        Exit Function
Erros:
        MsgBox("Detectado um erro na Function AfixaçãoEmPautaAcordesTernários...." & ErrorToString())

    End Function

    Private Function AfixaçãoEmPautaAcordesQuaternáriosEmBloco(ByVal Quaternário1 As Integer, ByVal Quaternário2 As Integer,
                                                     ByVal Quaternário3 As Integer, ByVal Quaternário4 As Integer) As Boolean

        'Nota : Se  a  inscrição das notas for em bloco haverá menos  consumo  de bitmaps pauta e facilita posteriormente 
        'a designação da nota após determinado o tempo ( semibreve , colcheia, etc)
        'Quaternário1..... significa o numero da tecla de 1 a 60 +-
        On Error GoTo Erros
        Dim k As Integer
        'O indice  seguinte  basea-se na posição da CoordenadaXInf
        Dim IndiceInf As Integer = CInt((CoordenadaXInf - 40) / 20) ' BitmapMemPautaInf(IndiceInf)   AS  BITMAP 
        Dim IndiceInfMáx As Integer = EspassamentoEntreNotas * MemMáxima
        Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXInf / IndiceInfMáx))
        Dim CorrecçãoAdaptativa As Integer = CoordenadaXInf - (IndiceInfMáx * Iterator)
        'If Not IsNothing(Quaternário1) And Not IsNothing(Quaternário2) And Not IsNothing(Quaternário3) And Not IsNothing(Quaternário4) Then
        If Quaternário1 > 0 And Quaternário2 > 0 And Quaternário3 > 0 And Quaternário4 > 0 Then
            'Obtenção das coordenadas YYY das Quatro notas em #
            Dim CoordenadaYSusChords() As Integer = {CInt(MemóriaPauta.Rows(2).Cells.Item(Quaternário1).Value),
                  CInt(MemóriaPauta.Rows(2).Cells.Item(Quaternário2).Value),
                  CInt(MemóriaPauta.Rows(2).Cells.Item(Quaternário3).Value),
                  CInt(MemóriaPauta.Rows(2).Cells.Item(Quaternário4).Value)}
            'Obtenção das coordenadas YYY das Quatro notas em bemol
            Dim CoordenadaYBemChords() As Integer = {CInt(MemóriaPauta.Rows(5).Cells.Item(Quaternário1).Value),
                  CInt(MemóriaPauta.Rows(5).Cells.Item(Quaternário2).Value),
                  CInt(MemóriaPauta.Rows(5).Cells.Item(Quaternário3).Value),
                  CInt(MemóriaPauta.Rows(5).Cells.Item(Quaternário4).Value)}
            'Obtenção dos nomes  das Quatro notas em #
            Dim NomeDaNotaPianoInfSusChords() As String = {MemóriaPauta.Columns(Quaternário1).Name,
                  MemóriaPauta.Columns(Quaternário2).Name,
                  MemóriaPauta.Columns(Quaternário3).Name,
                  MemóriaPauta.Columns(Quaternário4).Name}
            'Obtenção dos nomes  das Quatro notas em bemol
            Dim NomeDaNotaPianoInfBemChords() As String = {MemóriaPauta.Rows(3).Cells.Item(Quaternário1).Value.ToString,
                  MemóriaPauta.Rows(3).Cells.Item(Quaternário2).Value.ToString,
                  MemóriaPauta.Rows(3).Cells.Item(Quaternário3).Value.ToString,
                  MemóriaPauta.Rows(3).Cells.Item(Quaternário4).Value.ToString}

            'Iniciar pelo modo instituido pelo user
            Dim AcidSus() As Boolean = {Mid(NomeDaNotaPianoInfSusChords(0), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(1), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(2), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(3), 1, 1) = "#"}
            Dim AcidBem() As Boolean = {Mid(NomeDaNotaPianoInfBemChords(0), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(1), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(2), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(3), 1, 1) = "b"}
            ''Obtenção do valor booleano # para  as três notas
            If Acidentes = "Sustenidos" Or Acidentes = "" Then
                AcidSus = {Mid(NomeDaNotaPianoInfSusChords(0), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(1), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(2), 1, 1) = "#",
                  Mid(NomeDaNotaPianoInfSusChords(3), 1, 1) = "#"}
                AcidBem = {False, False, False, False}
            End If
            If Acidentes = "Bemóis" Then ''Obtenção do valor booleano bemol para  as Quatro notas
                AcidBem = {Mid(NomeDaNotaPianoInfBemChords(0), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(1), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(2), 1, 1) = "b",
                  Mid(NomeDaNotaPianoInfBemChords(3), 1, 1) = "b"}
                AcidSus = {False, False, False, False}
            End If
            If Acidentes <> "Bemóis" And Acidentes <> "Sustenidos" And Acidentes <> "" Then
                MsgBox("Erro no modo de acidentar  as  notas ...click em -#- ou -b- ")
            End If
            'Desta forma eliminamos  a função de procura 
            'For Each Célula As DataGridViewCell In MemóriaPauta.Rows.Item(0).Cells

            'Existem acordes de três e de quatro notas - Neste caso tratamos Quatro
            'Enviar dados para inscrição na pauta  -----------------------------------------------
            ColocaçãoEmBlocoDosAcordesQuaternários(CoordenadaXInf, CoordenadaYSusChords(0), AcidSus(0), AcidBem(0),
                  CoordenadaYSusChords(1), AcidSus(1), AcidBem(1), CoordenadaYSusChords(2), AcidSus(2), AcidBem(2),
                  CoordenadaYSusChords(3), AcidSus(3), AcidBem(3))

            'If IndiceInf <= MemMáxima - 1 Then
            '    BitmapMemPautaInf(IndiceInf) = BitMapPauta
            'Else
            '    'Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXInf / 1000))
            '    'Dim CorrecçãoAdaptativa As Integer = CoordenadaXInf - (1000 * Iterator)
            '    'BitmapMemPautaSup(CInt((CorrecçãoAdaptativa) / 20)) = BitMapPauta  ?????
            '    BitmapMemPautaInf(CInt((CorrecçãoAdaptativa) / 20)) = BitMapPauta
            'End If
        Else
            Return False
        End If

        Exit Function
Erros:
        MsgBox("Detectado um erro na Function AfixaçãoEmPautaAcordesQuaternáriosEmBloco...." & ErrorToString())

    End Function

    Public Sub ColocaçãoEmBlocoDosAcordesTernários(ByVal CoordenadaXInf As Integer,
                 ByVal CoordenadaYSusChords0 As Integer, ByVal AcidSus0 As Boolean, ByVal AcidBem0 As Boolean,
                 ByVal CoordenadaYSusChords1 As Integer, ByVal AcidSus1 As Boolean, ByVal AcidBem1 As Boolean,
                 ByVal CoordenadaYSusChords2 As Integer, ByVal AcidSus2 As Boolean, ByVal AcidBem2 As Boolean)
        'On Error GoTo Erros
        'Nesta hipótese vai-se  escrever todas as notas do acorde  de uma  vez no PictureBox.BackgroundImage através do bitmap
        'Ainda  não  temos  temporização pelo que  só  se usa uma  nota  a  semibreve
        Dim NotaDimH As Integer = My.Resources._001nCSSemiBreve.Height
        Dim NotaDimW As Integer = My.Resources._001nCSSemiBreve.Width
        Dim AcidenteH As Integer = My.Resources._000wSSSus.Height
        'Aqui começa o registo  diferenciado
        Dim PtNotaCurrente0 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords0 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente0 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords0 - AcidenteH / 2)) '- CorrectionIcon))
        Dim PtNotaCurrente1 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords1 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente1 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords1 - AcidenteH / 2)) '- CorrectionIcon))
        Dim PtNotaCurrente2 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords2 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente2 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords2 - AcidenteH / 2)) '- CorrectionIcon))
        'Comuns a todos os casos
        Dim SzNotaCurrente As New Size(24, 32)
        Dim SzAcidenteNotaCurrente As New Size(20, 20)
        'Rectanglos e pontos 
        Dim RectNotaCurrente0 As New Rectangle(PtNotaCurrente0, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente0 As New Rectangle(AcidentePtNotaCurrente0, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen0 As Point = RectNotaCurrente0.Location
        Dim RectNotaCurrente1 As New Rectangle(PtNotaCurrente1, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente1 As New Rectangle(AcidentePtNotaCurrente1, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen1 As Point = RectNotaCurrente1.Location
        Dim RectNotaCurrente2 As New Rectangle(PtNotaCurrente2, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente2 As New Rectangle(AcidentePtNotaCurrente2, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen2 As Point = RectNotaCurrente2.Location

        'O indice  seguinte  basea-se na posição da CoordenadaXInf
        Dim IndiceInf As Integer = CInt((CoordenadaXInf - 40) / 20) ' BitmapMemPautaInf(IndiceInf)   AS  BITMAP 
        Dim IndiceInfMáx As Integer = EspassamentoEntreNotas * MemMáxima
        Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXInf / IndiceInfMáx))
        Dim CorrecçãoAdaptativa As Integer = CoordenadaXInf - (IndiceInfMáx * Iterator)
        'Alterações gráficas produzidas pelo teclado inf
        Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage)
        Dim GrPautaPInf As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPautaPInf ' Comtemplando  as três hipóteses
            Try
                .SmoothingMode = SmoothingMode.HighQuality
                .CompositingQuality = CompositingQuality.HighQuality
                'Primeira nota
                If AcidSus0 = True And AcidBem0 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente0)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente0)
                    'AcidSustenido = False
                ElseIf AcidSus0 = False And AcidBem0 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente0)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente0)
                    ' AcidBemol = False
                ElseIf AcidSus0 = False And AcidBem0 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente0)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords0 - NotaDimH / 2
                'Segunda nota
                If AcidSus1 = True And AcidBem1 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente1)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente1)
                    'AcidSustenido = False
                ElseIf AcidSus1 = False And AcidBem1 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente1)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente1)
                    ' AcidBemol = False
                ElseIf AcidSus1 = False And AcidBem1 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente1)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords1 - NotaDimH / 2
                'Terceira nota
                If AcidSus2 = True And AcidBem2 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente2)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente2)
                    'AcidSustenido = False
                ElseIf AcidSus2 = False And AcidBem2 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente2)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente2)
                    ' AcidBemol = False
                ElseIf AcidSus2 = False And AcidBem2 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente2)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords2 - NotaDimH / 2

                '================Memorização   pauta INF
                PautaPictureBox.BackgroundImage = BitMapPauta
                'O Indice O representa uma pauta virgem pelo que a sequencia de bitmaps aqui deve começar em 1
                If IndiceInf > 0 Then ' Assegura que não está fora da pauta
                    If IndiceInf < MemMáxima - 1 Then ' Primeiras notas até  mem maxima > 10, 20 ou 50 ... 
                        BitmapMemPautaInf(IndiceInf) = BitMapPauta
                        MemPautaInf = IndiceInf
                        'MsgBox("Atribuição de MemPautaSup = IndiceSup + 1  :  " & MemPautaSup)
                        lblChords(12).Text = "MemPautaInfAcN= " & MemPautaInf
                    End If
                    'Quando se  excede as primeiras notas memorizadas "mem maximo!
                    If IndiceInf >= MemMáxima - 1 Then
                        'A ideia é reiniciar os bitmaps "memória" a partir do 1
                        'Sendo que o bitmap memória 0 passa a ser o anterior nº mem máxima
                        If MemPautaInf < MemMáxima - 1 Then
                            MemPautaInf = MemPautaInf + 1
                            BitmapMemPautaInf(MemPautaInf) = BitMapPauta
                            'Assegurar a correcção para o resto da pauta
                            'MemPautaSup = (CInt((CorrecçãoAdaptativa) / 20))
                            lblChords(12).Text = "MemPautaInfAcN= " & MemPautaInf
                        End If
                        If MemPautaInf = MemMáxima - 1 Then
                            BitmapMemPautaInf(0) = BitMapPauta
                            'PautaPictureBox.BackgroundImage = BitMapPauta
                            For i = 1 To BitmapMemPautaInf.Count - 1 ' Apagar a memória no bitmap
                                BitmapMemPautaInf(i) = Nothing
                            Next
                            'Assegurar a ocorrencia da  gravação apenas nas  transições
                            MemPautaInf = 0
                            lblChords(12).Text = "MemPautaInfAcZ= " & MemPautaInf
                        End If
                    End If
                End If
            Catch ex As Exception
                MsgBox(ex.ToString)
            Finally
                GrPautaPInf.Dispose()
            End Try
        End With

        'Deslocamento  scroll 
        'ªªªªªªªªªªªªªªªªªªªªªªªªªªªª
        If CoordenadaXInf > 500 Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf - 200
        End If
        If CoordenadaXInf < FlLayPanel.HorizontalScroll.Value Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf
        End If
        If CoordenadaXInf >= FlLayPanel.HorizontalScroll.Maximum Then
            Dim Resposta As MsgBoxResult = MsgBox("Chegou ao Final da Pauta . Quer começar de Novo ? ", MsgBoxStyle.Question, "SE RESPONDER SIM VAI APAGAR A PAUTA")
            If Resposta = MsgBoxResult.Ok Then ReconstruçãoDaPautaVazia()
        End If
        'ªªªªªªªªªªªªªªªªªªªªªªªªª

        '        Exit Sub
        'Erros:
        '        MsgBox("Detectado um erro na Sub ColocaçãoEmBlocoDosAcordesPInf...." & ErrorToString())
    End Sub

    Public Sub ColocaçãoEmBlocoDosAcordesQuaternários(ByVal CoordenadaXInf As Integer,
                 ByVal CoordenadaYSusChords0 As Integer, ByVal AcidSus0 As Boolean, ByVal AcidBem0 As Boolean,
                 ByVal CoordenadaYSusChords1 As Integer, ByVal AcidSus1 As Boolean, ByVal AcidBem1 As Boolean,
                 ByVal CoordenadaYSusChords2 As Integer, ByVal AcidSus2 As Boolean, ByVal AcidBem2 As Boolean,
                 ByVal CoordenadaYSusChords3 As Integer, ByVal AcidSus3 As Boolean, ByVal AcidBem3 As Boolean)
        'On Error GoTo Erros
        'Nesta hipótese vai-se  escrever todas as notas do acorde  de uma  vez no PictureBox.BackgroundImage através do bitmap
        'Ainda  não  temos  temporização pelo que  só  se usa uma  nota  a  semibreve
        Dim NotaDimH As Integer = My.Resources._001nCSSemiBreve.Height
        Dim NotaDimW As Integer = My.Resources._001nCSSemiBreve.Width
        Dim AcidenteH As Integer = My.Resources._000wSSSus.Height
        'Aqui começa o registo  diferenciado
        Dim PtNotaCurrente0 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords0 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente0 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords0 - AcidenteH / 2)) '- CorrectionIcon))
        Dim PtNotaCurrente1 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords1 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente1 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords1 - AcidenteH / 2)) '- CorrectionIcon))
        Dim PtNotaCurrente2 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords2 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente2 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords2 - AcidenteH / 2)) '- CorrectionIcon))
        Dim PtNotaCurrente3 As New Point(CoordenadaXInf + EspassamentoEntreNotas, CInt(CoordenadaYSusChords3 - NotaDimH / 2)) '- CorrectionIcon)
        Dim AcidentePtNotaCurrente3 As New Point(CoordenadaXInf + EspassamentoEntreNotas - 5, CInt(CoordenadaYSusChords3 - AcidenteH / 2)) '- CorrectionIcon))

        'Comuns a todos os casos
        Dim SzNotaCurrente As New Size(24, 32)
        Dim SzAcidenteNotaCurrente As New Size(20, 20)
        'Rectanglos e pontos 
        Dim RectNotaCurrente0 As New Rectangle(PtNotaCurrente0, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente0 As New Rectangle(AcidentePtNotaCurrente0, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen0 As Point = RectNotaCurrente0.Location
        Dim RectNotaCurrente1 As New Rectangle(PtNotaCurrente1, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente1 As New Rectangle(AcidentePtNotaCurrente1, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen1 As Point = RectNotaCurrente1.Location
        Dim RectNotaCurrente2 As New Rectangle(PtNotaCurrente2, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente2 As New Rectangle(AcidentePtNotaCurrente2, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen2 As Point = RectNotaCurrente2.Location
        Dim RectNotaCurrente3 As New Rectangle(PtNotaCurrente3, SzNotaCurrente)
        Dim RectAcidenteNotaCurrente3 As New Rectangle(AcidentePtNotaCurrente3, SzAcidenteNotaCurrente)
        Dim PtNotaOnScreen3 As Point = RectNotaCurrente3.Location

        'O indice  seguinte  basea-se na posição da CoordenadaXInf
        Dim IndiceInf As Integer = CInt((CoordenadaXInf - 40) / 20) ' BitmapMemPautaInf(IndiceInf)   AS  BITMAP 
        Dim IndiceInfMáx As Integer = EspassamentoEntreNotas * MemMáxima
        Dim Iterator As Integer = CInt(Math.Floor(CoordenadaXInf / IndiceInfMáx))
        Dim CorrecçãoAdaptativa As Integer = CoordenadaXInf - (IndiceInfMáx * Iterator)
        'Alterações gráficas produzidas pelo teclado inf
        Dim BitMapPauta As New Bitmap(PautaPictureBox.BackgroundImage)
        Dim GrPautaPInf As Graphics = Graphics.FromImage(BitMapPauta)
        With GrPautaPInf ' Comtemplando  as três hipóteses
            Try
                .SmoothingMode = SmoothingMode.HighQuality
                .CompositingQuality = CompositingQuality.HighQuality
                'Primeira nota
                If AcidSus0 = True And AcidBem0 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente0)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente0)
                    'AcidSustenido = False
                ElseIf AcidSus0 = False And AcidBem0 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente0)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente0)
                    ' AcidBemol = False
                ElseIf AcidSus0 = False And AcidBem0 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente0)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords0 - NotaDimH / 2
                'Segunda nota
                If AcidSus1 = True And AcidBem1 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente1)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente1)
                    'AcidSustenido = False
                ElseIf AcidSus1 = False And AcidBem1 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente1)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente1)
                    ' AcidBemol = False
                ElseIf AcidSus1 = False And AcidBem1 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente1)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords1 - NotaDimH / 2
                'Terceira nota
                If AcidSus2 = True And AcidBem2 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente2)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente2)
                    'AcidSustenido = False
                ElseIf AcidSus2 = False And AcidBem2 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente2)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente2)
                    ' AcidBemol = False
                ElseIf AcidSus2 = False And AcidBem2 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente2)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords2 - NotaDimH / 2
                'Quarta nota
                If AcidSus3 = True And AcidBem3 = False Then
                    .DrawIcon(My.Resources._000wSSSus, RectAcidenteNotaCurrente3)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente3)
                    'AcidSustenido = False
                ElseIf AcidSus3 = False And AcidBem3 = True Then
                    .DrawIcon(My.Resources._000wSSBem, RectAcidenteNotaCurrente3)
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente3)
                    ' AcidBemol = False
                ElseIf AcidSus3 = False And AcidBem3 = False Then
                    .DrawIcon(My.Resources._001nCSSemiBreve, RectNotaCurrente3)
                End If
                'Me.LabelInfo2.Text = CoordenadaXInf + 20 & "X" & CoordenadaYSusChords2 - NotaDimH / 2
                '================Memorização   pauta INF
                PautaPictureBox.BackgroundImage = BitMapPauta
                'O Indice O representa uma pauta virgem pelo que a sequencia de bitmaps aqui deve começar em 1
                If IndiceInf > 0 Then ' Assegura que não está fora da pauta
                    If IndiceInf < MemMáxima - 1 Then ' Primeiras notas até  mem maxima > 10, 20 ou 50 ... 
                        BitmapMemPautaInf(IndiceInf) = BitMapPauta
                        MemPautaInf = IndiceInf
                        'MsgBox("Atribuição de MemPautaSup = IndiceSup + 1  :  " & MemPautaSup)
                        lblChords(12).Text = "MemPautaInfAcN= " & MemPautaInf
                    End If
                    'Quando se  excede as primeiras notas memorizadas "mem maximo!
                    If IndiceInf >= MemMáxima - 1 Then
                        'A ideia é reiniciar os bitmaps "memória" a partir do 1
                        'Sendo que o bitmap memória 0 passa a ser o anterior nº mem máxima
                        If MemPautaInf < MemMáxima - 1 Then
                            MemPautaInf = MemPautaInf + 1
                            BitmapMemPautaInf(MemPautaInf) = BitMapPauta
                            'Assegurar a correcção para o resto da pauta
                            'MemPautaSup = (CInt((CorrecçãoAdaptativa) / 20))
                            lblChords(12).Text = "MemPautaInfAcN= " & MemPautaInf
                        End If
                        If MemPautaInf = MemMáxima - 1 Then
                            BitmapMemPautaInf(0) = BitMapPauta
                            'PautaPictureBox.BackgroundImage = BitMapPauta
                            For i = 1 To BitmapMemPautaInf.Count - 1 ' Apagar a memória no bitmap
                                BitmapMemPautaInf(i) = Nothing
                            Next
                            'Assegurar a ocorrencia da  gravação apenas nas  transições
                            MemPautaInf = 0
                            lblChords(12).Text = "MemPautaInfAcZ= " & MemPautaInf
                        End If
                    End If
                End If
            Catch ex As Exception
            Finally
                GrPautaPInf.Dispose()
            End Try
        End With

        'Deslocamento  scroll 
        'ªªªªªªªªªªªªªªªªªªªªªªªªªªªª
        If CoordenadaXInf > 500 Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf - 200
        End If
        If CoordenadaXInf < FlLayPanel.HorizontalScroll.Value Then
            FlLayPanel.HorizontalScroll.Value = CoordenadaXInf
        End If
        If CoordenadaXInf >= FlLayPanel.HorizontalScroll.Maximum Then
            Dim Resposta As MsgBoxResult = MsgBox("Chegou ao Final da Pauta . Quer começar de Novo ? ", MsgBoxStyle.Question, "SE RESPONDER SIM VAI APAGAR A PAUTA")
            If Resposta = MsgBoxResult.Ok Then ReconstruçãoDaPautaVazia()
        End If
        'ªªªªªªªªªªªªªªªªªªªªªªªªª

        '        Exit Sub
        'Erros:
        '        MsgBox("Detectado um erro na Sub ColocaçãoEmBlocoDosAcordesPInf...." & ErrorToString())
    End Sub

#End Region

#Region "Chords With Mouse"
    ''' <summary>
    ''' Create the keys of the musical keyboard
    ''' </summary>
    ''' <remarks></remarks>
    Sub CreateChordsKeyBoard()
        Dim wChordsKeyWhite As New Point(22, 80)
        Dim wChordsKeyBlack As New Point(12, 50)
        Dim PosChordsKeyWhite As New Point(30, 400)
        Dim PosChordsKeyBlack As New Point(25, 400)

        For ChordsIndex As Integer = 1 To lblChordscKey.Count - 1
            lblChordscKey(ChordsIndex) = New Label
            With lblChordscKey(ChordsIndex)
                .BorderStyle = BorderStyle.FixedSingle
                Dim incWhiteKeyPosX As Integer
                'White keys
                If numKeysWhite.Contains(ChordsIndex) Then
                    .Size = New Size(wChordsKeyWhite)
                    .BackColor = Color.White
                    .Location =
                        New Point(PosChordsKeyWhite.X + incWhiteKeyPosX, PosChordsKeyWhite.Y + 300)
                    incWhiteKeyPosX = incWhiteKeyPosX + 21
                    .SendToBack() 'send to back
                End If
                'Black keys
                If numKeysBlack.Contains(ChordsIndex) Then
                    .BackColor = Color.Black
                    .Size = New Size(wChordsKeyBlack)
                    .Location =
                        New Point(PosChordsKeyBlack.X + incWhiteKeyPosX, PosChordsKeyBlack.Y + 300)
                End If
                Me.Controls.Add(lblChordscKey(ChordsIndex))
                If numKeysBlack.Contains(ChordsIndex) Then
                    lblChordscKey(ChordsIndex).BringToFront()
                End If

                AddHandler .MouseDown, AddressOf lblChordscKey_MouseDown
                AddHandler .MouseUp, AddressOf lblChordscKey_MouseUp
                AddHandler .MouseMove, AddressOf lblChordscKey_MouseMove
                AddHandler .MouseLeave, AddressOf lblChordscKey_MouseLeave
                AddHandler .KeyDown, AddressOf lblChordsWithKey_KeyDown
                AddHandler .KeyUp, AddressOf lblChordsWithKey_KeyUp
            End With

        Next

    End Sub

    Private Sub lblChordscKey_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        On Error Resume Next
        'Update the instrument to be used for the chords
        ChangeInstrumentChords(Instrument2InMemory)
        CoordenadaXInf = CoordenadaXInf + EspassamentoEntreNotas
        Dim ChordsIndex As Integer = Array.IndexOf(lblChordscKey, sender)
        lblChordscKey(ChordsIndex).BackColor = Color.Gray 'Change color of the key

        'Assigning Values to Chords' Integer Structure
        RelevantNotes1 = ChordsIndex ' Fundam
        RelevantNotes2 = ChordsIndex + 1
        RelevantNotes3 = ChordsIndex + 2
        RelevantNotes4 = ChordsIndex + 3
        RelevantNotes5 = ChordsIndex + 4
        RelevantNotes6 = ChordsIndex + 5 '3ª
        RelevantNotes7 = ChordsIndex + 6 'M+
        RelevantNotes8 = ChordsIndex + 7 'M-
        RelevantNotes9 = ChordsIndex + 8 '5ª
        RelevantNotes10 = ChordsIndex + 9 'M+
        RelevantNotes11 = ChordsIndex + 10
        RelevantNotes12 = ChordsIndex + 11

        'Note: The following chords were considered:
        'There may be other more significant chords but I do not know
        'Dim NamedChords() As String =
        '{"Chors =0", "Maior", "Maior +", "Maior -", "Maior 6ª", "Maior 7ª", "Menor",
        ' "Menor +", "Menor -", "Menor 6ª", "Menor 7ª"}
        If VerifyChordsExist = True Then
            Select Case VerifyChordsExist = True
                Case ChordsName = NamedChords(1) ' = "Maior"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes8)
                Case ChordsName = NamedChords(2) '= "Maior +"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes6), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes9), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes6).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes9).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes6, RelevantNotes9)
                Case ChordsName = NamedChords(3) '= "Maior -"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes7), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes7).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes7)
                Case ChordsName = NamedChords(4) '= "Maior 6ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes10), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes10).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes8, RelevantNotes10)
                Case ChordsName = NamedChords(5) '= "Maior 7ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes11), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes11).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes8, RelevantNotes11)
                Case ChordsName = NamedChords(6) '= "Menor"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes8)
                Case ChordsName = NamedChords(7) '= "Menor +"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes9), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes9).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes9)
                Case ChordsName = NamedChords(8) '= "Menor -"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes7), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes7).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes7)
                Case ChordsName = NamedChords(9) '="Menor 6ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes10), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes10).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes8, RelevantNotes10)
                Case ChordsName = NamedChords(10) '="Menor 7ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes11), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes11).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes8, RelevantNotes11)
            End Select

        ElseIf VerifyChordsExist = False Then
            'Afixaçaõ em pauta
            DesignaçãoDaNotaPianoInf(CByte(ChordsIndex))
            'CoordenadaXInf = CoordenadaXInf + 20
            ObtençãoCoordenadaYInf(NotaChords, CoordenadaXInf)
            PlayMusicalChords(CByte(ChordsIndex), VolumeKey, Octave)
        End If
        TeclaInfIsClickid = True
    End Sub

    Private Sub lblChordscKey_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        On Error Resume Next
        'This sub is intended to restore the initial appearance of the keys and muffle the sound 
        'of the chords and or a key only

        Dim ChordsIndex As Integer = Array.IndexOf(lblChordscKey, sender)

        'Assigning Values to Chords' Integer Structure
        RelevantNotes1 = ChordsIndex ' Fundam
        RelevantNotes2 = ChordsIndex + 1
        RelevantNotes3 = ChordsIndex + 2
        RelevantNotes4 = ChordsIndex + 3
        RelevantNotes5 = ChordsIndex + 4 '3ª 
        RelevantNotes6 = ChordsIndex + 5
        RelevantNotes7 = ChordsIndex + 6 'M+
        RelevantNotes8 = ChordsIndex + 7 'M-
        RelevantNotes9 = ChordsIndex + 8 '5ª
        RelevantNotes10 = ChordsIndex + 9 'M+
        RelevantNotes11 = ChordsIndex + 10
        RelevantNotes12 = ChordsIndex + 11

        'Stop sounds and restore keyboard
        If VerifyChordsExist = True Then
            Select Case VerifyChordsExist = True
                Case ChordsName = NamedChords(1) ' = "Maior"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes5, Octave)
                    OffMusicalNote(RelevantNotes8, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(2) ' = "Maior +"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes6, Octave)
                    OffMusicalNote(RelevantNotes9, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes6) Then
                        lblChordscKey(RelevantNotes6).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes6).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes9) Then
                        lblChordscKey(RelevantNotes9).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes9).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(3) ' = "Maior -"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes5, Octave)
                    OffMusicalNote(RelevantNotes7, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes7) Then
                        lblChordscKey(RelevantNotes7).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes7).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(4) ' = "Maior 6ª"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes5, Octave)
                    OffMusicalNote(RelevantNotes8, Octave)
                    OffMusicalNote(RelevantNotes10, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes10) Then
                        lblChordscKey(RelevantNotes10).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes10).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(5) ' = "Maior 7ª"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes5, Octave)
                    OffMusicalNote(RelevantNotes8, Octave)
                    OffMusicalNote(RelevantNotes11, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes11) Then
                        lblChordscKey(RelevantNotes11).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes11).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(6) ' = "Menor"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes4, Octave)
                    OffMusicalNote(RelevantNotes8, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(7) ' = "Menor +"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes4, Octave)
                    OffMusicalNote(RelevantNotes9, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes9) Then
                        lblChordscKey(RelevantNotes9).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes9).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(8) ' = "Menor -"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes4, Octave)
                    OffMusicalNote(RelevantNotes7, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes7) Then
                        lblChordscKey(RelevantNotes7).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes7).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(9) ' = "Menor 6ª"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes4, Octave)
                    OffMusicalNote(RelevantNotes8, Octave)
                    OffMusicalNote(RelevantNotes10, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes10) Then
                        lblChordscKey(RelevantNotes10).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes10).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(10) ' = "Menor 7ª"
                    OffMusicalNote(RelevantNotes1, Octave)
                    OffMusicalNote(RelevantNotes4, Octave)
                    OffMusicalNote(RelevantNotes8, Octave)
                    OffMusicalNote(RelevantNotes11, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes11) Then
                        lblChordscKey(RelevantNotes11).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes11).BackColor = Color.Black 'Change color of the key
                    End If

            End Select
        ElseIf VerifyChordsExist = False Then
            OffMusicalNoteChords(ChordsIndex, Octave)
            If numKeysWhite.Contains(ChordsIndex) Then
                lblChordscKey(ChordsIndex).BackColor = Color.White 'Change color of the key
            Else
                lblChordscKey(ChordsIndex).BackColor = Color.Black 'Change color of the key
            End If
        End If
        TeclaInfIsClickid = False

    End Sub

    Private Sub lblChordscKey_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim ChordsIndex As Integer = Array.IndexOf(lblChordscKey, sender)
        Dim mPoint As New Point(Me.PointToClient(Cursor.Position).X, Me.PointToClient(Cursor.Position).Y)
        Dim X As Integer = mPoint.X
        Dim Y As Integer = mPoint.Y
        Cursor = Cursors.Hand
        'Balizar no  eixo dos YYY - Os dois teclados
        If Y > 400 And Y < 500 And TeclaInfIsClickid = True Then
            'Baizar no eixo dos XXX
            If X > 30 And X < 780 Then
                If X < CInt(lblChordscKey(ChordsIndex).Left) Or
                        X > (CInt(lblChordscKey(ChordsIndex).Left) +
                             CInt(lblChordscKey(ChordsIndex).Width)) Then
                    EventoUpIII() ' procedimento mouse UP ou desligar a nota 
                    EventoDownIII() ' procedimento mouse Down ou accionar a nota 
                    'A Condição de igualdade acontece sempre que se pressiona uma tecla 
                    'São accionados os procedimentos MouseDown e MouseMove simultaneamente
                    'ElseIf X = CInt(lblMuscKey(Index).Left) Then
                    '    EventoUpIII()
                End If
            End If
        End If
    End Sub

    Private Sub lblChordscKey_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
        'Repete o procedimento MouseUP repetidamete para restaurar as cores 
        Call lblChordscKey_MouseLeave_RestoreColores(sender, e)
        'TeclaInfIsClickid = True
        Cursor = Cursors.Default
    End Sub

    Private Sub lblChordscKey_MouseLeave_RestoreColores(ByVal sender As Object, ByVal e As System.EventArgs)
        On Error Resume Next
        'This sub is intended to restore the initial appearance of the keys and muffle the sound 
        'of the chords and or a key only

        Dim ChordsIndex As Integer = Array.IndexOf(lblChordscKey, sender)

        'Assigning Values to Chords' Integer Structure
        RelevantNotes1 = ChordsIndex ' Fundam
        RelevantNotes2 = ChordsIndex + 1
        RelevantNotes3 = ChordsIndex + 2
        RelevantNotes4 = ChordsIndex + 3
        RelevantNotes5 = ChordsIndex + 4 '3ª 
        RelevantNotes6 = ChordsIndex + 5
        RelevantNotes7 = ChordsIndex + 6 'M+
        RelevantNotes8 = ChordsIndex + 7 'M-
        RelevantNotes9 = ChordsIndex + 8 '5ª
        RelevantNotes10 = ChordsIndex + 9 'M+
        RelevantNotes11 = ChordsIndex + 10
        RelevantNotes12 = ChordsIndex + 11

        'Stop sounds and restore keyboard
        If VerifyChordsExist = True Then
            Select Case VerifyChordsExist = True
                Case ChordsName = NamedChords(1) ' = "Maior"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes5, Octave)
                    'OffMusicalNote(RelevantNotes8, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(2) ' = "Maior +"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes6, Octave)
                    'OffMusicalNote(RelevantNotes9, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes6) Then
                        lblChordscKey(RelevantNotes6).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes6).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes9) Then
                        lblChordscKey(RelevantNotes9).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes9).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(3) ' = "Maior -"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes5, Octave)
                    'OffMusicalNote(RelevantNotes7, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes7) Then
                        lblChordscKey(RelevantNotes7).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes7).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(4) ' = "Maior 6ª"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes5, Octave)
                    'OffMusicalNote(RelevantNotes8, Octave)
                    'OffMusicalNote(RelevantNotes10, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes10) Then
                        lblChordscKey(RelevantNotes10).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes10).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(5) ' = "Maior 7ª"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes5, Octave)
                    'OffMusicalNote(RelevantNotes8, Octave)
                    'OffMusicalNote(RelevantNotes11, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes11) Then
                        lblChordscKey(RelevantNotes11).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes11).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(6) ' = "Menor"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes4, Octave)
                    'OffMusicalNote(RelevantNotes8, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(7) ' = "Menor +"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes4, Octave)
                    'OffMusicalNote(RelevantNotes9, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes9) Then
                        lblChordscKey(RelevantNotes9).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes9).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(8) ' = "Menor -"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes4, Octave)
                    'OffMusicalNote(RelevantNotes7, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes7) Then
                        lblChordscKey(RelevantNotes7).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes7).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(9) ' = "Menor 6ª"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes4, Octave)
                    'OffMusicalNote(RelevantNotes8, Octave)
                    'OffMusicalNote(RelevantNotes10, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes10) Then
                        lblChordscKey(RelevantNotes10).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes10).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(10) ' = "Menor 7ª"
                    'OffMusicalNote(RelevantNotes1, Octave)
                    'OffMusicalNote(RelevantNotes4, Octave)
                    'OffMusicalNote(RelevantNotes8, Octave)
                    'OffMusicalNote(RelevantNotes11, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes11) Then
                        lblChordscKey(RelevantNotes11).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes11).BackColor = Color.Black 'Change color of the key
                    End If

            End Select
        ElseIf VerifyChordsExist = False Then
            'OffMusicalNoteChords(ChordsIndex, Octave)
            If numKeysWhite.Contains(ChordsIndex) Then
                lblChordscKey(ChordsIndex).BackColor = Color.White 'Change color of the key
            Else
                lblChordscKey(ChordsIndex).BackColor = Color.Black 'Change color of the key
            End If
        End If

    End Sub

#End Region

#Region "Chords with keyboard"

    Private Sub lblChordsWithKey_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) 'Handles Me.KeyDown
        On Error Resume Next
        'Update the instrument to be used for the chords
        ChangeInstrumentChords(Instrument2InMemory)
        CoordenadaXInf = CoordenadaXInf + 20
        Dim ChordsIndex As Integer = CByte(KeyChords(e.KeyCode)) ' Array.IndexOf(lblChordscKey, sender)
        'lblChordscKey(ChordsIndex).BackColor = Color.Gray 'Change color of the key

        'Assigning Values to Chords' Integer Structure
        ' Dim RelevantNotes() As Integer
        RelevantNotes1 = ChordsIndex ' Fundamental
        RelevantNotes2 = ChordsIndex + 1
        RelevantNotes3 = ChordsIndex + 2
        RelevantNotes4 = ChordsIndex + 3
        RelevantNotes5 = ChordsIndex + 4
        RelevantNotes6 = ChordsIndex + 5 '3ª
        RelevantNotes7 = ChordsIndex + 6 'M+
        RelevantNotes8 = ChordsIndex + 7 'M-
        RelevantNotes9 = ChordsIndex + 8 '5ª
        RelevantNotes10 = ChordsIndex + 9 'M+
        RelevantNotes11 = ChordsIndex + 10
        RelevantNotes12 = ChordsIndex + 11

        'Note: The following chords were considered:
        'There may be other more significant chords but I do not know
        'Dim NamedChords() As String =
        '{"Chors =0", "Maior", "Maior +", "Maior -", "Maior 6ª", "Maior 7ª", "Menor",
        ' "Menor +", "Menor -", "Menor 6ª", "Menor 7ª"}
        If VerifyChordsExist = True Then
            Select Case VerifyChordsExist = True
                Case ChordsName = NamedChords(1) ' = "Maior" 
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes8)
                Case ChordsName = NamedChords(2) '= "Maior +"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes6), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes9), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes6).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes9).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes6, RelevantNotes9)
                Case ChordsName = NamedChords(3) '= "Maior -"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes7), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes7).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes7)
                Case ChordsName = NamedChords(4) '= "Maior 6ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes10), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes10).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes8, RelevantNotes10)
                Case ChordsName = NamedChords(5) '= "Maior 7ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes5), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes11), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes5).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes11).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes5, RelevantNotes8, RelevantNotes11)
                Case ChordsName = NamedChords(6) '= "Menor"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes8)
                Case ChordsName = NamedChords(7) '= "Menor +"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes9), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes9).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes9)
                Case ChordsName = NamedChords(8) '= "Menor -"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes7), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes7).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesTernáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes7)
                Case ChordsName = NamedChords(9) '="Menor 6ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes10), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes10).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes8, RelevantNotes10)
                Case ChordsName = NamedChords(10) '="Menor 7ª"
                    PlayMusicalChords(CByte(RelevantNotes1), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes4), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes8), VolumeKey, Octave)
                    PlayMusicalChords(CByte(RelevantNotes11), VolumeKey, Octave)
                    lblChordscKey(RelevantNotes1).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes4).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes8).BackColor = Color.Gray 'Change color of the key
                    lblChordscKey(RelevantNotes11).BackColor = Color.Gray 'Change color of the key
                    AfixaçãoEmPautaAcordesQuaternáriosEmBloco(RelevantNotes1, RelevantNotes4, RelevantNotes8, RelevantNotes11)
            End Select
        ElseIf VerifyChordsExist = False Then
            PlayMusicalChords(CByte(ChordsIndex), VolumeKey, Octave)
        End If

        Call Memória.TimerTim1(sender, e)
    End Sub

    Private Sub lblChordsWithKey_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) 'Handles Me.KeyUp
        On Error Resume Next
        'This sub is intended to restore the initial appearance of the keys and muffle the sound 
        'of the chords and or a key only

        Dim ChordsIndex As Integer = CByte(KeyChords(e.KeyCode)) 'Array.IndexOf(lblChordscKey, sender)

        'Assigning Values to Chords' Integer Structure
        RelevantNotes1 = ChordsIndex ' Fundam
        RelevantNotes2 = ChordsIndex + 1
        RelevantNotes3 = ChordsIndex + 2
        RelevantNotes4 = ChordsIndex + 3
        RelevantNotes5 = ChordsIndex + 4 '3ª 
        RelevantNotes6 = ChordsIndex + 5
        RelevantNotes7 = ChordsIndex + 6 'M+
        RelevantNotes8 = ChordsIndex + 7 'M-
        RelevantNotes9 = ChordsIndex + 8 '5ª
        RelevantNotes10 = ChordsIndex + 9 'M+
        RelevantNotes11 = ChordsIndex + 10
        RelevantNotes12 = ChordsIndex + 11

        'Stop sounds and restore keyboard
        If VerifyChordsExist = True Then
            Select Case VerifyChordsExist = True
                Case ChordsName = NamedChords(1) ' = "Maior"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes5, Octave)
                    OffMusicalNoteChords(RelevantNotes8, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(2) ' = "Maior +"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes6, Octave)
                    OffMusicalNoteChords(RelevantNotes9, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes6) Then
                        lblChordscKey(RelevantNotes6).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes6).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes9) Then
                        lblChordscKey(RelevantNotes9).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes9).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(3) ' = "Maior -"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes5, Octave)
                    OffMusicalNoteChords(RelevantNotes7, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes7) Then
                        lblChordscKey(RelevantNotes7).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes7).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(4) ' = "Maior 6ª"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes5, Octave)
                    OffMusicalNoteChords(RelevantNotes8, Octave)
                    OffMusicalNoteChords(RelevantNotes10, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes10) Then
                        lblChordscKey(RelevantNotes10).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes10).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(5) ' = "Maior 7ª"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes5, Octave)
                    OffMusicalNoteChords(RelevantNotes8, Octave)
                    OffMusicalNoteChords(RelevantNotes11, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes5) Then
                        lblChordscKey(RelevantNotes5).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes5).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes11) Then
                        lblChordscKey(RelevantNotes11).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes11).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(6) ' = "Menor"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes4, Octave)
                    OffMusicalNoteChords(RelevantNotes8, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(7) ' = "Menor +"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes4, Octave)
                    OffMusicalNoteChords(RelevantNotes9, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes9) Then
                        lblChordscKey(RelevantNotes9).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes9).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(8) ' = "Menor -"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes4, Octave)
                    OffMusicalNoteChords(RelevantNotes7, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes7) Then
                        lblChordscKey(RelevantNotes7).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes7).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(9) ' = "Menor 6ª"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes4, Octave)
                    OffMusicalNoteChords(RelevantNotes8, Octave)
                    OffMusicalNoteChords(RelevantNotes10, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes10) Then
                        lblChordscKey(RelevantNotes10).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes10).BackColor = Color.Black 'Change color of the key
                    End If
                Case ChordsName = NamedChords(10) ' = "Menor 7ª"
                    OffMusicalNoteChords(RelevantNotes1, Octave)
                    OffMusicalNoteChords(RelevantNotes4, Octave)
                    OffMusicalNoteChords(RelevantNotes8, Octave)
                    OffMusicalNoteChords(RelevantNotes11, Octave)
                    If numKeysWhite.Contains(RelevantNotes1) Then
                        lblChordscKey(RelevantNotes1).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes1).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes4) Then
                        lblChordscKey(RelevantNotes4).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes4).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes8) Then
                        lblChordscKey(RelevantNotes8).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes8).BackColor = Color.Black 'Change color of the key
                    End If
                    If numKeysWhite.Contains(RelevantNotes11) Then
                        lblChordscKey(RelevantNotes11).BackColor = Color.White 'Change color of the key
                    Else
                        lblChordscKey(RelevantNotes11).BackColor = Color.Black 'Change color of the key
                    End If

            End Select
        ElseIf VerifyChordsExist = False Then
            OffMusicalNoteChords(ChordsIndex, Octave)
            If numKeysWhite.Contains(ChordsIndex) Then
                lblChordscKey(ChordsIndex).BackColor = Color.White 'Change color of the key
            Else
                lblChordscKey(ChordsIndex).BackColor = Color.Black 'Change color of the key
            End If
        End If

    End Sub

#End Region

#Region "ChordsMaker Functions"
    ''' <summary>
    ''' Play a musical Chords
    ''' </summary>
    ''' <param name="NoteChords">Value of musical Chords</param>  
    ''' <param name="Volume">Volume musical note</param>
    ''' <param name="bOct">Octave</param>
    ''' <returns></returns>
    Public Function PlayMusicalChords(ByVal NoteChords As Byte, ByVal Volume As Byte, ByVal bOct As Byte) As Boolean
        ChangeInstrumentChords(Instrument2InMemory)

        NoteChords = CByte(NoteChords + (21 + (12 * bOct)))
        intMsgChords = CInt(Volume * Convert.ToInt32(CStr(10000), 16) + NoteChords * Convert.ToInt32(CStr(100), 16) + NativeMethodsIII.KeyOn)
        Return CBool(NativeMethodsIII.midiOutShortMsg(hMidiOut, intMsgChords))

    End Function
    ''' <summary>
    ''' Off a musical note
    ''' </summary>
    ''' <param name="NoteChords">Value of musical note</param>
    ''' <param name="bOct">Octave</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function OffMusicalNoteChords(ByVal NoteChords As Integer, ByVal bOct As Integer) As Boolean
        NoteChords = NoteChords + (21 + (12 * bOct))
        intMsgChords = NoteChords * Convert.ToInt32(CStr(100), 16) + NativeMethodsIII.KeyOff
        Return CBool(NativeMethodsIII.midiOutShortMsg(hMidiOut, intMsgChords))

    End Function
    ''' <summary>
    ''' Change the instrument
    ''' </summary>
    ''' <param name="Instrument2InMemory"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ChangeInstrumentChords(ByVal Instrument2InMemory As Integer) As Boolean
        intMsgChords = Instrument2InMemory * Convert.ToInt32(CStr(100), 16) + NativeMethodsIII.InstrumentsChords
        Return CBool(NativeMethodsIII.midiOutShortMsg(hMidiOut, intMsgChords))
        'Return Nothing
    End Function
#End Region

#Region "Musical Keyboard"

    ''' <summary>
    ''' Create the keys of the musical keyboard
    ''' </summary>
    ''' <remarks></remarks>
    ''' 
    Private Sub CreateMusicalKeyBoard()
        Dim wKeyWhite As New Point(22, 80)
        Dim wKeyBlack As New Point(12, 50)
        Dim PosKeyWhite As New Point(30, 300)
        Dim PosKeyBlack As New Point(25, 300)

        For Index As Integer = 1 To lblMuscKey.Count - 1
            lblMuscKey(Index) = New Label
            With lblMuscKey(Index)
                .BorderStyle = BorderStyle.FixedSingle
                Dim incWhiteKeyPosX As Integer
                'White keys
                If numKeysWhite.Contains(Index) Then
                    .Size = New Size(wKeyWhite)
                    .BackColor = Color.White
                    .Location =
                        New Point(PosKeyWhite.X + incWhiteKeyPosX, PosKeyWhite.Y + 300)
                    incWhiteKeyPosX = incWhiteKeyPosX + 21
                    .SendToBack() 'send to back
                End If
                'Black keys
                If numKeysBlack.Contains(Index) Then
                    .BackColor = Color.Black
                    .Size = New Size(wKeyBlack)
                    .Location =
                        New Point(PosKeyBlack.X + incWhiteKeyPosX, PosKeyBlack.Y + 300)
                End If
                Me.Controls.Add(lblMuscKey(Index))
                If numKeysBlack.Contains(Index) Then
                    lblMuscKey(Index).BringToFront()
                End If

                AddHandler .MouseDown, AddressOf lblMuscKey_MouseDown
                AddHandler .MouseUp, AddressOf lblMuscKey_MouseUp
                AddHandler .MouseMove, AddressOf lblMuscKey_MouseMove
                AddHandler .MouseLeave, AddressOf lblMuscKey_MouseLeave

            End With

        Next

    End Sub

    'Sub CreateMusicalKeyBoard2()
    '    Dim TecladoSup As New GroupBox With {.Left = 25, .Top = 600, .Height = 100, .Width = 600, .Visible = True,
    '        .BackColor = Color.Black}
    '    Me.Controls.Add(TecladoSup)

    '    'Teclas imbuídas no flowPanel
    '    'Dim wKeyWhite As New Point(22, 150)
    '    'Dim wKeyBlack As New Point(12, 100)
    '    'Dim PosKeyWhite As New Point(30, 0)
    '    'Dim PosKeyBlack As New Point(25, 0)
    '    Dim wKeyWhite As New Point(25, 90)
    '    Dim wKeyBlack As New Point(14, 50)
    '    Dim PosKeyWhite As New Point(9, 5)
    '    Dim PosKeyBlack As New Point(0, 5)
    '    For Index As Integer = 1 To lblMuscKey.Count - 1
    '        lblMuscKey(Index) = New Label With {.ImageAlign = ContentAlignment.MiddleCenter, .Enabled = True, .FlatStyle = FlatStyle.Popup, .BackgroundImageLayout = ImageLayout.Stretch}
    '        With lblMuscKey(Index)
    '            .BorderStyle = BorderStyle.FixedSingle
    '            Dim incWhiteKeyPosX As Integer
    '            'White keys
    '            If numKeysWhite.Contains(Index) Then
    '                .Size = New Size(wKeyWhite)
    '                .BackColor = Color.White
    '                .Location =
    '                    New Point(PosKeyWhite.X + incWhiteKeyPosX, PosKeyWhite.Y)
    '                incWhiteKeyPosX = incWhiteKeyPosX + 29
    '                .SendToBack() 'send to back
    '            End If
    '            'Black keys
    '            If numKeysBlack.Contains(Index) Then
    '                .BackColor = Color.Black
    '                .Size = New Size(wKeyBlack)
    '                .Location =
    '                    New Point(PosKeyBlack.X + incWhiteKeyPosX, PosKeyBlack.Y) ' + 300)
    '            End If
    '            TecladoSup.Controls.Add(lblMuscKey(Index))
    '            If numKeysBlack.Contains(Index) Then
    '                lblMuscKey(Index).BringToFront()
    '            End If

    '            AddHandler .MouseDown, AddressOf lblMuscKey_MouseDown
    '            AddHandler .MouseUp, AddressOf lblMuscKey_MouseUp
    '            AddHandler .MouseMove, AddressOf lblMuscKey_MouseMove
    '            AddHandler .MouseLeave, AddressOf lblMuscKey_MouseLeave
    '        End With

    '    Next
    '    'TecladoSup.BringToFront()

    'End Sub

    Private Sub lblMuscKey_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 'Handles Me.MouseDown
        ChangeInstrument(Instrument1InMemory)
        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
        'Para o timer da medição da  memória que é manual
        If Tim1.Enabled = True Then Tim1.Stop()

        If numKeysWhite.Contains(Index) Then
            lblMuscKey(Index).BackColor = Color.Gray 'Change color of the key
            DesignaTeclas = "nCS"
        End If
        If numKeysBlack.Contains(Index) Then
            lblMuscKey(Index).BackColor = Color.Gray 'Change color of the key
            If Acidentes = "Sustenidos" Or Acidentes <> "Bemóis" Then DesignaTeclas = "_CS"
            If Acidentes = "Bemóis" Then DesignaTeclas = "bCS"

        End If
        'Afixaçaõ em pauta - Poderia  transitar também para o mouse Up ?
        DesignaçãoDaNotaPianoSup(CByte(Index))
        'CoordenadaXSup = CoordenadaXSup + 20
        'ObtençãoCoordenadaYSup(NotaSolo, CoordenadaXSup)
        PlayMusicalNote(CByte(Index), VolumeKey, Octave)
        TeclaSupIsClickid = True

        TicksCount = 0 '    Assegura contagem a partir do zero no tick timer NOTA : Delaração em modulo como Public
        Me.lblChords(12).Text = "" '    Apagar as notas do label informativo
        Teclas.TeclasMouseDown.Start() ' Aciona o timer no modulo Teclas
    End Sub

    Private Sub lblMuscKey_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) ' Handles Me.MouseUp

        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
        Teclas.TeclasMouseDown.Stop() ' Parar o timer
        DuraçãoDoImpulso = Teclas.TicksCount ' Variável que  recebe a informaçao do Timer Teclas

        'Pesquisar em IconsTeclasCodeNames pela duração da nota em contraposição ao código pré-inscrito nos diversos icons
        Call PesquisarNota(DuraçãoDoImpulso)

        'Aspectos gráficos
        If numKeysWhite.Contains(Index) Then
            lblMuscKey(Index).BackColor = Color.White 'Change color of the key
        ElseIf numKeysBlack.Contains(Index) Then
            lblMuscKey(Index).BackColor = Color.Black 'Change color of the key
        Else
            lblMuscKey(Index).BackColor = Color.Black 'Change color of the key
        End If
        TeclaSupIsClickid = False 'Impede cliques involuntários no mousemove
        'Silenciar a nota
        OffMusicalNote(Index, Octave)

        'Marcar em pauta            
        If Marcar = False Then
            lblChords(12).Text = "Nota ???.." & "I: " & DuraçãoDoImpulso & " D: " & Math.Round(DesvioTemporal, 2)
            If DesvioTemporal > 1.5 Or DesvioTemporal < 0.6 Then lblChords(12).BackColor = Color.Gray
            Exit Sub
        Else
            lblChords(12).Text = Mid(IconsTeclasCodeNames(Indíce - 1), 8) & " I: " & DuraçãoDoImpulso & " D: " & Math.Round(DesvioTemporal, 2)
            CoordenadaXSup = CoordenadaXSup + 20 ' Avanço da posição da nota
            ObtençãoCoordenadaYSup(NotaSolo, CoordenadaXSup) 'Determinaçao final da  posição no eixo dos YY
            If DesvioTemporal < 1.5 And DesvioTemporal > 0.6 Then lblChords(12).BackColor = Color.Green
        End If
    End Sub

    Private Sub lblMuscKey_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
        Dim mPoint As New Point(Me.PointToClient(Cursor.Position).X, Me.PointToClient(Cursor.Position).Y)
        Dim X As Integer = mPoint.X
        Dim Y As Integer = mPoint.Y
        Cursor = Cursors.Hand
        'Balizar no  eixo dos YYY - Os dois teclados
        If Y > 300 And Y < 400 And TeclaSupIsClickid = True Then
            'Baizar no eixo dos XXX
            If X > 50 And X < 780 Then
                If X < CInt(lblMuscKey(Index).Left) Or
                        X > (CInt(lblMuscKey(Index).Left) +
                             CInt(lblMuscKey(Index).Width)) Then
                    EventoUpIII() ' procedimento mouse UP ou desligar a nota 
                    EventoDownIII() ' procedimento mouse Down ou accionar a nota 
                    'A Condição de igualdade acontece sempre que se pressiona uma tecla 
                    'São accionados os procedimentos MouseDown e MouseMove simultaneamente
                    'ElseIf X = CInt(lblMuscKey(Index).Left) Then
                    '    EventoUpIII()
                End If
            End If
        End If

    End Sub

    Private Sub lblMuscKey_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
        'Retomar a cor das teclas
        If numKeysWhite.Contains(Index) Then
            lblMuscKey(Index).BackColor = Color.White 'Change color of the key
        Else
            lblMuscKey(Index).BackColor = Color.Black 'Change color of the key
        End If

        Cursor = Cursors.Default

    End Sub

#End Region

#Region "Play Sounds Functions"
    ''' <summary>
    ''' Play a musical note
    ''' </summary>
    ''' <param name="Note">Value of musical note</param>  
    ''' <param name="Volume">Volume musical note</param>
    ''' <param name="bOct">Octave</param>
    ''' <returns></returns>
    Public Function PlayMusicalNote(ByVal Note As Byte, ByVal Volume As Byte, ByVal bOct As Byte) As Boolean
        ChangeInstrument(Instrument1InMemory)
        Note = CByte(Note + (21 + (12 * bOct)))
        intMsg = CInt(Volume * Convert.ToInt32(CStr(10000), 16) + Note * Convert.ToInt32(CStr(100), 16) + NativeMethodsIII.KeyOn)
        Return CBool(NativeMethodsIII.midiOutShortMsg(hMidiOut, intMsg))
    End Function
    ''' <summary>
    ''' Off a musical note
    ''' </summary>
    ''' <param name="Note">Value of musical note</param>
    ''' <param name="bOct">Octave</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function OffMusicalNote(ByVal Note As Integer, ByVal bOct As Integer) As Boolean
        Note = Note + (21 + (12 * bOct))
        intMsg = Note * Convert.ToInt32(CStr(100), 16) + NativeMethodsIII.KeyOff
        Return CBool(NativeMethodsIII.midiOutShortMsg(hMidiOut, intMsg))
    End Function
    ''' <summary>
    ''' Change the instrument
    ''' </summary>
    ''' <param name="instCode"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ChangeInstrument(ByVal instCode As Integer) As Boolean
        intMsg = instCode * Convert.ToInt32(CStr(100), 16) + NativeMethodsIII.Instruments
        Return CBool(NativeMethodsIII.midiOutShortMsg(hMidiOut, intMsg))
        Return Nothing
    End Function
#End Region

#Region "Computer keyboard keys"
    ''' <summary>
    ''' Assigning Computer keyboard keys
    ''' </summary>
    ''' <param name="keycode"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Key(ByVal keycode As Integer) As Integer
        ' Esta  rotina  tem a exclusiva  função de eliminar os toques nas teclas do Keyboard que 
        ' não  têm qualquer função nesta  aplicação sem passar informação para outras rotinas
        Dim BlackHalfKey() As Keys = {Keys.W, Keys.E, Keys.T, Keys.Y, Keys.U}
        Dim WhiteHalfKey() As Keys = {Keys.A, Keys.S, Keys.D, Keys.F, Keys.G, Keys.H, Keys.J, Keys.K}
        Dim BassKey() As Keys = {Keys.Z, Keys.X, Keys.C, Keys.V, Keys.B, Keys.N, Keys.M, Keys.Oemcomma}
        Dim AltoKey() As Keys = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8}

        If BlackHalfKey.Contains(CType(keycode, Keys)) Or
            WhiteHalfKey.Contains(CType(keycode, Keys)) Or
            BassKey.Contains(CType(keycode, Keys)) Or
             AltoKey.Contains(CType(keycode, Keys)) Then
            For I As Integer = 10 To 14
                If keycode = BlackHalfKey(I - 10) Then Msg.NoteTest = CByte(numKeysBlack(I))
            Next
            For I As Integer = 14 To 21
                If keycode = WhiteHalfKey(I - 14) Then Msg.NoteTest = CByte(numKeysWhite(I))
            Next
            For I As Integer = 0 To 7
                If keycode = BassKey(I) Then Msg.NoteTest = CByte(numKeysWhite(I))
            Next
            For I As Integer = 28 To 35
                If keycode = AltoKey(I - 28) Then Msg.NoteTest = CByte(numKeysWhite(I))
            Next

            Return Msg.NoteTest
        Else
            Return 0
        End If

    End Function

    Public Function KeySolo(ByVal keycode As Integer) As Integer
        Dim BlackHalfKey() As Keys = {Keys.W, Keys.E, Keys.T, Keys.Y, Keys.U}
        Dim WhiteHalfKey() As Keys = {Keys.A, Keys.S, Keys.D, Keys.F, Keys.G, Keys.H, Keys.J, Keys.K}
        Dim BassKey() As Keys = {Keys.Z, Keys.X, Keys.C, Keys.V, Keys.B, Keys.N, Keys.M, Keys.Oemcomma}
        Dim AltoKey() As Keys = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8}

        If BlackHalfKey.Contains(CType(keycode, Keys)) Or
            WhiteHalfKey.Contains(CType(keycode, Keys)) Or
            BassKey.Contains(CType(keycode, Keys)) Or
             AltoKey.Contains(CType(keycode, Keys)) Then
            For I As Integer = 10 To 14
                If keycode = BlackHalfKey(I - 10) Then Msg.Note = CByte(numKeysBlack(I))
            Next

            For I As Integer = 14 To 21
                If keycode = WhiteHalfKey(I - 14) Then Msg.Note = CByte(numKeysWhite(I))
            Next

            For I As Integer = 0 To 7
                If keycode = BassKey(I) Then Msg.Note = CByte(numKeysWhite(I))
            Next
            For I As Integer = 28 To 35
                If keycode = AltoKey(I - 28) Then Msg.Note = CByte(numKeysWhite(I))
            Next

            lblMuscKey(Msg.Note).BackColor = Color.Gray
            'lblChordscKey(Msg.Note).BackColor = Color.Gray
            Return Msg.Note
        Else
            Return 0
        End If

        ChangeInstrument(Instrument1InMemory)
    End Function

    Public Function KeyChords(ByVal keycode As Integer) As Integer
        Dim BlackHalfKey() As Keys = {Keys.W, Keys.E, Keys.T, Keys.Y, Keys.U}
        Dim WhiteHalfKey() As Keys = {Keys.A, Keys.S, Keys.D, Keys.F, Keys.G, Keys.H, Keys.J, Keys.K}
        Dim BassKey() As Keys = {Keys.Z, Keys.X, Keys.C, Keys.V, Keys.B, Keys.N, Keys.M, Keys.Oemcomma}
        Dim AltoKey() As Keys = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8}

        If BlackHalfKey.Contains(CType(keycode, Keys)) Or
            WhiteHalfKey.Contains(CType(keycode, Keys)) Or
            BassKey.Contains(CType(keycode, Keys)) Or
             AltoKey.Contains(CType(keycode, Keys)) Then
            For I As Integer = 10 To 14
                If keycode = BlackHalfKey(I - 10) Then Msg.NoteChords = CByte(numKeysBlack(I))
            Next

            For I As Integer = 14 To 21
                If keycode = WhiteHalfKey(I - 14) Then Msg.NoteChords = CByte(numKeysWhite(I))
            Next

            For I As Integer = 0 To 7
                If keycode = BassKey(I) Then Msg.NoteChords = CByte(numKeysWhite(I))
            Next
            For I As Integer = 28 To 35
                If keycode = AltoKey(I - 28) Then Msg.NoteChords = CByte(numKeysWhite(I))
            Next

            'lblMuscKey(Msg.NoteChords).BackColor = Color.Gray
            lblChordscKey(Msg.NoteChords).BackColor = Color.Gray
            Return Msg.NoteChords
        Else
            Return 0
        End If

        ChangeInstrument(Instrument2InMemory)
    End Function

#Region "IDisposable Support"
    Private disposedValue As Boolean ' Para detectar chamadas redundantes

    ' IDisposable
    'Protected Overridable Sub Dispose(disposing As Boolean)
    '    If Not disposedValue Then
    '        If disposing Then
    '            ' TODO: descartar estado gerenciado (objetos gerenciados).
    '        End If

    '        ' TODO: liberar recursos não gerenciados (objetos não gerenciados) e substituir um Finalize() abaixo.
    '        ' TODO: definir campos grandes como nulos.
    '    End If
    '    disposedValue = True
    'End Sub

    ' TODO: substituir Finalize() somente se Dispose(disposing As Boolean) acima tiver o código para liberar recursos não gerenciados.
    'Protected Overrides Sub Finalize()
    '    ' Não altere este código. Coloque o código de limpeza em Dispose(disposing As Boolean) acima.
    '    Dispose(False)
    '    MyBase.Finalize()
    'End Sub

    ' Código adicionado pelo Visual Basic para implementar corretamente o padrão descartável.
    'Public Sub Dispose() Implements IDisposable.Dispose
    '    ' Não altere este código. Coloque o código de limpeza em Dispose(disposing As Boolean) acima.
    '    Dispose(True)
    '    ' TODO: remover marca de comentário da linha a seguir se Finalize() for substituído acima.
    '    ' GC.SuppressFinalize(Me)
    'End Sub
#End Region

#End Region

End Class

#Region "Native Methods"

'Não  sei  se  é  correcto colocar  aqui os  disposables mas parece diminuir a carga no CPU
Class BaseClassIII : Implements IDisposable
    ' Flag: Has Dispose already been called?
    Dim disposed As Boolean = False
    ' Instantiate a SafeHandle instance.
    Dim handle As SafeHandle = New SafeFileHandle(IntPtr.Zero, True)

    ' Public implementation of Dispose pattern callable by consumers.
    Public Sub Dispose() _
                  Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    ' Protected implementation of Dispose pattern.
    Protected Overridable Sub Dispose(disposing As Boolean)
        If disposed Then Return

        If disposing Then
            handle.Dispose()
            ' Free any other managed objects here.
            '
        End If

        disposed = True
    End Sub
End Class

Module AppVersionIII
    ''' <summary>
    ''' Gets the AssemblyFileVersion from the specified assembly.
    ''' </summary>
    ''' <param name="Assembly">[Assembly] Assembly to get the Assembly File Version from.</param>
    ''' <returns>[String] The Assembly's file version.</returns>
    <Extension>
    Friend Function GetFileVersion(ByVal Assembly As Assembly) As String
        On Error GoTo Err
        Return DirectCast(Assembly.GetCustomAttribute(GetType(AssemblyFileVersionAttribute)), AssemblyFileVersionAttribute).Version
Err:
        Return Nothing
    End Function
End Module

Module MouseEventsIII
    ''' <summary>
    ''' Simulate MouseDown the left mouse button
    ''' </summary>
    ''' <remarks></remarks>

    Public Sub EventoDownIII()
        NativeMethodsIII.mouse_event(NativeMethodsIII.MouseEventFlags.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, New System.IntPtr())
    End Sub
    ''' <summary>
    ''' Simulate MouseUp the left mouse button
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub EventoUpIII()
        NativeMethodsIII.mouse_event(NativeMethodsIII.MouseEventFlags.MOUSEEVENTF_LEFTUP, 0, 0, 0, New System.IntPtr())
    End Sub

End Module

<SuppressUnmanagedCodeSecurity()>
Friend NotInheritable Class NativeMethodsIII
    Inherits Attribute
    Private Sub New()
    End Sub

#Region "API MIDI message"
    <DllImport("winmm.dll")>
    Public Shared Function midiOutOpen(ByRef lphMidiOut As IntPtr,
                                       ByVal uDeviceID As Integer,
                                       ByVal dwCallback As IntPtr,
                                       ByVal dwInstance As IntPtr,
                                       ByVal dwFlags As UInteger) As UInteger
    End Function
    <DllImport("winmm.dll")>
    Public Shared Function midiOutShortMsg(ByVal hMidiOut As IntPtr,
                                           ByVal dwMsg As Integer) As UInteger
    End Function

    <DllImport("winmm.dll")>
    Public Shared Function midiOutClose(ByVal hMidiOut As IntPtr) As Integer
    End Function

    <StructLayout(LayoutKind.Auto)>
    Public Structure MidiMsg
        Dim status As Byte
        Dim Note, NoteChords, NoteTest As Byte
        Dim Volume As Byte
        Dim Data3 As Byte
    End Structure
    Public Const MIDI_MAPPER As Int32 = -1
    Public Const CALLBACK_NULL = &H0
    Public Const KeyOn As Integer = &H90
    Public Const KeyOff As Integer = &H80
    Public Const Instruments As Integer = &HC0
    Public Const InstrumentsChords As Integer = &HC0
#End Region

#Region "API Mouse Events"
    'With my thanks to Robbie and Melissa http://www.nullskull.com/articles/transparentform_send_mouse_click_to_desktop.asp
    'Com a alteração "ByVal  dwExtraInfo As UInt32" para "ByVal dwExtraInfo As IntPtr" consegue-se a adapatação para 64b e (32b)
    'Assim também foi alterado a instrução :
    'NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    'Para
    'NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_LEFTUP, 0, 0, 0, New System.IntPtr())
    <DllImport("user32.dll", CharSet:=CharSet.Auto)>
    Friend Shared Sub mouse_event(ByVal dwFlags As UInt32,
                                   ByVal dx As UInt32,
                                   ByVal dy As UInt32,
                                   ByVal dwData As UInt32,
                                   ByVal dwExtraInfo As IntPtr)

    End Sub

    <Flags()>
    Public Enum MouseEventFlags As UInteger
        MOUSEEVENTF_ABSOLUTE = &H8000
        MOUSEEVENTF_LEFTDOWN = &H2
        MOUSEEVENTF_LEFTUP = &H4
        MOUSEEVENTF_MIDDLEDOWN = &H20
        MOUSEEVENTF_MIDDLEUP = &H40
        MOUSEEVENTF_MOVE = &H1
        MOUSEEVENTF_RIGHTDOWN = &H8
        MOUSEEVENTF_RIGHTUP = &H10
        MOUSEEVENTF_XDOWN = &H80
        MOUSEEVENTF_XUP = &H100
        MOUSEEVENTF_WHEEL = &H800
        MOUSEEVENTF_HWHEEL = &H1000
    End Enum

#End Region

#Region "StreamRessources"
    'Retirado como exemplo de como implementar o IDisposable safe Handles de https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose
    'È  curioso que para evitar qq aviso  teve  de  ser colocada dentro da  Class nativemethods 
    'Tambem só assim deixa  de ser visivel fora Do assembly
    'Mas ainda não sei como funciona ......................Parece aumentar a carga na CPU
    'Neste  momento creio que  não  estou  usando o stream reader
    Public Class DisposableStreamResource : Implements IDisposable
        ' Define constants.
        Protected Const GENERIC_READ As UInteger = &H80000000UI
        Protected Const FILE_SHARE_READ As UInteger = &H0I
        Protected Const OPEN_EXISTING As UInteger = 3
        Protected Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80
        Private ReadOnly INVALID_HANDLE_VALUE As New IntPtr(-1) 'Campo somente de leitura  sugerido pelo programa 
        Private Const INVALID_FILE_SIZE As Integer = &HFFFFFFFF

        ' Define Windows APIs.
        Protected Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (
                                             lpFileName As String, dwDesiredAccess As UInt32,
                                             dwShareMode As UInt32, lpSecurityAttributes As IntPtr,
                                             dwCreationDisposition As UInt32, dwFlagsAndAttributes As UInt32,
                                             hTemplateFile As IntPtr) As IntPtr
        Private Declare Function GetFileSize Lib "kernel32" (hFile As SafeFileHandle,
                                                            ByRef lpFileSizeHigh As Integer) As Integer

        ' Define locals.
        Private disposed As Boolean = False
        Private safeHandle As SafeFileHandle
        Private ReadOnly bufferSize As Long  'Campo somente de leitura  sugerido pelo programa 
        Private ReadOnly upperWord As Integer 'Campo somente de leitura  sugerido pelo programa 

        Public Sub New(filename As String)
            If filename Is Nothing Then
                Throw New ArgumentNullException("The filename cannot be null.")
            ElseIf filename = "" Then
                Throw New ArgumentException("The filename cannot be an empty string.")
            End If

            Dim handle As IntPtr = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ,
                                            IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
                                            IntPtr.Zero)
            If handle <> INVALID_HANDLE_VALUE Then
                safeHandle = New SafeFileHandle(handle, True)
            Else
                Throw New FileNotFoundException(String.Format("Cannot open '{0}'", filename))
            End If

            ' Get file size.
            bufferSize = GetFileSize(safeHandle, upperWord)
            If bufferSize = INVALID_FILE_SIZE Then
                bufferSize = -1
            ElseIf upperWord > 0 Then
                bufferSize = (CLng(upperWord) << 32) + bufferSize
            End If
        End Sub

        Public ReadOnly Property Size As Long
            Get
                Return bufferSize
            End Get
        End Property

        Public Sub Dispose() _
                  Implements IDisposable.Dispose
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub

        Protected Overridable Sub Dispose(disposing As Boolean)
            If disposed Then Exit Sub

            ' Dispose of managed resources here.
            If disposing Then
                safeHandle.Dispose()
            End If

            ' Dispose of any unmanaged resources not wrapped in safe handles.

            disposed = True
        End Sub
    End Class
#End Region

End Class

#End Region

Module Memória
    ' Medição Da Memória USADA
    'Tentativa de obter o gasto de memória e de CPU

    Public WithEvents Tim1 As New Timer With {.Interval = 5000, .Enabled = True}
    Dim cpu As New Integer
    ReadOnly Perfor As New PerformanceCounter With {.[ReadOnly] = True, .CategoryName = "Processor", .CounterName = "% Processor Time", .InstanceName = "_Total"}
    ReadOnly Tot As Integer = CInt(Val(My.Computer.Info.TotalPhysicalMemory) / 1024 / 1024)
    ReadOnly Disponiv As Integer = CInt(Val(My.Computer.Info.AvailablePhysicalMemory) / 1024 / 1024)
    ReadOnly Usada As Integer = Tot - Disponiv
    ReadOnly Rate As Integer = CInt(Usada * 100 / Tot)
    ReadOnly Title As String = Form1.Text

    Public Sub TimerTim1(ByVal sender As Object, ByVal e As EventArgs) Handles Tim1.Tick
        On Error GoTo TimerError
        If Teclas.TeclasMouseDown.Enabled = True Then Teclas.TeclasMouseDown.Enabled = False
        With Tim1
            'Medição dos dados a cada 5 seg
            cpu = CInt(Perfor.NextValue)
            Form1.Text = ""
            Form1.Text = Title & "  Memory Used !!! = " & Rate & " %" & "  CPU : " & cpu & " %"
            'Threading.Thread.Sleep(100) ' 1seg  =  1000
        End With
        Exit Sub
TimerError:
        MsgBox(Err.Description)
    End Sub

End Module

Module Teclas
    ' Medição Da Tempo do click
    'Tentativa de obter as notas respeitantes ao tempo de cada click
    ReadOnly IntevaloDoTimer As Integer = CInt(Math.Round(128 / Form1.Andamento)) 'aprox 128_QuartiFusa
    Public WithEvents TeclasMouseDown As New Timer With {.Interval = CInt((IntevaloDoTimer)), .Enabled = True}
    Public TicksCount As New Integer
    'Private Rapidez As Integer = 32

    Public Sub TeclasMouseDown_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles TeclasMouseDown.Tick
        On Error GoTo TimerError
        If Memória.Tim1.Enabled = True Then Memória.Tim1.Enabled = False
        With TeclasMouseDown
            'Variavel para incrementar
            TicksCount = TicksCount + Form1.Rapidez
            'Visualização da contagem
            Dim NotaçõesMusicais As Integer = 128
            If TicksCount = NotaçõesMusicais Or TicksCount = (2 * NotaçõesMusicais) Or TicksCount = (4 * NotaçõesMusicais) _
                Or TicksCount = (8 * NotaçõesMusicais) Or TicksCount = (16 * NotaçõesMusicais) Or TicksCount = (32 * NotaçõesMusicais) _
                Or TicksCount = (64 * NotaçõesMusicais) Or TicksCount = (128 * NotaçõesMusicais) Then
                Form1.lblChords(12).BackColor = Color.Red
            Else
                Form1.lblChords(12).BackColor = Color.Gray
            End If
            Form1.lblChords(12).Text = ""
            Form1.lblChords(12).Text = TicksCount.ToString & "***" & TimeSpan.FromSeconds(TeclasMouseDown.Interval).TotalSeconds & " Sec"
        End With
        Exit Sub
TimerError:
        MsgBox(Err.Description)
    End Sub

End Module