我正在使用此示例http://www.codeproject.com/KB/cs/SMS.aspx创建一个将通过手机发送短信的应用程序。当我制作一个GUI win应用程序时,一切正常,但当我尝试将其转换为Windows服务应用程序(无GUI)在后台工作时,它告诉我没有连接手机。
以下是两个非常简单的例子:
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服务
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);
}
}
}
当我启动服务时,它会将“Phone not connected”写入事件日志。我有什么想法我做错了吗?或者至少如何查明错误...
感谢。
答案 0 :(得分:0)
您需要创建计时器类的实例,并检查手机是否按特定间隔连接,而不是在onStart事件中编写电话连接代码。您可以在onstart事件中启动计时器。