我正在使用这个示例http://www.codeproject.com/KB/cs/SMS.aspx来制作一个应用程序,它将通过移动电话发送短信。当我创建一个GUI win应用程序时,一切运行正常,但当我尝试将其转换为windows服务应用程序(无GUI)以在后台工作时,它告诉我没有连接电话。
下面是两个非常简单的例子:
GUI应用程序
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);
}
}
}赢得服务
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“。你知道我做错了什么吗?或者至少如何定位错误..。
谢谢。
发布于 2011-03-24 20:23:20
您不需要在onStart事件中编写电话连接代码,而是需要创建timer类的实例,并检查电话是否按特定时间间隔连接。您可以在onstart事件中启动计时器。
https://stackoverflow.com/questions/5418978
复制相似问题