2010-06-12 103 views
2

發送短信我有這樣的代碼:C#從計算機

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(); 

我從這裏得到它:

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_22832563.html

我有一個新的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) 
     { 

     } 
    } 
} 

你能告訴我:

  1. 我究竟在哪裏粘貼代碼?
  2. 我如何獲得運行代碼?

我發送AT命令,我的手機是連接到計算機

+0

按鈕怎麼樣? – kenny 2010-06-12 01:58:54

回答

2

將工具箱中的SerialPort拖放到您的表單上。設置其屬性並雙擊DataReceived。這需要照顧前5條線。

在Load事件處理程序中,放置打開和寫入調用,以處理其餘行。

在窗體上放置一個TextBox,將其MultiLine屬性設置爲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") 
     )); 
    } 

從那裏,您可以修改窗體設計,使其更有用。也許你想添加一個Button,它的Click事件再次輪詢調制解調器。

+0

謝謝hans,到目前爲止至少我的程序編譯了,但是我還有其他問題,就像你在其他帖子中看到的一樣 – 2010-06-13 17:51:53

3

頂端代碼示例似乎表明,它應該在一個單獨的線程來運行(這將使意義),所以加開始按鈕到您的窗體並添加一個Click事件處理程序。

我剛從here那裏得到了下面的代碼,並重新格式化了一下。

在該事件處理程序編寫如下:

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_DataReceived你的代碼的期望。