I'm using this example http://www.codeproject.com/KB/cs/SMS.aspx to make an application that will send SMS via mobile phone. When I make a GUI win app everything works fine, but when I try to convert that to windows service app (no GUI) to work in the background it tells me no phone connected.
Here are both, very simple, examples:
GUI app
using System;
using System.Windows.Forms;
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;
namespace SMS.Forms
{
public partial class SendSMS : Form
{
SmsSubmitPdu pdu;
private int port;
private int baudrate;
private int timeout;
public SendSMS()
{
InitializeComponent();
//phone connection
port = 3;
baudrate = 115200;
timeout = 300;
}
private void button1_Click(object sender, EventArgs e)
{
GsmCommMain comm = new GsmCommMain(port, baudrate, timeout);
try
{
comm.Open();
//send sms
pdu = new SmsSubmitPdu("Test msg", "0xxxxxxxxx", "");
comm.SendMessage(pdu);
comm.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, "Connection error: " + ex.Message, "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
MessageBox.Show(this, "Successfully connected to the phone.", "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
WIN service
using System;
using System.Diagnostics;
using System.ServiceProcess;
using GsmComm.GsmCommunication;
using GsmComm.PduConverter;
namespace SMS
{
public partial class SendSMS : ServiceBase
{
SmsSubmitPdu pdu;
//logs
private string sSource;
private string sLog开发者_如何学运维;
private string sEvent;
private int port;
private int baudrate;
private int timeout;
public SendSMS()
{
InitializeComponent();
//event logs
sSource = "SendSMS";
sLog = "SMS";
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
//phone connection
port = 3;
baudrate = 115200;
timeout = 300;
}
protected override void OnStart(string[] args)
{
//logs
sEvent = "SMS service started";
EventLog.WriteEntry(sSource, sEvent);
GsmCommMain comm = new GsmCommMain(port, baudrate, timeout);
try
{
comm.Open();
while (!comm.IsConnected())
{
sEvent = "Phone not connected";
EventLog.WriteEntry(sSource, sEvent);
comm.Close();
return;
}
//send sms
pdu = new SmsSubmitPdu("Test msg", "0xxxxxxxxx", "");
comm.SendMessage(pdu);
comm.Close();
}
catch (Exception ex)
{
sEvent = "Not done " + ex.Message;
EventLog.WriteEntry(sSource, sEvent);
return;
}
finally
{
comm.Close();
}
}
protected override void OnStop()
{
//logs
sEvent = "SMS service stopped";
EventLog.WriteEntry(sSource, sEvent);
}
}
}
When I start the service it writes "Phone not connected" to event log. Any ideas what I'm doing wrong? Or at least how to pinpoint the error...
Thanks.
Instead of writing the Phone connection code in the onStart event, you need to create instance of timer class, and check whether the phone is connected on specific intervals. You can start the timer in the onstart event.
精彩评论