vb.net是在vb的基础上更进一步的接近了面向对象编程的思想,在继承一部分发现窗体的继承比较和以前不同,在以前没怎么遇到过这类的问题,下面以一个小例子,来总结一下窗体继承的用法和好处:
1、首先新建一个项目,窗体布局如下:
以这个窗体为父窗体,然后继承出两个窗体form1和form2.继承的方法如下:
(1)首先运行form1生成EXE文件,然后在【项目】中选择【添加新项】
(2)然后选择【Windows Forms】左侧,在选择【继承的窗体】
(3)然后选择你的父窗体的位置,点击确定即可!
重复上述过程,我们可以添加多个子窗体,此时我们的【解决方案管理器】窗口如下图:
此时我们就得到了和父窗体一样的窗体布局,但是我们还可以在原有的基础上,添加控件,重新布局子窗体(但是我们不能修改从父窗体中继承的控件)
三个红框内的控件是在父窗体中继承得到的。用同样的方法可以得到form3。
代码如下:
Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Me.Visible = False intstep -= 1 If intstep = 0 Then frm1.Visible = True End If If intstep = 1 Then frm2.Visible = True End If End Sub Protected Shared intstep As Integer, strname, strpass As String, strEmail As String Protected Shared strmemo As Integer Protected Shared frm2 As New Form2 Protected Shared frm1 As New Form1 Protected Shared frm3 As New Form3 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Me.Visible = False intstep += 1 Select Case intstep Case 1 frm2.Visible = True Case 2 frm3.TxtName.Text = strname frm3.TxtPassword.Text = strpass frm3.TxtFoxmail.Text = strEmail frm3.Visible = True End Select End Sub End Class
Public Class Form2 Private Sub TxtUserName_TextChanged(sender As Object, e As EventArgs) Handles TxtUserName.TextChanged strname = TxtUserName.Text End Sub Private Sub TxtFoxmail_TextChanged(sender As Object, e As EventArgs) Handles TxtFoxmail.TextChanged strEmail = TxtFoxmail.Text End Sub Private Sub TxtPassword_TextChanged(sender As Object, e As EventArgs) Handles TxtPassword.TextChanged End Sub Private Sub TxtPassword1_TextChanged(sender As Object, e As EventArgs) Handles TxtPassword1.TextChanged If TxtPassword.Text = TxtPassword1.Text Then strpass = TxtPassword.Text Button2.Enabled = True Else MsgBox("你输入的密码不一致") Button2.Enabled = False End If End Sub End Class
在设计时,当生成包含基窗体的项目时,对基窗体外观所做的更改(属性的设置或控件的增减)将在继承的窗体上反映。仅将更改保存到基窗体是不够的。若要生成项目,请从“生成”菜单选择“生成”。 在我们做有多个相似功能的窗体的时候,我们可以考虑用窗体的继承,这样可以为我们节省很多的时间和精力,并且使我们的程序更职业化。