Programming - C# .NET delegates and interacting with forms on seperate threads


O.K, so you have 2 forms instantiated in a Windows Form Application, and you want to control the contents of 1 form from another, but this is impossible because GUIs run on seperate threads, and thread instances are not thread safe. So here is a new design mattern to help you control 1 form instance from within another form.

//define the delegate

public delegate showwindow();

//the accessible method we want to control

public
voidshowthiswindow()
{
this
.TopMost = true;
this
.Focus();
this
.BringToFront();
this
.TopMost = false;
//this.Show();
}

//this is the facade, it hides the fact you are being handled by a BeginInvoke handle

public
voidreShowWindow()
{
if
(this.InvokeRequired)
{
// Execute the same method, but this time on the GUI thread
this
.BeginInvoke(newshowwindow(showthiswindow));
// we return immedeately
return
;
}
showthiswindow();
}
and
So there you go folks, control GUI elements from seperate forms isn't as hard as you thought. Is it?

Home | Privacy Policy | Site Map | Links | Company | Contact Us | Arena           

We provide cutting edge software development, consultancy and web design services            

There are currently 551 user(s) with 33940 hits.