Jump to content
  • Advertisement
Sign in to follow this  

[.net] (C#) altering/accessing controls in Window forms from other forms/classes

This topic is 3855 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Greetings! I'm writing a basic game in C# as an bonus task in a course I'm attending in but since I'm totally new in C# Windows (Forms) programming I've run into a irritating problem. Application consists of a "game" class and Program.cs The game class contains (of course >_<) needed Game data and Program.cs the applikation with all buttons etc but I dont know how to access the controls in the main form from the game class. lets say I have a label named lblTheWord in frmMainForm (the main window) and I want to modify it from the game class in a function call GenerateNewWord() .. how do I do it? Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
Just pass in a reference to the form to the Game class..

class Game
{
MainForm mainForm = null;

public Game(MainForm form)
{
mainForm = form;
}

public DoSomething()
{
mainForm.lblTheWord.Text = "Test";
}
}


Or not so nice is to make a class with a static reference to the form.

class Global
{
public static MainForm MainForm = null;
}



Then when you instanciate the form in Program.cs you get a reference to the form.

static class Program
{
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

using (Global.MainForm = new MainForm())
Application.Run(Global.MainForm);
}
}




Then from everywhere you game use Global.MainForm.lblTheWord.Text = "Test";

People would say the first method is the best since it follows the rule of encapsulation for OOP. But personally I often use the second method.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!