不同窗体的串口调用
我用VB.NET在WINCE上编程,在第一个窗体中使用串口控件与WINCE系统的按键进行通信,获得按键值,进行命令解释,根据不同的命令值打开不同的窗体。另一个窗体也有串口控件,也是用来监视按键。我想在第一个窗体关闭时也要关闭该窗体的串口,打开第二个界面时,把第二个界面的串口打开。串口号都为4。
代码如下:
调用的窗体
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim ReadCount As Integer
ReadCount = Me.SerialPort1.BytesToRead
If ReadCount <> 3 Then
Exit Sub
End If
ReDim InByte(SerialPort1.BytesToRead - 1)
Me.SerialPort1.Read(InByte, 0, SerialPort1.BytesToRead)
Me.Invoke(New Exp(AddressOf CommandExplain))
End Sub
Private Sub CommandExplain()
Select Case InByte(1)
Case &H3B '打开电压
SerialPort1.Close()
frmVoltage.Show()
Me.Close()
Case &H3A '打开电流
lblCurrent.ForeColor = Color.Red
frmMainCurrent.Show()
Case &H39 '打开频率
lblPower.ForeColor = Color.Red
frmMainPower.Show()
Case &H38 '打开谐波畸变率
lblTHDU.ForeColor = Color.Red
frmMainHarmonicWave.Show()
Case &H37 '打开相位角
lblPhasorDiagram.ForeColor = Color.Red
Case &H36 '打开故障信息
End Select
End Sub
Private Sub frmMain_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
myPenClost_1.Dispose()
myPenclost_2.Dispose()
myPenSelect_1.Dispose()
myPenSelect_2.Dispose()
myPenAnJian.Dispose()
myGraph.Dispose()
End Sub
被调用的窗体
Private Sub frmVoltage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If SerialPort1.IsOpen = False Then
Me.SerialPort1.Open()
End If
End Sub
问题就出现在:Me.SerialPort1.Open()
请大家帮忙解决。 --------------------编程问答-------------------- 串口对象定义到模块里。就可以大家都共用了。 --------------------编程问答-------------------- 或是在某个类中定义shared的共享访问变量也可以了。 --------------------编程问答-------------------- 感谢您这么快给我回帖,但是我使用的是串口控件,并且每个窗口都有,而不是在某个模块中定义的。
--------------------编程问答-------------------- 放下vb6的想法吧
控件是什么。不过是具有设计时可见这个属性的一些类。
在任意类中。定义如下
public shared seral as new SerialPort()
就可以了
添加事件:
AddHandler seral.DataReceived , Addressof MyOnComm
public shared sub MyOnComm(参数看帮助)
end sub --------------------编程问答-------------------- 我在public class frmmain窗体类中添加不上啊 --------------------编程问答-------------------- 请您具体一点。谢谢。 --------------------编程问答--------------------
Public Class Form2
Private Sub Form2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
'窗体的Click事件
GlobalThings.serial.WriteLine("yeah")
End Sub
End Class
Public Class GlobalThings
Public Shared WithEvents serial As New IO.Ports.SerialPort()
Public Shared builder As New System.Text.StringBuilder
Private Shared Sub serial_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serial.DataReceived
builder.Append(serial.ReadExisting())
End Sub
End Class
同理,所有地方都可以这样类似form2的click的方式访问
GlobalThings.serial --------------------编程问答-------------------- 关注此题的讨论. --------------------编程问答-------------------- 可以在每个窗体中都定义一个 SerialPort,每次窗体关闭的时候,将串口关闭,以便别的窗口调用即可。
补充:.NET技术 , VB.NET