c#从计算机发送短信

c#从计算机发送短信,c#,text,sms,C#,Text,Sms,我有以下代码: private SerialPort port = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One); Console.WriteLine("Incoming Data:"); port.WriteTimeout = 5000; port.ReadTimeout = 5000;

我有以下代码:

private SerialPort port = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One);

                  Console.WriteLine("Incoming Data:");
                  port.WriteTimeout = 5000;
                  port.ReadTimeout = 5000;
                  // Attach a method to be called when there is data waiting in the port's buffer
                  port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

                  // Begin communications
                  port.Open();
                  #region PhoneSMSSetup
                  port.Write("AT+CMGF=1\r\n");
                  Thread.Sleep(500);
                  port.Write("AT+CNMI=2,2\r\n");
                  Thread.Sleep(500);
                  port.Write("AT+CSCA=\"+4790002100\"\r\n");
                  Thread.Sleep(500);
                  #endregion
                  // Enter an application loop which keeps this thread alive
                  Application.Run();
我从这里得到的:

我有一个新的winforms空应用程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
你能告诉我:

  • 我应该在哪里粘贴代码
  • 如何让代码运行

  • 我正在向连接到计算机的手机发送AT命令。顶部的代码示例似乎表明它应该在单独的线程中运行(这很有意义),因此在表单中添加一个开始按钮,并向其添加一个
    单击
    事件处理程序

    我只是从下面的代码中抓取并重新格式化了一点

    在该事件处理程序中,编写如下内容:

    ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
    Thread myThread = new Thread(myThreadDelegate);
    myThread.Start();
    
    然后创建一个如下所示的类:

    public class ThreadWork 
    {
       public static void DoWork()
       {
           // put your top half code in here, the bit that does the actual serial communication
       }
    }
    

    然后添加代码所需的事件处理程序
    port\u DataReceived

    将SerialPort从工具箱中拖到表单上。设置其属性并双击DataReceived。这就解决了前5行

    在Load事件处理程序中,放置Open和Write调用,这将处理其余的行

    在窗体上放置文本框,将其多行属性设置为True。在DataReceived事件处理程序中编写以下代码:

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {
            string response = serialPort1.ReadLine();
            this.BeginInvoke(new MethodInvoker(
                () => textBox1.AppendText(response + "\r\n")
            ));
        }
    

    从那里,您可以修改表单设计,使其更有用。也许您想添加一个按钮,该按钮的单击事件将再次轮询调制解调器。

    谢谢您,hans,到目前为止,至少我的程序已经编译好了,但正如您在另一篇帖子中看到的,我还有其他问题