Thomas Anderson
Thomas Anderson

Reputation: 23

Windows forms - calling the same function from different forms

I have a little problem with windows forms in c#. Let's keep it simple: I have a method which sets the default background color and foreground color. I have multiple forms from which I want to call it and I want have only one method (keep the possibility to add a default background image, etc... ). How should I do it ?

This is the basic code:

public void LoadGraphics() {
  this.BackColor = Graphics.GraphicsSettings.Default.BackgroundColor;
  this.ForeColor = Graphics.GraphicsSettings.Default.ForegroundColor;
  this.BackgroundImage = new Bitmap(Graphics.GraphicsResources.bg_small);
}

Upvotes: 2

Views: 3339

Answers (2)

Nasreddine
Nasreddine

Reputation: 37808

You can create a static class that contains the code to be shared between your forms:

static class Utils
{
    public static void ChangeColor(Form form, Color color)
    {
        form.BackColor = color;
    }
}

Then you can call this function from any other form:

Utils.ChangeColor(this, Color.Red);

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33511

Create a parent class that implements the method and derive your Forms from that parent class:

class Foo : Form {
    void LoadGraphics() {
        this.BackColor = Graphics.GraphicsSettings.Default.BackgroundColor;
        this.ForeColor = Graphics.GraphicsSettings.Default.ForegroundColor;
        this.BackgroundImage = new Bitmap(Graphics.GraphicsResources.bg_small);
    }
}

class YourForm : Foo {
    void someFunction() {
        LoadGraphics();
    }
}

Upvotes: 6

Related Questions