短信服务






4.71/5 (12投票s)
通过GSM调制解调器发送短信的服务
引言
本文将提供通过GSM调制解调器从您的计算机向任何手机发送短信的基本功能。
Using the Code
#region Private Declaration for the main thread
private Thread m_MailThread = null;
#endregion
#region Constructor
/// <summary>
/// Constructor for InitializeComponent
/// </summary>
public MySmsService()//Change MySmsService to your Service Class Name
{
InitializeComponent();
}
#endregion
#region OnStart Event of the service
protected override void OnStart(string[] args)
{
EvtlgSmsService.WriteEntry("MySmsService started!!");
if (m_MailThread == null)
m_MailThread = new Thread(new ThreadStart(SMSThread));
m_MailThread.Start();
}
#endregion
#region OnStop Event of the service
protected override void OnStop()
{
EvtlgSmsService.WriteEntry("MySmsService stopped !!.");
if (serialPort1.IsOpen)
serialPort1.Close();
m_MailThread.Abort();
}
#endregion
#region Sms Main thread
/// <summary>
/// Sms main thread
/// </summary>
private void SMSThread()
{
do
{
Thread.Sleep(30000);
SendSMS();
}
while (1 == 1);
}
#endregion
#region Send Sms function
/// <summary>
/// SendSMS for sending the SMS
/// </summary>
private void SendSMS()
{
SendSMS("+91000000000", "Hello This is a test message");
//+91 is the country code and followed by phone number
}
#endregion
#region Function for sending the Sms
/// <summary>
/// Overloaded send SMS for sending the SMS
/// </summary>
/// <param name="phoneNumber"></param>
/// <param name="message"></param>
private void SendSMS(String phoneNumber, String message)
{
try
{
if (!serialPort1.IsOpen)
serialPort1.Open();
serialPort1.Write("AT+CMGF=1" + (Char)13);
serialPort1.Write(String.Format("AT+CMGS=\"{0}\"" + (Char)13, phoneNumber));
serialPort1.Write(String.Format("{0}" + (Char)26 + (Char)13, message));
EvtlgSmsService.WriteEntry("SMS sent successfully");
}
catch (Exception e)
{
EvtlgSmsService.WriteEntry("SMS sending failed:" + e.Message);
}
}
#endregion
}
只需复制上面的代码并将其粘贴到您的Windows服务的Service
类中。在设计器中添加一个串口组件和一个事件日志。将GSM手机或调制解调器连接到您的计算机。检查调制解调器连接到哪个端口 - 该端口应在SerialPort1.portname
中指定。您还应确保您的调制解调器支持文本模式下的命令。使用超终端和AT命令检查您的调制解调器。
历史
- 2007年12月13日:初始发布