![](/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.