Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a windows forms application with some controls added to the designer. When I want to change something (LIKE) enabling a text box from inside the Form1.cs, I simply use:

textBox1.Enabled = true;

but now I have a separated class called class1.cs.

How could I enable textBox1 from a static function class1.cs?

NOTE: I did not try any code because I am totally clueless about doing this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

EDIT: Lot of edit.

public partial class Form1 : Form
{
    // Static form. Null if no form created yet.
    private static Form1 form = null;

    private delegate void EnableDelegate(bool enable);

    public Form1()
    {
        InitializeComponent();
        form = this;
    }

    // Static method, call the non-static version if the form exist.
    public static void EnableStaticTextBox(bool enable)
    {
        if (form != null)
            form.EnableTextBox(enable);
    }

    private void EnableTextBox(bool enable)
    {
        // If this returns true, it means it was called from an external thread.
        if (InvokeRequired)
        {
            // Create a delegate of this method and let the form run it.
            this.Invoke(new EnableDelegate(EnableTextBox), new object[] { enable });
            return; // Important
        }

        // Set textBox
        textBox1.Enabled = enable;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...