Microsoft Small Basic

Program Listing: NHT122-0
' Morse Telegraph Key
' Version 0.2a
' Copyright © 2019 Nonki Takahashi. The MIT License.
' Last update 2019-01-25
' Program ID NHT122-0

GraphicsWindow.Title = "Morse Telegraph Key 0.2a"
LF = Text.GetCharacter(10)
dah = 150 ' ~ [ms] (dit < 200 [ms])
gap = 600
Form()
OnButtonClicked()
GraphicsWindow.KeyDown = OnKeyDown
GraphicsWindow.KeyUp = OnKeyUp
Controls.ButtonClicked = OnButtonClicked
While "True"
If o < i Then
ShowMorse()
Else
Program.Delay(100)
EndIf
EndWhile

Sub Form
gw = 598
gh = 428
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
GraphicsWindow.BackgroundColor = "LightGray"
GraphicsWindow.PenWidth = 0
GraphicsWindow.BrushColor = "Blue"
lamp = Shapes.AddRectangle(gw, gh)
Shapes.SetOpacity(lamp, 80)
Shapes.HideShape(lamp)
GraphicsWindow.BrushColor = "Black"
GraphicsWindow.FontName = "Consolas"
GraphicsWindow.FontSize = 9
tbox = Controls.AddMultiLineTextBox(10, 10)
th = 250
Controls.SetSize(tbox, gw - 20, th)
GraphicsWindow.FontSize = 12
btn = Controls.AddButton("Reset", gw - 54, gh - 34)
morse = ".-=A;-...=B;-.-.=C;-..=D;.=E;"
morse = morse + "..-.=F;--.=G;....=H;..=I;.---=J;"
morse = morse + "-.-=K;.-..=L;--=M;-.=N;---=O;"
morse = morse + ".--.=P;--.-=Q;.-.=R;...=S;-=T;"
morse = morse + "..-=U;...-=V;.--=W;-..-=X;-.--=Y;--..=Z;"
morse = morse + "--..--=,;.-.-.-=.;"
morse = morse + ".----=1;..---=2;...--=3;....-=4;.....=5;"
morse = morse + "-.-.--=!;..--..=?;"
morse = morse + "-....=6;--...=7;---..=8;----.=9;-----=0;"
morse = morse + "........=ERR;"
index = Array.GetAllIndices(morse)
x = 10
y = th + 20
For c = 1 To Array.GetItemCount(morse)
GraphicsWindow.DrawText(x, y, morse[index[c]])
GraphicsWindow.DrawText(x + 24, y, index[c])
If Text.IsSubText("(7)(14)(21)(28)(35)", "(" + c + ")") Then
x = 10
y = y + 20
Else
x = x + 82
EndIf
EndFor
EndSub

Sub OnButtonClicked
i = 0
o = 0
t0 = Clock.ElapsedMilliseconds
buf = ""
Controls.SetTextBoxText(tbox, buf)
EndSub

Sub OnKeyDown
t1 = Clock.ElapsedMilliseconds
Shapes.ShowShape(lamp)
i = i + 1
d[i] = Math.Round(t1 - t0)
keyDown = "True"
EndSub

Sub OnKeyUp
t0 = Clock.ElapsedMilliseconds
Shapes.HideShape(lamp)
i = i + 1
d[i] = Math.Round(t0 - t1)
keyUp = "True"
EndSub

Sub ShowMorse
While o < i
o = o + 1
If Math.Remainder(o, 2) = 0 Then
' dit/dah
If dah <= d[o] Then
' dah
buf = buf + "-"
Else
' dit
buf = buf + "."
EndIf
len = len + 1
Else
' gap
If dah <= d[o] Then
buf = buf + " "
len = len + 1
If 107 < len Or 4000 <= d[o] Then
buf = buf + LF
len = 0
ElseIf gap <= d[o] Then
buf = buf + " "
len = len + 2
EndIf
EndIf
EndIf
Controls.SetTextBoxText(tbox, buf)
EndWhile
EndSub