Control interoperation instances between parent and child Windows in C

  • 2020-12-19 21:10:09
  • OfStack

This article gives an example of how controls interoperate between parent and child Windows in C#. Share to everybody for everybody reference. The specific analysis is as follows:

Many people agonize over how to manipulate controls on a primary form in a child form, or how to manipulate controls on a child form in a primary form. This is a bit easier by keeping the child form object when you create it in the main form.

The following focuses on the first one, currently there are two common methods, basically the same:

First, define a static member in the main form class to hold the current main form object, for example:

public static yourMainWindow pCurrentWin = null;

Then, in the main form constructor, initialize the static member as follows:

pCurrentWin = this;

Calling the parent form from a child form can manipulate the current primary form with the primary form class name.pCurrentWin.

The second is to define a private member in a child form to hold the current main form object, for example:

private yourMainWindow pParentWin = null;

Then in the subform constructor, add a parameter as follows:

public yourChildWindow( yourMainWindow WinMain ) 
{
  pParentWin = WinMain;
  //Other code
}

When the child form is created on the main form, the child form is constructed with this as a parameter so that calling the parent form from within the child form can be done directly with "this.pParentWin"

However, all this does is give you access to the current main form object, so how to manipulate the control, many people directly modify the member accessors of the control, that is, change "private" to "public", I think this breaks the encapsulation of its own class, so I prefer to add public properties or methods for invocation, such as:

public string ButtonText 
{
  get{ return btn.Text;}
  set{ btn.Text = value;}
} public void Button_Click()
{
  this.btnDConvert.PerformClick();//Execute button click
}

Hopefully this article has helped you with your C# programming.


Related articles: