Winforms: bring 2 obscured forms to front - c#

I'm trying to solve this problem for a long time.
I have 2 forms, my objectives are:
When user minimize form2, form1 must minimize too.
When user maximize form2, form1 must maximize too.
When both forms are obscured by another window, and user clicks in the form2 icon in taskbar, form1 must also come to front.
The first 2 things I solved with the a_Resize method. But I can't do the third one. I tried with activate event but when I do that the form2 keeps blocked.
Here is my code:
public partial class Form1 : Form
{
Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2();
form2.Show();
form2.Resize += new EventHandler(a_Resize);
}
void a_Resize(object sender, EventArgs e)
{
if (((Form)sender).WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Minimized;
}
else
{
this.WindowState = FormWindowState.Normal;
}
}
}
If I add a handler to the form2 activate event:
form2.Activated += new EventHandler(form2_Activated);
And call for instance the Focus method (I tried other methods too), the form2 keeps blocked behind form1.
void form2_Activated(object sender, EventArgs e)
{
this.Focus();
}
Someone have any ideas how I can do that?

When you create form2, just pass this as a parameter to Show() to signify that form1 is the owner. With an owner link, the forms will always be raised together (at least in my experience -- I don't have a specification to back me up on this).
public Form1()
{
InitializeComponent();
form2 = new Form2();
form2.Show(this); //pass 'this' as argument to Show() to link them
form2.Resize += new EventHandler(a_Resize);
}

Related

Switching between forms and sending variable correctly

I am wondering how can I correctly switch between forms by button click event.
I have Form1 and Form2.
Form1 have: -TextBoxForm1
-ButtonForm1
Form2 have: -TextBoxForm2
-ButtonForm2
I would like to on_click ButtonForm1 event go to the Form2. Then I want to write some message to TextBoxForm2 and press ButtonForm2 it will go to the Form1 again and message from TextBoxForm2 will appear in TextBoxForm1.
Everything works fine, but I have one problem. When I close application and I wanna debug and start it again, some errors appear like:"application is already running".
Form1:
public static string MSG;
public Form1()
{
InitializeComponent();
TextBoxForm1.Text = MSG;
}
private void ButtonForm1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
//There is probably my fault but when I was trying this.Close(); everything shutted down
form2.Show();
}
Form2:
private void ButtonForm2_Click(object sender, EventArgs e)
{
Form1.MSG = TextBoxForm2.Text;
Form1 form= new Form1();
form.Show();
this.Close();
}
How can I do this correctly please? :) I am beginner, thank you!
I would not go the route of using a STATIC for passing between forms as you mention you are a beginner, but lets get the closing to work for you.
In your main form create a new method to handle an event call as Hans mentioned in the comment. Then, once you create your second form, attach to its closing event to force form 1 to just become visible again.
// Inside your Form1's class..
void ReShowThisForm( object sender, CancelEventArgs e)
{
// since this will be done AFTER the 2nd form's click event, we can pull it
// into your form1's still active textbox control without recreating the form
TextBoxForm1.Text = MSG;
this.Show();
}
and where you are creating form2
private void ButtonForm1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Closing += ReShowThisForm;
this.Hide();
form2.Show();
}
and in your second form click, you should only need to set the static field and close the form
private void ButtonForm2_Click(object sender, EventArgs e)
{
Form1.MSG = TextBoxForm2.Text;
this.Close();
}
Easy solution is to use modal form. Display Form2 temporarily, when it is displayed Form1 is invisible.
var form2 = new Form2();
this.Visible = false; // or Hide();
form2.ShowDialog(this);
this.Visible = true;
And to pass data you can define property in Form2, to example:
public string SomeData {get; set;}
Form1 has to set SomeData, which you take in Shown and display. Same property can be used to get data from Form2 (before closing).
// form 1 click
var form2 = new Form2() { SomeData = TextBoxForm1.Text; }
this.Visible = false;
form2.ShowDialog(this);
this.Visible = true;
TextBoxForm1.Text = form2.SomeData;
// form 2 shown
TextBoxForm2.Text = SomeData;
// form 2 click
SomeData = TextBoxForm2.Text;
Close();

Closing Multiple Forms in C#

I have total 3 forms (Form1, Form2 and Form3) in my Windows Forms Application.
Form2 is log-in page. When user clicks on sign-in button in Form1, Form2 must be open and if user provides accurate username and password then Form3 is needed to open and to close both Form1 and Form2.
How to code such thing in C#? I am using Microsoft Visual Studio 2012.
So far I have done following procedure:
double click the Form1 to get at the coding window and wrote-
Form2 secondForm = new Form2();
Just outside of the Form Load event
& inside the button, i wrote-
secondForm.Show();
So when I run the solution, Form2 is opened by clicking a button in Form1 (Works Perfectly!). But I have no idea how to close Form1 and Form2 when user enter correct username and password combination in Form2 to open Form3.
Form1 firstForm = new Form1();
firstForm.Close();
isn't closing the form.
Please guide me.
You should add a new Class with a Main() method. (OR) There will be Program.cs in your project.
And, start the application from the Main() method. You can change "Startup object:" property of your project to "<YourApplicationName>.Program".
You Main() method should show Form1 and Form2 as Dialog.
If DialogResult is OK then run the Form3 by Application.Run() method.
DialogResult r;
r = (new Form1().ShowDialog());
if( r == DialogResult.OK )
Application.Run(new Form3());
You cannot close the main form (the one that you used to start the message loop) if you do that will end/close the entire application. What you can do however instead is this:
Form1 code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var f2 = new Form2();
var res = f2.ShowDialog();
if (res == DialogResult.OK)
{
var f3 = new Form3();
this.Visible = false;
f3.ShowDialog();
this.Close();
}
}
}
Form2 code:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
// if username and password is ok set the dialog result to ok
this.DialogResult = DialogResult.OK;
this.Close();
}
}

show a form at its current state instead of new form()

I have created a C# application.
Here I have two forms, form1 and form2.
form2 is called from form1.
Later form2 is made hidden.
Now I want to show form2 from form1.
Please give me some idea.
You need to keep reference to Form2 object, and when you want it to be visible, just call frm2.Show() - don't construct the new Form2 object with new Form2() - use the existing one.
// You need to contruct Form2 before calling Show().
Form2 frm2 = new Form2();
// Some handler somewhere
void btnShowForm2_Click(..., ...)
{
frm2.Show();
}
Edit: As Micah pointed out, you will want to hide Form2 instead of closing it:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true; // this cancels the close event.
}
You will want to use form.hide() when hiding form2 instead of form.close
keep a reference to form2 and call form.show when you want to show it again
take form2 instance variable at class level
example
Public Class Form1
{
Form frm2;
//Show form here
protected void Button1_Clik
{
frm2=new Form2();
frm2.Show();
}
//Even the form is hidden, you may show the same instance /same state of form again
protected void Button2_Click()
{
frm2.Show();
}
}

Bring form2 to front from a deactivated form1

I have a form1 that opens form2 as a "fake popup"
this.enabled = false;
MyForm2 myform2 = new MyForm2();
myform2.Show();
myform2.BringToFront();
When i dispose form2 i enable form1 back.
Now if the user minimizes both forms, and then clicks on form1, form1 will pop in his disenabled state.
I need to pop form2 insted.
So I created a static class to hold my last active form. On load of form2(or any other form) i save my last active form.
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
MyStaticClass.lastForm = this;
}
In form1(and other similar forms) i use:
protected override void OnGotFocus(System.EventArgs e)
{
base.OnGotFocus(e);
if (!this.Enabled && MyStaticClass.lastForm!= null && MyStaticClass.lastForm != this)
{
MyStaticClass.lastForm.Show();
MyStaticClass.lastForm.BringToFront();
MyStaticClass.lastForm.Activate();
}
}
OnGotFocus gets executed and my show/activate etc does too, but form2 never pops up. What am I doing wrong?
Thank you,
gg
You are "showing" and "activating" your form, the problem is it's still minimized. Change the WindowState to Normal.
MyStaticClass.lastForm.WindowState = FormWindowState.Normal;
I think it would be confusing to the user to click on one window's taskbar button and get another.
Instead of going through this rigamarole, try calling ShowDialog() instead of Show() in form1; this will block all access to Form1 until Form2 closes. ShowDialog also has an overload that accepts a "parent" or "owner" form; if this overload is used (just pass this), the dialog will always show in front of Form1.

C#, how to hide one form and show another?

When my project starts Form1 loads and checks the program license with the server, if everything's OK it should: show Form2 and close Form1. Afterward when the user would close Form2 with the "x", the program should end.
What do you think would be the best way of doing it?
So far got only to form2.Show :)
...
if (responseFromServer == "OK")
{
Form2 form2 = new Form2();
form2.Show();
}
Thanks!
I use something like this. Code is in Program.cs
public static bool IsLogged = false;
Application.Run(new FUserLogin());
if (!isLogged)
Application.Exit();
else
Application.Run(new FMain());
As you probably know if you use Form1 as your main form then you can't close it as this will close the application (unless you customize the way the app starts, but that's more advanced).
One option is to start by creating Form2 as your main form, but keep it hidden, then create and show Form1, and then when the license check is finished, close Form1 and make Form2 visible.
Or you can start by showing Form1 and then when the license check is done, call Form1.Hide() and then create and show Form2. Then when Form2 is closed by the user, call Form1.Close() in the Form2.Closed event handler:
class Form1
{
private void Form1_Load(object sender, EventArgs e)
{
// do the license check,
// and then when the license check is done:
if (responseFromServer == "OK")
{
Form2 form2 = new Form2();
Form2.FormClosed += new FormClosedEventHandler(Form2_FormClosed);
Form2.Show();
this.Hide();
}
else
this.Close();
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close(); // will exit the application
}
}
You can show the first form using ShowDialog, which will block until the form closes. Inside Form1 you can just call this.Close() when it is done processing, and either set the DialogResult property, or (probably cleaner) you can create a public property that Form1 sets before it closes, and have the caller check that. Then you can either return from Main directly, or go ahead and instantiate your new class and pass it to Application.Run().
static class Program
{
[STAThread]
static void Main()
{
var form1 = new Form1();
var result = from1.ShowDialog(); // Form1 can set DialogResult, or another property to indicate success
if (result != DialogResult.OK) return; // either this
if (!form1.ValidationSuccessful) return; // or this
Application.Run(new Form2());
}
}
I like this because you are not referencing Form2 from Form1, all of the code to deal with showing Form1 and exiting the application is consolidated in one place, and can easily be commented out for development or testing.
Try this to hide Form1:
this.Hide();
then in your FormClosing event of Form2:
Form2_FormClosing(object sender, EventArgs e)
{
Application.Exit();
}
Try this
//Form1 code
if (responseFromServer == "OK")
{
this.Hide();
Form2 frm = new Form2();
frm.Show();
}
And you can exit from the application using Application.Exit() method in the Form2's form closing event
//Login Form Load Events or Constructor
this.Close(); //first Close Login From
Application.Run(new Main());//second Run Main Form

Categories