![](/img/trans.png)
[英]VB.NET: Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.KeyPressEventArgs'.'
[英]how to solve Unable to cast object of type 'System.Windows.Forms.Form in VB.Net
我有以下子程序:
Public Sub MyCodes_Users_Salahiyat()
MyPubVar_Dt_Op_Salahiyat = New DataTable()
MyPubVar_Dt_Op_Salahiyat.Columns.Add("Op_ID", Type.GetType("System.String"))
MyPubVar_Dt_Op_Salahiyat.Columns.Add("FrmName", Type.GetType("System.String"))
MyPubVar_Dt_Op_Salahiyat.Columns.Add("CmdName", Type.GetType("System.String"))
MyPubVar_Dt_Op_Salahiyat.Columns.Add("FrmCaption", Type.GetType("System.String"))
MyPubVar_Dt_Op_Salahiyat.Columns.Add("CmdCaption", Type.GetType("System.String"))
Dim FormType As Type = Me.GetType().BaseType
Dim xForms As List(Of Form) =
(From t In [GetType]().Assembly.GetTypes()
Where t.IsSubclassOf(FormType) = True Select DirectCast(Activator.CreateInstance(t), Form)).ToList()
For Each xFrm In xForms
Dim xCtrl As Control = xFrm.GetNextControl(xFrm, True)
Dim xid As Integer
Do Until xCtrl Is Nothing
If xCtrl Is Nothing Then
GoTo Line1
Else
If xCtrl.GetType = GetType(Button) Then
xid = xid + 1
MyPubVar_Dt_Op_Salahiyat.Rows.Add(xid, xFrm.Name, xCtrl.Name, xFrm.Text, xCtrl.Text)
End If
End If
Line1:
xCtrl = xFrm.GetNextControl(xCtrl, True)
Loop
Next
End Sub
但是當我調用該程序時,出現以下錯誤:
無法將“CementAccSys.My.MyApplication”類型的 object 轉換為“System.Windows.Forms.Form”類型
奇怪的是,當我從另一個表單調用該過程時,錯誤不會出現!
要獲取正在運行的項目的Form
控件和每個的Button
控件:
Public Sub MyCodes_Users_Salahiyat()
MyPubVar_....
For Each f In Assembly.GetExecutingAssembly().GetTypes().
Where(Function(t) GetType(Form).IsAssignableFrom(t))
' Create a Form and dispose of it when it is no longer needed...
Using ins = DirectCast(Activator.CreateInstance(f), Form)
' You have a Form here, do what you need to do...
Console.WriteLine($"{ins.Name}, {ins.Text}")
For Each btn In GetAllControls(ins).OfType(Of Button)
' You have a button here belongs to the current Form...
Console.WriteLine($"{btn.Name}, {btn.Text}")
Next
End Using
Next
End Sub
' A recursive method to get all the controls...
Private Function GetAllControls(parent As Control) As IEnumerable(Of Control)
Dim cs = parent.Controls.OfType(Of Control)
Return cs.SelectMany(Function(c) GetAllControls(c)).Concat(cs)
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.