使用名称作为字符串调用单独的 Windows 窗体 [英] Calling a separate Windows Form using its name as a String
问题描述
我需要能够创建一个按钮,当我单击按钮时,该按钮可以链接到不同的 Windows 窗体.但是,此按钮是动态生成的,有时可以根据需要链接到不同的表单.例如:
I need to be able to create a Button that can link to a different Windows Form when I click the Button. However, this Button is dynamically generated and can sometimes link to different Forms as per required. For example:
我的按钮可以链接到 FormA.vb 或 FormB.vb.我可以让按钮根据需要创建字符串FormA"或FormB",但我不知道如何将 FormA.vb 或 FormB.vb 调用到屏幕上.
My Button can link to either FormA.vb or FormB.vb. I can make the Button create the String "FormA" or "FormB" as necessary, but I don't know how to call FormA.vb or FormB.vb to the screen.
到目前为止,我一直在使用以下方法更改 Windows 窗体:
Thus far, I have been changing Windows Forms by using:
FormA.MdiParent = MainForm //My main form window
FormA.Show()
Me.Close()
但这显然不适用于:
"FormA".MdiParent = MainForm
"FormA".Show()
仅仅因为它们是字符串而不是类.
Simply because they are Strings and not classes.
有没有办法让我的 Button 链接正确?
Is there a way to make my Button link correctly?
提前致谢.
推荐答案
试试这个,你必须导入System.Windows.Forms
和System.Reflection
Try this, you have to import System.Windows.Forms
and System.Reflection
首先将表单名称放入strCreatedFromButton
然后找到它.
First get the form name into the strCreatedFromButton
then find it.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strCreatedFromButton As String = "Form3"
Dim frm As New Form
frm = DirectCast(CreateObjectInstance(strCreatedFromButton), Form)
frm.Show()
End Sub
Public Function CreateObjectInstance(ByVal objectName As String) As Object
Dim obj As Object
Try
If objectName.LastIndexOf(".") = -1 Then
objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
End If
obj = [Assembly].GetEntryAssembly.CreateInstance(objectName)
Catch ex As Exception
obj = Nothing
End Try
Return obj
End Function
这篇关于使用名称作为字符串调用单独的 Windows 窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!