C#手機程序開發

如今手機已成爲大衆的交流工具。有關手機的程序開發越來越廣泛,本節通過幾個典型實例介紹如何利用短信貓發送、接收短信、遠程控制計算機、業務員銷售數據採集和短信息娛樂互動平臺。
實例431 利用短信貓收發短信息
實例說明
短信貓是利用SIM卡發送短信的硬件設備,通過串口或USB接口(根據設備型號而定)與計算機相連。在程序中可以利用短信貓發送或接收短信。本例實現了利用短信貓收發短信息的功能。實例運行結果如圖13.15所示。
文本框:圖13.15  利用短信貓收發短信息技術要點
本例使用的是北京人大金倉信息技術有限公司的串口短信貓。在購買短信貓時會附帶包括SDK的開發包,其中提供了操作短信貓的函數(封裝在dllforvc.dll動態庫中)。下面介紹操作短信貓的主要函數。
(1)GSMModemGetSnInfoNew函數
該函數獲取短信貓註冊需要的信息,代碼如下:
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetSnInfoNew",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetSnInfoNew(string device, string baudrate);
參數說明如下。
l     device:通信端口,爲null時系統會自動檢測。
l     baudrate:通訊波特率,爲null時系統會自動檢測。
(2)GSMModemGetDevice函數
該函數獲取當前的通訊端口,代碼如下:
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetDevice",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetDevice();
(3)GSMModemGetBaudrate函數
該函數獲取當前的通訊波特率,代碼如下:
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetBaudrate",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetBaudrate();
(4)GSMModemInitNew函數
該函數用於初始化短信貓。語法如下:
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemInitNew",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern bool GSMModemInitNew(
        string device,
        string baudrate,
        string initstring,
        string charset,
        bool swHandshake,
        string sn);
參數說明如下。
l     device:標識通信端口,如果爲NULL,系統會自動檢測。
l     baudrate:標識通訊波特率,如果爲NULL,系統會自動檢測。
l     initstring:標識初始化命令,爲NULL即可。
l     charset:標識通訊字符集,爲NULL即可。
l     swHandshake:標識是否進行軟件握手,爲False即可。
l     sn:標識短信貓的授權號,需要根據實際情況填寫。
(5)GSMModemSMSsend函數
該函數用於發送手機短信。語法如下:
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemSMSsend",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern bool GSMModemSMSsend(
        string serviceCenterAddress,
        int encodeval,
        string text,
        int textlen,
        string phonenumber,
        bool requestStatusReport);
參數說明如下。
l     serviceCenterAddress:標識短信中心號碼,爲NULL即可。
l     encodeval:標識短信息編碼格式,如果爲8,表示中文短信編碼。
l     text:標識短信內容。
l     textlen:標識短信內容的長度。
l     phonenumber:標識接收短信的電話號碼。
l     requestStatusReport:標識狀態報告。
(6)GSMModemSMSReadAll函數
該函數取得所有短信息,包括SIM卡和手機中的短信息。返回的短信內容格式爲電話號碼1|短信內容1||電話號碼2|短信內容2||:
    //接收短信息返回字符串格式爲:手機號碼|短信內容||手機號碼|短信內容||
    //RD_opt爲1表示接收短信息後不做任何處理,爲0表示接收後刪除信息
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemSMSReadAll",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemSMSReadAll(int RD_opt);
參數說明如下。
l     RD_opt:對讀取後的短信息進行處理,0表示刪除,1表示不做處理。
實現過程
(1)新建一個項目,命名爲Ex13_14,默認窗體爲Form1。
(2)在Form1窗體中,主要添加TextBox控件和Label控件,控件的數量及用途如圖13.15所示,添加兩個Button控件,分別用於發送短信息和接收短信息。
(3)主要程序代碼。
將所使用的函數封裝在GMS類中。代碼如下:
class GMS
{
    //初始化gsm modem,並連接gsm modem
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemInitNew",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern bool GSMModemInitNew(
        string device,
        string baudrate,
        string initstring,
        string charset,
        bool swHandshake,
        string sn);
    //獲取短信貓新的標識號碼
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetSnInfoNew",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetSnInfoNew(string device, string baudrate);
    //獲取當前通訊端口
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetDevice",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetDevice();
    //獲取當前通訊波特率
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetBaudrate",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetBaudrate();
    //斷開連接並釋放內存空間       
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemRelease",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern void GSMModemRelease();
    //取得錯誤信息   
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemGetErrorMsg",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemGetErrorMsg();
    //發送短信息
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemSMSsend",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern bool GSMModemSMSsend(
        string serviceCenterAddress,
        int encodeval,
        string text,
        int textlen,
        string phonenumber,
        bool requestStatusReport);
    //接收短信息返回字符串格式爲:手機號碼|短信內容||手機號碼|短信內容||
    //RD_opt爲1接收短信息後不做任何處理,0爲接收後刪除信息
    [DllImport("dllforvc.dll",
         EntryPoint = "GSMModemSMSReadAll",
         CharSet = CharSet.Ansi,
         CallingConvention = CallingConvention.StdCall)]
    public static extern string GSMModemSMSReadAll(int RD_opt);
}
在裝載Form1窗體時,獲取設備信息。代碼如下:
        private void Form1_Load(object sender, EventArgs e)
        {
            //機器號碼,當參數爲空時,函數自動獲取設備信息
            txtJQHM.Text = GMS.GSMModemGetSnInfoNew(txtCOM.Text, txtBTL.Text);
            txtCOM.Text = GMS.GSMModemGetDevice();  //COM1
            txtBTL.Text= GMS.GSMModemGetBaudrate();  //波特率
        }
發送短信息。代碼如下:
        private void btnSend_Click(object sender, EventArgs e)
        {
               if(txtSJHM.Text == "")
               {
           MessageBox.Show("手機號碼不能爲空!","提示", MessageBoxButtons.OK);
                   txtSJHM.Focus();
                   return;
               }
               if(txtContent.Text=="")
               {
           MessageBox.Show("短信內容不能爲空!", "提示", MessageBoxButtons.OK);
                   txtContent.Focus();
                   return;
               }
               //連接設備
               if(GMS.GSMModemInitNew(txtCOM.Text, txtBTL.Text, null, null, false, txtPower.Text)==false)
               {
                   MessageBox.Show("設備連接失敗!" + GMS.GSMModemGetErrorMsg(),"提示", MessageBoxButtons.OK);
                   return;
               }
               // 發送短信
               if (GMS.GSMModemSMSsend(null, 8, txtContent.Text, Encoding.Default.GetByteCount(txtContent.Text),txtSJHM.Text, false) == true)
                   MessageBox.Show("短信發送成功!", "提示", MessageBoxButtons.OK);
               else
                   MessageBox.Show("短信發送失敗!" + GMS.GSMModemGetErrorMsg(), "提示", MessageBoxButtons.OK);
        }
接收短信息。代碼如下:
        private void btnResvice_Click(object sender, EventArgs e)
        {
            //1)連接設備
            if (GMS.GSMModemInitNew(txtCOM.Text, txtBTL.Text, null, null, false, txtPower.Text) == false)
            {
                MessageBox.Show("連接失敗!" + GMS.GSMModemGetErrorMsg(), "提示", MessageBoxButtons.OK);
                return;
            }
            //2)接收短信
            txtContent.Text = GMS.GSMModemSMSReadAll(1);
            txtSJHM.Text = txtContent.Text.Substring(0, 13);
            txtContent.Text = txtContent.Text.Substring(13, txtContent.Text.Length-13);
        }
舉一反三
根據本實例,讀者可以開發以下程序。
*  利用短信貓羣發短信。
*  辦公自動化系統,辦公短信通知、短信日程提醒、應急信息短信發佈和短信審批等。
實例432 利用短信遠程關閉計算機
實例說明
本例實現了利用短信遠程關閉計算機的功能。運行程序,首先,進行關機信息設置;然後,開啓服務;最後,通過手機向短信貓發送“關機”數據。片刻之後,指定的計算機將會自動關機。程序如圖13.16所示。
文本框:圖13.16  利用短信遠程關閉計算機技術要點
相關函數請參見實例“利用短信貓收發短信息”中的技術要點。
實現過程
(1)新建一個項目,命名爲Ex13_15,默認窗體爲Form1。
(2)在Form1窗體中,主要添加TextBox控件和Label控件,控件的數量及用途如圖13.16所示,添加一個Button控件,用於開啓或停止遠程關閉計算機服務。
(3)主要程序代碼。
        private void Form1_Load(object sender, EventArgs e)
        {
           //機器號碼
            txtJQHM.Text = GMS.GSMModemGetSnInfoNew(txtCOM.Text, txtBTL.Text); 
            txtCOM.Text = GMS.GSMModemGetDevice();  //COM1
            txtBTL.Text = GMS.GSMModemGetBaudrate();  //波特率
            labStatus.Text = "服務關閉中。。。。。";
        }
        private void Close_Windows()
        {
            try
            {
                //指定生成 WMI 連接所需的所有設置
                ConnectionOptions op = new ConnectionOptions();
                op.Username = txtUser.Text;  //遠程計算機用戶名稱
                op.Password = txtPWD.Text;   //遠程計算機用戶密碼
                //設置操作管理範圍
         ManagementScope scope = new ManagementScope("////" + txtIP.Text + "//root//cimv2", op);
                scope.Connect();  //將此 ManagementScope 連接到實際的 WMI 範圍。
                ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
             ManagementObjectSearcher query = new ManagementObjectSearcher(scope, oq);
                //得到WMI控制
                ManagementObjectCollection queryCollection = query.Get();
                foreach (ManagementObject obj in queryCollection)
                {
                  obj.InvokeMethod("ShutDown", null); //執行關閉遠程計算機
                }
            }
            catch(Exception ex)
            {
                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.WriteLine("shutdown /s");
                p.StandardInput.WriteLine("exit");
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            //連接設備
            if (GMS.GSMModemInitNew(txtCOM.Text, txtBTL.Text, null, null, false, txtPower.Text) == false)
            {
                MessageBox.Show("連接失敗!" + GMS.GSMModemGetErrorMsg(), "提示", MessageBoxButtons.OK);
                return;
            }
            //接收短信
            string str = GMS.GSMModemSMSReadAll(1);
            if (str==null)
                return;
            if (str.Substring(str.IndexOf("|")+1, 2) == "關機")
            {
                this.Close_Windows();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "開啓服務")
            {
                timer1.Enabled = true;
                labStatus.Text = "關機命令採集中。。。。。";
                button1.Text = "停止服務";
            }
            else
            {
                timer1.Enabled = false;
                button1.Text = "開啓服務";
                labStatus.Text = "服務關閉中。。。。。";
            }
        }
舉一反三
根據本實例,讀者可以實現以下功能。
*  利用短信實現客戶資料查詢。
*  保險行業中:保單查詢、續費提醒、客戶生日提醒和保費計算等。
實例433 短信息採集菸草銷售數據
實例說明
在各類銷售行業中,產品銷售數據量是企業不可缺少的一項數據。當銷售人員在外地出差並且在沒有計算機的情況下,如何及時的將銷售數據彙報到公司中呢?
本例實現利用短信息採集菸草銷售數據的功能。銷售人員根據規定的格式編輯短信發送到短信息貓中即可。運行程序,單擊【菸草銷售信息採集】按鈕採集菸草銷售數據,然後單擊【統計】按鈕,將銷售數據整理出來。如圖13.17所示。
技術要點
相關函數請參見實例“利用短信貓收發短信息”中的技術要點。
另外,程序規定的編輯短信息格式爲,以冒號“:”分隔並結束。例如“張三:業務員:12:長春:3400:”。其中,主要使用String.Split( )方法將信息數據拆分。
圖13.17  短信息採集菸草銷售數據
String.Split( )方法:返回包含此實例中的子字符串(由指定 Char 數組的元素分隔)的 String 數組。
語法:
public string[] Split (
    params char[] separator
)
參數說明如下。
l     separator:分隔此實例中子字符串的 Unicode 字符數組,不包含分隔符的空數組或空引用。
l     返回值:一個數組,其元素包含此實例中的子字符串,這些子字符串由 separator 中的一個或多個字符分隔。
實現過程
(1)新建一個項目,命名爲Ex13_16,默認窗體爲Form1。
(2)在Form1窗體中,主要添加TextBox控件和Label控件,控件的數量及用途如圖13.17所示,添加3個Button控件,分別用於發送短信息、採集銷售數據和整理採集數據,添加兩個DataGridView表格,分別用於顯示短信息內容和整理後的銷售數據。
(3)主要程序代碼。
單擊【菸草銷售信息採集】按鈕,接受短信息並保存到數據庫中。代碼如下:
          private void btnResvice_Click(object sender, EventArgs e)
        {
            //連接設備
            if (GMS.GSMModemInitNew(txtCOM.Text, txtBTL.Text, null, null, false, txtPower.Text) == false)
            {
                MessageBox.Show("連接失敗!" + GMS.GSMModemGetErrorMsg(), "提示", MessageBoxButtons.OK);
                return;
            }
            //接收短信
            string content = GMS.GSMModemSMSReadAll(0);
            if (content ==null)
            {
                this.getMessage();
                return;
            }
            content= content.Replace("||", "|"); // 替換||爲|
            string[] str_sp = content.Split('|');// 進行分離
            int k=0;
            dataGridView1.ColumnCount = 2;
            dataGridView1.RowCount = str_sp.Length / 2;
            dataGridView1.Columns[0].HeaderText = "手機號碼";
            dataGridView1.Columns[1].HeaderText = "短信息";
            for (int i = 0; i < str_sp.Length / 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    dataGridView1[j, i].Value = str_sp[k];
                    if (k % 2 != 0)
                        this.InsertMessage("insert into RecivedBox (Mobile,Content,reciveTime)values('" + Convert.ToString(dataGridView1[0, i].Value) + "','" + Convert.ToString(dataGridView1[1, i].Value) + "','" + DateTime.Now.ToString() + "') ");
                    k++;
                }
            }
            this.getMessage();
        }
自定義方法getSplitMessage()用來拆分短信息並且整理爲正規數據。代碼如下:
        private void getSplitMessage()
        {
            string content = "";
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                content = content + Convert.ToString(dataGridView1["短信息", i].Value);
            }
            string[] str_sp = content.Split(':');// 進行分離
            int k = 0;
            dataGridView2.ColumnCount = 5;
            dataGridView2.RowCount = str_sp.Length/5 ;
            dataGridView2.Columns[0].HeaderText = "姓名";
            dataGridView2.Columns[1].HeaderText = "職務";
            dataGridView2.Columns[2].HeaderText = "月份";
            dataGridView2.Columns[3].HeaderText = "銷售地區";
            dataGridView2.Columns[4].HeaderText = "銷售數量";
            for (int i = 0; i < str_sp.Length / 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    dataGridView2[j, i].Value = str_sp[k];
                    k++;
                }
            }
        }
自定義InsertMessage()方法,將接受的短信息保存到數據庫中。代碼如下:
        private void InsertMessage(string strSql)
        {
            //將短信息內容添加到數據庫中
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "message.mdb" + ";Persist Security Info=False");
            con.Open();
            OleDbCommand cmd = new OleDbCommand(strSql, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
自定義getMessage()方法,獲取數據庫中所有的短信息數據。代碼如下:
        private void getMessage()
        {
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "message.mdb" + ";Persist Security Info=False");
            OleDbDataAdapter dap = new OleDbDataAdapter("select mobile as 手機號碼,content as 短信息,reciveTime as 日期 from RecivedBox", con);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0].DefaultView;
        }
調用自定義getSplitMessage()方法,將整理後的銷售數據顯示在DataGridView表格中。代碼如下:
        private void btnFind_Click(object sender, EventArgs e)
        {
            if(dataGridView1.Rows.Count>0)
            this.getSplitMessage();
        }
舉一反三
根據本實例,讀者可以實現以下功能。
*  利用短信實現銷售業績查詢。
*  利用短信實現訂購商品。
實例434 “春晚”節目評比短信息互動平臺
實例說明
在觀看娛樂電視節目中,主持人經常帶動場外的電視觀衆參與到活動當中。例如,在春節聯歡晚會中,通過編輯短信來選取觀衆最喜歡的春晚節目,那麼本實例將實現爲“春晚”節目評比的短信息互動平臺。電視觀衆根據規定的格式編輯短信發送到短信息互動平臺進行節目評比。運行程序,單擊【獲取參與觀衆短信】按鈕,即可得到觀衆的投票,如圖13.18所示。
文本框:圖13.18  短信息採集菸草銷售數據技術要點
相關函數請參見實例“利用短信貓收發短信息”中的技術要點。
實現過程
(1)新建一個項目,命名爲Ex13_17,默認窗體爲Form1。
(2)在Form1窗體中,主要添加TextBox控件和Label控件,控件的數量及用途如圖13.18所示,添加一個Button控件,用於獲取參與的觀衆短信息,添加一個DataGridView控件,用於顯示觀衆的投票信息。
(3)主要程序代碼。
        private void btnResvice_Click(object sender, EventArgs e)
        {
            //連接設備
            if (GMS.GSMModemInitNew(txtCOM.Text, txtBTL.Text, null, null, false, txtPower.Text) == false)
            {
                MessageBox.Show("連接失敗!" + GMS.GSMModemGetErrorMsg(), "提示", MessageBoxButtons.OK);
                return;
            }
            //接收短信
            string content = GMS.GSMModemSMSReadAll(0);
            if (content == null)
            {
                this.getMessage();
                return;
            }
            content = content.Replace("||", "|"); // 替換||爲|
            string[] str_sp = content.Split('|');// 進行分離
            int k = 0;
            string[,] str_Sp = new string[2, str_sp.Length / 2];
            for (int i = 0; i < str_sp.Length / 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    str_Sp[j, i] = str_sp[k];
                    if (k % 2 != 0)
                        this.InsertMessage("insert into RecivedBox (Mobile,Content,reciveTime)values('" + Convert.ToString(str_Sp[0, i]) + "','" + Convert.ToString(str_Sp[1, i]) + "','" + DateTime.Now.ToString() + "') ");
                    k++;
                }
            }
            this.getMessage();
        }
        private void getMessage()
        {
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "message.mdb" + ";Persist Security Info=False");
            OleDbDataAdapter dap = new OleDbDataAdapter("select mobile as 手機號碼,content as 短信息,reciveTime as 日期 from RecivedBox", con);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0].DefaultView;
        }
        private void InsertMessage(string strSql)
        {
            //將短信息內容添加到數據庫中
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "message.mdb" + ";Persist Security Info=False");
            con.Open();
            OleDbCommand cmd = new OleDbCommand(strSql, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
舉一反三
根據本實例,讀者可以實現以下功能。
*  手機短信息平臺訂購商品
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章