Reputation: 565
From Form1 I've been opening Form2. If I then click on a button or whatever in Form1, I want Form2 to be activated. Something like
Form2.Activate();
But that just gives me errors.
This is my code right now:
private void button1_Click(object sender, EventArgs e) // first I click here
{
Form2 f2 = new Form2();
f2.Show();
}
private void button2_Click(object sender, EventArgs e) // then here, to activate it
{
Form2 f2 = new Form2();
f2.Activate();
}
Upvotes: 0
Views: 12684
Reputation: 39152
Move the Form2 reference out to Class level so it can be accessed from both button1 and button2.
Something like...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 f2 = null;
private void button1_Click(object sender, EventArgs e) // first I click here
{
if (f2 == null || f2.IsDisposed)
{
f2 = new Form2();
f2.Show();
}
else
{
ActivateForm2();
}
}
private void button2_Click(object sender, EventArgs e) // then here, to activate it
{
ActivateForm2();
}
private void ActivateForm2()
{
if (f2 != null && !f2.IsDisposed)
{
if (f2.WindowState == FormWindowState.Minimized)
{
f2.WindowState = FormWindowState.Normal;
}
f2.Activate();
}
}
}
Upvotes: 2
Reputation: 8309
You're having that error because Activate method should be called from an instance of the Form2 class not the Form2 class its self, Activate() is not a Static method, You have to instantiate the Form2 class first, this event handler is for a button click on the first Form
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
this was to show the form, to activate it and make it the main one showed to you, you can than call the Activate() method to that instance, like
form2.Show();
form2.Activate();
Upvotes: 3
Reputation: 9800
I believe you need to create an instance of a class in order to access instance methods. Basically, the instance is created via a constructor call, like this:
Form2 form = new Form2();
However, the method to show newly created form is this one:
form2.Show();
Upvotes: 2