關於窗體之間的傳值我在《編程技巧與維護》雜誌上寫過總結文章,比較久遠了。編程
開始的時候,用下面的方法傳遞,程序運行正常。ide
Form1 f1 = this.Owner as Form1;
//Form1 f1 = (Form1)this.Owner;(這樣寫也能夠)
f1.DawnCommPortProperty.sPort = CBCommPort.Text;//串口號
f1.DawnCommPortProperty.sBaudRate = CBBaudRate.Text;//波特率
f1.DawnCommPortProperty.sStopBit = CBStopBit.Text;//中止位
f1.DawnCommPortProperty.sDataBit = CBDataBit.Text;//數據位
f1.DawnCommPortProperty.sParity = CBParity.Text;//奇偶校驗位
f1.DawnCommPortProperty.sDataFormat = CBDataFormat.Text;//數據格式
f1.DawnCommPortProperty.sReadTimeout = textBox1.Text;//超時讀取時間
this.DialogResult = DialogResult.OK;
this.Close();this
但是在編輯環境下總提示警告信息,讓人感受很彆扭。orm
想着換一種寫法,結果折騰了快一個晚上。string
後面仍是用委託來作,沒有警告提示信息,程序運行也正常。it
Form1 f1 = new Form1();
TMPCommPortProperty.sPort = CBCommPort.Text;//串口號
TMPCommPortProperty.sBaudRate = CBBaudRate.Text;//波特率
TMPCommPortProperty.sStopBit = CBStopBit.Text;//中止位
TMPCommPortProperty.sDataBit = CBDataBit.Text;//數據位
TMPCommPortProperty.sParity = CBParity.Text;//奇偶校驗位
TMPCommPortProperty.sDataFormat = CBDataFormat.Text;//數據格式
TMPCommPortProperty.sReadTimeout = textBox1.Text;//超時讀取時間
TransmitEvent(TMPCommPortProperty);
this.DialogResult = DialogResult.OK;
this.Close();
由於傳遞的是一個結構體,因此要在窗體中進行聲明:event
public delegate void TransmitDelegate(Form1.isCPPropertys Minevalue);
public event TransmitDelegate TransmitEvent;
public Form1.isCPPropertys TMPCommPortProperty = new Form1.isCPPropertys("", "", "", "", "", "", "");class
下面是在父窗體中進行的操做:技巧
public struct isCPPropertys
{
public string sPort;//串口號
public string sBaudRate;//波特率
public string sDataBit;//數據位
public string sParity;//校驗位
public string sStopBit;//中止位
public string sDataFormat;//數據格式
public string sReadTimeout;//超時讀取時間
public isCPPropertys(string S1,string S2,string S3,string S4,string S5,string S6,string S7)
{
sPort = S1;
sBaudRate = S2;
sDataBit = S3;
sParity = S4;
sStopBit = S5;
sDataFormat = S6;
sReadTimeout = S7;
}
};程序
public isCPPropertys DawnCommPortProperty = new isCPPropertys("","","","","","","");
最後就是打開子窗體的動做了:
FrmSetCommPort Frm1 = new FrmSetCommPort();
//Frm1.ShowDialog(this);(用this來表示父窗體,前面的強制轉換用到的)
Frm1.TransmitEvent += Transmit;
if (Frm1.ShowDialog() == DialogResult.OK)
{
YBDWCommPort.CommPortProperty.sPort = DawnCommPortProperty.sPort;//串口號
YBDWCommPort.CommPortProperty.sBaudRate = DawnCommPortProperty.sBaudRate;//波特率
YBDWCommPort.CommPortProperty.sStopBit = DawnCommPortProperty.sStopBit;//中止位
YBDWCommPort.CommPortProperty.sDataBit = DawnCommPortProperty.sDataBit;//數據位
YBDWCommPort.CommPortProperty.sParity = DawnCommPortProperty.sParity;//奇偶校驗位
YBDWCommPort.CommPortProperty.sDataFormat = DawnCommPortProperty.sDataFormat;//數據格式
YBDWCommPort.CommPortProperty.sReadTimeout = DawnCommPortProperty.sReadTimeout;//超時讀取時間
YBDWCommPort.SetCommPortProperty();
//啓動偵聽,接收串口數據
YBDWCommPort.OnReceiveMsg += OnReceiveMsg;
YBDWCommPort.Start();
this.button1.Text = "關閉串口";
}
結構體直接賦值。
public void Transmit(isCPPropertys PSPCPPropertys) { DawnCommPortProperty = PSPCPPropertys; }