Pages

4/10/2012

Use Morse Code to write text in Desktop Apps

First of all create a windows form project in visual studio and drag three buttons on the form and a textbox(you can add further controls but these are minimum controls needed).

Declare following global variables.\

private string inputString = "";
        private int count = 0;

        private static readonly Dictionary<string, string> mapping = new Dictionary<string, string>() {
        {  ".-","a" },
        {  "-...","b" },
        {  "-.-.", "c"},
        {  "-..","d" },
        {  "." ,"e"},
        {  "..-.","f" },
        {  "--.","g" },
        {  "....","h" },
        {  "..","i" },
        {  ".---","j" },
        {  "-.-" ,"k"},
        {  ".-.." ,"l"},
        {  "--" ,"m"},
        {  "-." ,"n"},
        {  "---" ,"o"},
        {  ".--." ,"p"},
        {  "--.-" ,"q"},
        {  ".-." ,"r"},
        {  "..." ,"s"},
        {  "-" ,"t"},
        {  "..-" ,"u"},
        {  "...-" ,"v"},
        {  ".--" ,"w"},
        {  "-..-" ,"x"},
        {  "-.--" ,"y"},
        {  "--.." ,"z"},
        {  "-----" ,"0"},
        {  ".----" ,"1"},
        {  "..---" ,"2"},
        {  "...--" ,"3"},
        {  "....-" ,"4"},
        {  "....." ,"5"},
        {  "-...." ,"6"},
        {  "--..." ,"7"},
        {  "---.." ,"8"},
        {  "----." ,"9"}
    };


Now name one button as "." and second as "-" as morse code depends on these two characters.

Name the third button as "space" which will be used to differentiate characters and letters.

On click event of button named "." write following line.

inputString += ".";

On click event of button named "-" write following line.

inputString += "-";

On click event of button named "space" write following lines. 

            count++;
            if (count == 1 && inputString != "")
            {
                textBox1.Text += GetLetter(inputString);
                count = 0;
            }
            else
            {
                textBox1.Text += GetLetter(inputString) + " ";
                count = 0;
            }

            inputString = "";


        public string GetLetter(string morseCode)
        {
            return mapping.ContainsKey(morseCode.ToString()) ? mapping[morseCode] : "";
        }


 Now build and run this project. 

If you want to differentiate between characters hit space once and if you want to add space hit space twice.

This can b very useful in mobile development where it could be used for typing.

Any suggestions and queries are welcome.


Twitter Delicious Facebook Digg Favorites More