日期:2011-11-03 浏览次数:20475 次
以下给出了C#.NET和VB.NET的示例代码。用Form1、Form2类分别表示主、从窗体。
1、内部成员访问法,适合于主窗体访问它所创建的从窗体对象中的成员。只需将从窗体允许主窗体访问的那些成员加上internal或Friend限定符。例如:
C#主
private void ShowForm2Info() {
Form
f2.Show();
MessageBox.Show(f2.MyName);
}
C#从
internal string MyName = "A Form2 Object";
VB主
Private Sub ShowForm2Info()
Dim f2 As New Form2
f2.Show()
MsgBox(f2.MyName)
End Sub
VB从
Friend MyName As String = "A Form2 Object"
2、将以上方法反过来用,让从窗体访问创建它的主窗体中的成员,需要增加一个步骤:在从窗体的构造函数中传入一个主窗体的引用,以便找到创建它的主窗体(新建的构造函数中不要忘了调用InitializeComponent()函数)。主窗体创建从窗体对象时传入自身的引用。例如:
C#主
private void ShowForm2() {
Form
f2.Show();
}
internal string MyName = "A Form1 Object";
C#从
private Form
public Form2(Form1 _f1) {
InitializeComponent();
f1 = _f1;
}
private void ShowForm1Info() {
MessageBox.Show(f1.MyName);
}
VB主
Private Sub ShowForm2()
Dim f2 As New Form2(Me)
f2.Show()
End Sub
Friend MyName As String = "A Form1 Object"
VB从
Private f1 As Form1
Public Sub New(ByVal _f1 As Form1)
MyBase.New()
InitializeComponent()
f1 = _f1
End Sub
Private Sub ShowForm1Info()
MsgBox(f1.MyName)
End Sub
3、从窗体访问主窗体中的成员,如果主窗体只有一个实例,或者被访问对象是全局性的,可以将主窗体中要求访问的成员设置为静态的,加上static或Shared限定符即可:
C#主
private void ShowForm2() {
Form
f2.Show();
}
internal static string MyName = "A Form1 Object";
C#从
private void ShowForm1Info() {
MessageBox.Show(Form1.MyName);
}
VB主
Private Sub ShowForm2()
Dim f2 As New Form2()
f2.Show()
End Sub
Friend Shared MyName As String = "A Form1 Object"
VB从
Private Sub ShowForm1Info()
MsgBox(Form1.MyName)
End Sub
4、还可以运用.NET的事件委托机制,实现更加灵活的相互调用。下例是从窗体激发主窗体的事件。事件委托机制的功能事实上远比此例强大,大家可以找书看看它的详细用法。
C#主
private void ShowForm2() {
Form
f2.Show();
f2.SendMessage += new Form2.DelegateOfSendMessage(ShowMessage);
}
private void ShowMessage(string str) {
MessageBox.Show(str);
}
C#从
public delegate void DelegateOfSendMessage(string str);
public event DelegateOfSendMessage SendMessage;
private void Send() {
SendMessage("A Message From Form2");
}
VB主
Private Sub ShowForm2()
Dim f2 As New Form2
f2.Show()
AddHandler f2.SendMessage, AddressOf ShowMessage
End Sub
Private Sub ShowMessage(ByVal str As String)
MsgBox(str)
End Sub
VB从
Public Delegate Sub DelegateOfSendMessage(ByVal str As Str