Sending an SMS message using .NET CF on Win Mobile

My best man asked me a few months ago to create him an app that would allow him to send a predefined sms to a predefined number on a click of a button using his Win Mobile phone. I thought about it and decided to write this application for him.

First thing that we need to do is to create a Smart Device project, and choose device application from the next page. In my solution i have one form called Sender and a Program.cs file, this is only the basics so we will not need anything more.

As you can see from the previous picture, the user interface is very intuitive and plain. We have two textboxes and a button that sends the SMS. This part of the application is completely working and can be used to send SMS from your Win Mobile phone.

For sending the SMS message we need only the code below, and of course the call from the Send button

using Microsoft.WindowsMobile.PocketOutlook;
public static void SendSms(string recipientNumber, string messageText)
{
try
{
var sms = new SmsMessage()
{
Body = messageText
};
sms.To.Add(new Recipient(recipientNumber));
sms.Send();
MessageBox.Show("Message sent!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

To fire up the sending from a command line(that was the original idea if you remember, he wanted to be able to send it on a click of a button) we need to handle some command line arguments. My idea was to call the program the same way we have called the method that send the message first the recipient number, and then the message. calling the program without arguments would open the form, any other number of arguments will show a message with the correct way of doing it.

[MTAThread]
static void Main(string[] args)
{
switch (args.Length)
{
case 0:
Application.Run(new Sender());
break;
case 2:
Sender.SendSms(args[0],args[1]);
break;
default:
MessageBox.Show("Wrong number of arguments entered. Correct order is RecipientNumber \"SmsText in quotes\"");
break;
}
}

We can also do a regular expression check depending on the numbers we allow the user to send the SMS to, if we want to limit the user in any way, because i know my only user, i believe i can trust him 🙂

Next thing you need is to set up a shortcut that calls the application using the parameters and bind the shortcut to a button on your device. Quick way to pay tram fare when the conductor enters the tram and you just forgot to buy the ticket that day.