Home > Net >  Online, etc., and ask a simple question: how to access to the parent window controls in the thread f
Online, etc., and ask a simple question: how to access to the parent window controls in the thread f

Time:11-07


Looks like a lot of information on the net, all speak more troublesome, have a little bit more simple ideas and examples?

CodePudding user response:

 
//form1
there are two control//1 textBox1 text control
//2 backgroundWorker1 background control simulation thread
//3 for the controls
Public partial class Form1: Form {

Private void button1_Click (object sender, EventArgs e) {
This. BackgroundWorker1. RunWorkerAsync ();
}

Private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e) {
SetMessage (" aaaa ");
}

Public void SetMessage (string STR) {
Try {
TextBox1. Invoke (new Action (()=& gt; {
TextBox1. Text=STR;
}));

}
Catch {

}
}
}

CodePudding user response:

Use the Invoke, as shown below, richTextBox1 control's parent window, the following functions can be used within the child thread (if branch), can also be used in the parent form code (go else branch)
Void setInfoText (string text)
{
String STR=DateTime. Now. ToString (" MM - dd yyyy - HH: MM: ss ") + "" + text +" \ n ";

If (richTextBox1. InvokeRequired)
{
RichTextBox1. Invoke (new MethodInvoker (delegate
{
RichTextBox1. AppendText (STR);//operation of the parent form controls here
RichTextBox1. HideSelection=false;
}));
}
The else
{
RichTextBox1. AppendText (STR);
RichTextBox1. HideSelection=false;
}
}

CodePudding user response:

Pass the parent form reference to child form is not to go, such as constructors, properties, can be put into a global and static variables, don't have access to everywhere, if set the Owner, but can be by Owner down ah, of course also can go through the Windows API FindWindow, method a lot of,

CodePudding user response:

This. Owner. Invoke (new delegate () {this. Owner.=XXX XXX; });

CodePudding user response:

Entrusted with the Invoke positive solutions

CodePudding user response:

After all the stands threads to use members of the UI thread, should be Invoke the UI thread to execute the entrust,

CodePudding user response:

Main form call child form
 
Public int setint=0;
FormSon set=new FormSon ();
Set. The Owner=this;
Set the ShowDialog ();

Child form access the parent form
 
MainForm f1=(MainForm) Owner;
F1. Setint=1;



CodePudding user response:

Pass the parent form reference to child form is not to go, such as constructors, properties, can be put into a global and static variables, don't have access to everywhere, if set the Owner, but can be by Owner down ah, of course also can go through the Windows API FindWindow, method a lot of,
  •  Tags:  
  • C#