SoFunction
Updated on 2025-03-07

Example of control interoperability between parent window and child window in C#

This article describes the method of interoperating controls between parent windows and child windows in C#. Share it for your reference. The specific analysis is as follows:

Many people are troubled by how to operate controls on the main form in a child form, or controls on the subform in a main form. In comparison, the latter is a little simpler. Just keep the created child form object when creating a child form.

The following is a focus on the former. There are two common methods at present, which are basically the same:

The first is to define a static member in the main form class to save the current main form object, for example:

Copy the codeThe code is as follows:
public static yourMainWindow pCurrentWin = null;

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

Copy the codeThe code is as follows:
pCurrentWin = this;

Then, when calling the parent form in the child form, you can use "main form class name. pCurrentWin" to operate the current main form.

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

Copy the codeThe code is as follows:
private yourMainWindow pParentWin = null;

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

Copy the codeThe code is as follows:
public yourChildWindow( yourMainWindow WinMain )
{
  pParentWin = WinMain;
  //Other code
}

When creating a child form in the main form, use this as a parameter to construct the child form. In this way, call the parent form in the child form, you can use "" directly

However, what is done above is just to allow you to access the current main form object. So how to operate the control? Many people directly modify the control member access character, that is, change "private" to "public". I think this breaks the encapsulation of the class, so my favorite method is to add public attributes or methods for call, for example:

Copy the codeThe code is as follows:
public string ButtonText
{
  get{ return ;}
  set{ = value;}
}

public void Button_Click()
{
  ();//Execute button click
}

I hope this article will be helpful to everyone's C# programming.