Sending SMS Messages with Visual Basic

Introduction

We all know what an SMS is (hopefully!), but sadly, SMS is said to be a dying medium of communication. I honestly do not actually think it is, because most countries are still battling with proper internet communication, and the fact that internet prices are quite expensive, especially in South Africa. Anyway, enough rambling… Today, I will show you how to send and receive an SMS with your Windows Phone

Let’s get straight down to business.

Our Project

The project you will create today is a Windows Phone project, Blank app (to be precise). Name it anything you like and design your project to resemble Figure 1.

SMS1
Figure 1: Our Design

You may name your objects anything you like; but, keep in mind that my object names may be different than yours. If you want to follow my example to the letter, here is the resulting XAML code for this design:

<Page
   x_Class="SMS.MainPage"
   
   xmlns_x="http://schemas.microsoft.com/winfx/
      2006/xaml"
   xmlns_local="using:SMS"
   xmlns_d="http://schemas.microsoft.com/expression/
      blend/2008"
   xmlns_mc="http://schemas.openxmlformats.org/
      markup-compatibility/2006"
   mc_Ignorable="d"
   Background="{ThemeResource
      ApplicationPageBackgroundThemeBrush}">

   <Grid>
      <Button x_Name="btnSend" Content="Send"
         HorizontalAlignment="Left" VerticalAlignment="Top"
         Margin="10,0,0,0"/>
      <TextBox x_Name="txtSendTo" HorizontalAlignment="Left"
         Margin="20,76,0,0" TextWrapping="Wrap" Text="TextBox"
         VerticalAlignment="Top" Width="314"/>
      <TextBox x_Name="txtBody" HorizontalAlignment="Left"
         Margin="20,119,0,0" TextWrapping="Wrap" Text="TextBox"
         VerticalAlignment="Top" Height="231" Width="314"/>
      <Button x_Name="btnRecieve" Content="Recieve"
         HorizontalAlignment="Left" Margin="262,0,0,0"
         VerticalAlignment="Top"/>

   </Grid>
</Page>

Code

First, let me start with sending an SMS. Add the following code to add the appropriate namespaces and their functionalities to your project:

Imports System
Imports Windows.Devices.Sms

This simply imports SMS communication capabilities to your project. Speaking about capabilities, you could also add this capability to your project. To add any Capability to a project, follow these steps:

  1. Double-click Package.appxmanifest in the Solution Explorer, as shown in Figure 2. SMS2
    Figure 2: Solution Explorer
  2. This will produce the screen as shown in Figure 3.SMS3
    Figure 3: Settings
  3. Select the Capabilities tab and choose it from the items in the list.
  4. You also could click on Project, Properties and click the Package Manifest… button, as shown in Figure 4.
    SMS4
    Figure 4: Project Properties

If this is your first time playing with Windows Phone apps, have a thorough look through each of the tabs and play around a little. Here are a few articles that can assist you to get started with Windows Phone apps:

Add a modular variable. This is a variable object that will be used through all the objects on the page:

Private sdDevice As SmsDevice

Add the following code behind the button labeled Send:

Private Async Sub btnSend_Click(sender As Object, _
   e As RoutedEventArgs) Handles btnSend.Click

   If sdDevice Is Nothing Then
      Try
         sdDevice = Await SmsDevice.GetDefaultAsync()
         Catch ex As Exception

         Return
      End Try
   End If

   Try

      Dim stmMessage As New SmsTextMessage()
      stmMessage.To = txtSendTo.Text
      stmMessage.Body = txtBody.Text()

      Await sdDevice.SendMessageAsync(stmMessage)

      Catch err As Exception

         sdDevice = Nothing

   End Try

End Sub

You can say “Thank You, Windows.Devices.SMS Namespace.” Why? Well, I honestly did not think it will be so easy. Okay, it is not easy code, but it is not too overly complicated either! What happens in this sub is set out in the following list:

  • The Sub itself has been changed to Async, because it will deal with an Asynchronous process. If you have not heard about Async yet, I suggest you read the following article: Async Programming with Visual Basic and Windows 8 / 8.1
  • It then tries to get hold of a valid SMS capable device. If it cannot find a valid device, it will do nothing; else, it will continue to the next Try & Catch block. If you have never encountered a Try & Catch block before, I recommend this (somewhat old) article: Handling Exceptions in Visual Basic
  • Inside the last Try & Catch block, it simply set up the SMS message to be sent. I provided the number to where the SMS should be sent, as well as the body of the SMS. Then, I send the message.
  • Easy as Pie!

Receiving SMSs

Add the following modular variable:

Private blnListening As Boolean

This flag indicates that the device is listening for incoming messages. Add the next code segment behind the btnRecieve button’s Click event:

Private Async Sub btnReceive_Click(ByVal sender As Object, _
   ByVal e As RoutedEventArgs) Handles btnRecieve.Click

   If sdDevice Is Nothing Then
      Try
         sdDevice = Await SmsDevice.GetDefaultAsync()
         Catch ex As Exception

         Return
      End Try
   End If

   If Not blnListening Then
      Try
         AddHandler sdDevice.SmsMessageReceived, _
            AddressOf sdDevice_SmsMessageReceived
         blnListening = True

          Catch ex As Exception

          sdDevice = Nothing
      End Try
   End If
End Sub

Also, not too complicated. There is one spanner in the works, however. Notice the AddHandler line? Well, this line creates a handler named sdDevice.SmsMessageRecieved that is the actual method that will show the SMS details—note, not the content, just the details such as where this message is from. I may talk about reading SMSs later. Add the sdDevice.SmsMessageRecieved event now:

Private Async Sub sdDevice_SmsMessageReceived(ByVal sender As _
   SmsDevice, ByVal args As SmsMessageReceivedEventArgs)
   Await Dispatcher.RunAsync(Windows.UI.Core. _
      CoreDispatcherPriority.Normal, Sub()
      ' Get message from the event args.
      Try
         Dim stMessage As SmsTextMessage = args.TextMessage
         ReceivedFromText.Text = stMessage.From
         ReceivedMessageText.Text = stMessage.Body
         Catch ex As Exception
         End Try
   End Sub)
End Sub

Not rocket science. If you have not yet read my article about Async Programming that I spoke about, I suggest you do so now.

Reading an SMS

Add another button your page and name it btnRead. Give it a content value of Read. This button will be used to read the physical SMS that has been received. Add its code now:

Private Async Sub btnRead_Click(ByVal sender As Object, _
   ByVal e As RoutedEventArgs) Handles btnRead.Click

   If sdDevice Is Nothing Then
      Try

         sdDevice = Await SmsDevice.GetDefaultAsync()
         Catch ex As Exception

         Return
      End Try
   End If

   txtSendTo.Text = ""
   txtBody.Text = ""

   Try

      Dim id As UInteger
      If id >= 1 AndAlso (id <= sdDevice.MessageStore.MaxMessages) Then

         Dim strMessage As ISmsMessage = _
            Await device.MessageStore.GetMessageAsync(id)

         Dim strTextMessage As ISmsTextMessage = _
            TryCast(strMessage, ISmsTextMessage)
         If strTextMessage Is Nothing Then


            If TypeOf strMessage Is SmsBinaryMessage Then

               strTextMessage = _
                  SmsTextMessage.FromBinaryMessage(TryCast(strMessage, _
                  SmsBinaryMessage))

            End If

         End If

         If strTextMessage IsNot Nothing Then

            txtSendTo.Text = strTextMessage.From
            txtBody.Text = strTextMessage.Body

         End If
         Else

      End If
      Catch ex As Exception

      sdDevice = Nothing
   End Try
End Sub

You should know the drill by now! First, it determines whether or not we have a valid SMS device. If it is dealing with a valid SMS device, it will continue to the next steps; else, it will not do anything. Because space is very limited, I decided not to put too many controls onto the page. So, excuse the fact that it will keep on using txtSendTo and txtBody, although for a different purpose.

The text gets cleared, and then it establishes the total number of messages received. If there are more than 0 received, it determines what type of message it is. If it is a Text message, it converts the binary message to a text message and simply displays it.

Conclusion

I hope you have enjoyed this article. Until next time, cheers!

About the Author

Hannes du Preez is a Microsoft MVP for Visual Basic for the seventh year in a row.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read