我试图实现功能以允许用户选择他喜欢的表单。最喜欢的表格是他/她需要快速访问的表格。通过ToolStripMenu来避免浏览太长时间。
我尝试在应用程序配置中保存对表单的引用。但是我收到了错误
类型的价值' System.Windows.Forms.Form'无法转换为 '字符串'
Public Sub SetSetting(ByVal pstrKey As String, ByVal frmFavorite As Form)
Dim keyExists As Boolean = False
For Each strKey As String In configuration.AppSettings.Settings.AllKeys
If strKey.Equals(pstrKey) Then
configuration.AppSettings.Settings.Item(pstrKey).Value = frmFavorite
keyExists = True
End If
Next
If Not keyExists Then
configuration.AppSettings.Settings.Add(pstrKey, frmFavorite)
End If
configuration.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
End Sub
答案 0 :(得分:1)
您只能在应用程序配置文件中存储string
值,不能存储任何对象
但只需在配置文件中存储Form的名称。
启动应用程序时,通过反射创建表单,如this对象工厂示例中所示。
Public Class ObjectFactory
Public Shared Function CreateAnObject(ByVal ObjectName As String) As Object
Dim Assem = [Assembly].GetExecutingAssembly()
Dim myType As Type = Assem.GetType(ObjectName.Trim)
Dim o As Object = Nothing
Try
o = Activator.CreateInstance(myType)
Catch oEx As TargetInvocationException
MessageBox.Show(oEx.ToString)
End Try
Return o
End Function
End Class
...
Dim formName as String = configuration.AppSettings.Settings.Item(<YourSettingKey>)
Dim oForm As Form = _
ObjectFactory.CreateAnObject(formName)