我知道有一些问题需要考虑c#串口接收和写入,但我没有找到有用的解决方案。我在c#windows应用程序中编写了一个小程序。此应用程序允许用户使用移动miscall登录。我无法提取从串口收到的数据。我想从输出中提取手机号码,但没有运气。贝娄是我的代码请告诉我如何从输出中提取手机号码并将其显示在密码字段中。感谢
SerialPort port = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
private void Login_Load(object sender, EventArgs e)
{
port.RtsEnable = true;
port.DtrEnable = true;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
if (!port.IsOpen) port.Open();
port.Write("AT+CLIP=1" + Environment.NewLine);
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtPassword.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtPassword.Text = text;
}
}
protected void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var currentPort = (SerialPort)sender;
string result = currentPort.ReadExisting();
MessageBox.Show(result);
//if (!result.Contains("\r\nRING\r\n")) return;
//currentPort.Write("AT+CHUP" + Environment.NewLine);
//txtPassword.Text = result.Split('\"')[1];
//SetText(result.Split('\"')[1]);
//port.Write("AT+CHUP" + Environment.NewLine);
}
private void button1_Click(object sender, EventArgs e)
{
LoginUser();
}
从端口收到的数据如下。我想从中提取手机号码。我是C#的新手:
RING +CLIP: "032232323423",161,"",0,"",0
当我尝试打印此代码时:SetText(result.Split('\“')[1]); 它给我错误[索引超出范围]。
答案 0 :(得分:0)
在DataReceived事件中,您可以这样读:
byte[] buffer = new buffer[1024];
int readBytes = port.Read(buffer, 0, port.BytesToRead);
无论如何,我想你可以得到这样的电话号码:
int firstMark = result.IndexOf('\"');
result.SubString(firstMark, result.IndexOf('\"', firstMark + 1) - firstMark);