I am trying to figure out how to invoke a method of a child form which is opened in a using block.
In my code, I have a MainForm which is a MDI parent. MDI parent holds a reference of parent form . A parent form where the below method is declared.
-
The ParentForm Instance is available in MDIParent form as shown in the following code.
MainForm.cs
private void OpenParentForm() { try { FormParent frmParent = null; frmParent = Application.OpenForms["frmParent"] as FormParent; if (frmParent != null) { frmParent.Focus(); } else { frmParent = new FormParent(); frmParent.Name = "frmParent"; frmParent.MdiParent = this; frmParent.Show(); } } catch { } }
-
The Child form is opened in
frmParent.cs
private void ShowChildForm() { try { using (ChildForm frmChild = new ChildForm()) { if (frmChild.ShowDialog() == DialogResult.OK) this.RefreshData(); frmChild.Dispose(); } } catch { } }
The ChildForm having following method.
ChildForm.cs
private void ChildMethod()
{
//........
//........
//........
}
Following is my InvokeMethod
ReflectionHelper.cs
public static async Task<bool> InvokeMethod(Form Window, string methodName, object param)
{
try
{
Form mainWindow = Window;
var MainWindowtype = mainWindow.GetType();
MethodInfo MethodtoInvoke = MainWindowtype.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (MethodtoInvoke != null)
{
ParameterInfo[] pars = MethodtoInvoke.GetParameters();
object[] Parameter = null;
try
{
object returnValue = null;
if (pars != null && pars.Length > 0)
{
Parameter = new object[pars.Length];
foreach (var item in pars)
{
int index = item.Position;
if (param != null)
{
if (param.GetType() == item.ParameterType || item.ParameterType == typeof(object))
{
Parameter[index] = param;
}
}
}
returnValue = MethodtoInvoke.Invoke(mainWindow, Parameter);
}
else
returnValue = MethodtoInvoke.Invoke(mainWindow, null);
}
catch (Exception ex)
{
MessageBox.Show("Exception InvokeMethod \n" + ex.Message);
}
}
}
catch (Exception ex)
{
return false;
}
return true;
}
Currently, I am able to invoke Parentform instance methods which are available in MainForm.
Helper.cs
public class Helper
{
private async void OpenParentForm()
{
ReflectionHelper.InvokeMethod(static Instance of MainForm, MethodName, null);
}
}
I want to invoke MainForm>>frmParent>>[Instance of ChildForm in using block of frmParent.cs].ChildMethod()
Aucun commentaire:
Enregistrer un commentaire