Closing and Opening Forms - c#

What is the best way to close a form and get to another form.
At present I have a Main Form and then two forms:
I want to know how to close one form and open another form efficiently.The two times I did it had a slight different outcome:
The main form in my application is just the introduction which will load some Company Logo and show a progress bar which will then take it to a log-in form, where in I have a log-in button, from where the actual application will open.
I have some questions.In the Main Form I have added this code:
private void Form1_Load(object sender, EventArgs e)
{
int i;
for (i = 0; i <= 100; i++)
{
progressBar.Value = i;
label1.Text = "Please wait while Refresh loads up...";
}
}
private void progressTimer_Tick(object sender, EventArgs e)
{
this.Close();
}
private void MainForm_Deactivate(object sender, EventArgs e)
{
Form form = new FirstForm();
form.ShowDialog(this);
}
1) This works fine, just that the new form that opens up is at the task bar and is not in the center of the screen(as I have set it's property).How do I fix this?
In the First Form I have added this code:
private void loginButton_Click(object sender, EventArgs e)
{
using( ERPQueries eq = new ERPQueries())
{
int? count = eq.CheckEmployee(userTextBox.Text,passwordTextBox.Text);
if (count == 1)
{
//testLabel.Text = "Ok";
this.Close();
Form form = new SecondForm();
form.ShowDialog(this);
}
else
{
testLabel.Text = "Invalid username or password!";
}
}
}
2) Here the next Form pops up in the center of the screen.I want to know how is it different from the first case, as I have used showDialog() in both the cases?
3) Also in the first case my Main Form Disappears, whereas in the second case the First Form is still visible in the background and disappears only after closing the SecondForm.
I'm sure I'm doing a lot of mistakes, my code is flawed.Please help.This is the first time I'm making an application with multiple forms.
Edit:
When I use Show() instead of ShowDialog() I don't see the new form.Am I missing something?
I tried this.Dispose() instead of this.Close().In the first case it works fine.In the second case, it disposes all the forms.

try:
form.Show();
not
form.ShowDialog(this);
which is what makes it modal.

ShowDialog() is blocking call, so if in one Form's deactivate event you call ShowDialog() of another, your parent form will not yet finish it deactivating.
Like a suggesion I can give you create a collection/stack of forms you want to manage and give control over it to a FormManager class, where you implement whatever logic you want and can call either ShowDialog() or Show(). In other words bring out forms Show/Hide management out forms itself.
Regards.

Related

Having problem to close a second windows form without closing the main form

In a c# I have two forms: Windows Form1 & Windows Form2.
When I click on a link label in Form1, the second form is shown. But when I close the second form, my first Windows form closes too.
my main form is:
namespace Windows_Forms_Basics
{
public partial class ShowLocationOnMapForm : Form
{
private string latitude;
private string longitute;
private GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
public ShowLocationOnMapForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watcher = new GeoCoordinateWatcher();
// Catch the StatusChanged event.
watcher.StatusChanged += Watcher_StatusChanged;
// Start the watcher.
watcher.Start();
}
private void button_ShowOnMap_Click(object sender, EventArgs e)
{
textBox_Latitude.Text = latitude;
textBox_Longtitude.Text = longitute;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>")]
private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) // Find GeoLocation of Device
{
try
{
if (e.Status == GeoPositionStatus.Ready)
{
// Display the latitude and longitude.
if (watcher.Position.Location.IsUnknown)
{
latitude = "0";
longitute = "0";
}
else
{
latitude = watcher.Position.Location.Latitude.ToString();
longitute = watcher.Position.Location.Longitude.ToString();
}
}
else
{
latitude = "0";
longitute = "0";
}
}
catch (Exception)
{
latitude = "0";
longitute = "0";
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private HelpForm form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
form2.Show();
}
}
}
and my second form is:
namespace Windows_Forms_Basics
{
public partial class HelpForm : Form
{
public HelpForm()
{
InitializeComponent();
}
private void HelpForm_Load(object sender, EventArgs e)
{
}
private void button_BackToForm1_Click(object sender, EventArgs e)
{
ShowLocationOnMapForm form1 = new ShowLocationOnMapForm();
this.Hide();
form1.Show();
}
}
}
Do you have any idea how to tackle this problem?
I am guessing you may be “confusing” forms and one forms “ability” to access another form. Let’s start by taking a look at the bit of code in your initial question…
private HelpForm form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.Hide();
form2.Show();
}
This code is called from (what appears to be) a Form named ShowLocationOnMapForm.
On this form is a LinkLabel named linkLabel_help and its LinkClicked event is wired up and is shown above.
In addition, there appears to be a “global” variable form2 that is a HelpForm object (first line in the code above), which is another form. It is unnecessary to create this “global” form variable in the ShowLocationOnMapForm. …. However, we will continue as it is not pertinent at this point.
When the user “clicks” the `LinkLabel’ the above method will fire.
On the first Line in the method…
this.Hide();
Is going to “hide” the current form ShowLocationOnMapForm … and “show” the second form (HelpForm) with the line…
form2.Show();
On the surface, this may appear correct, however, there is one problem that I am guessing you are missing. The problem is…
How are you going to “unhide” the first form ShowLocationOnMapForm?
The second form (HelpForm) is “shown”, however, it isn’t going to KNOW anything about the first form. In this situation the first form is basically LOST and you have no way of accessing it. Therefore when you attempt the line… form1.Show(); in the second form, the compiler is going to complain because its not going to know what form1 is. In this code, there is NO way to get back to the first form. It is not only hidden from the user, but from the second form’s perspective the “CODE” can’t see it either!
Your faulty solution is not only “creating” another form1 but it is also doing the same with the second form.
Given this, it appears clear, that if you want to keep access to the first form… then you are going to have to use a ShowDialog instead of Show OR pass the first form to the second form.
Since it is unclear “how” you want these forms to interact, I can only proffer two (2) ways that you can use to at least keep access to the first form.
1) Use ShowDialog instead of Show when displaying the second form. It may look like …
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
HelpForm form2 = new HelpForm();
this.Hide();
form2.ShowDialog();
this.Show();
}
In the code above, the ShowDialog is going to “STOP” code execution in the first form and will wait for the second form (form2) to close. When executed, the first form is hidden, then the second form is shown, however, unlike the Show command, the line this.Show(); will not be executed until the second form closes. I am guessing this may be what you are looking for.
2) Pass the first form to the second form giving the second form “access” to the first form.
This will require that the second form has a “constructor” that takes a ShowLocationOnMapForm object as a parameter. With this, the second form can create a “global” variable of type ShowLocationOnMapForm that “points” to the first form. The constructor may look like…
private ShowLocationOnMapForm parentForm;
public HelpForm(ShowLocationOnMapForm parent) {
InitializeComponent();
parentForm = parent;
}
In the first form, you would instantiate the second form with...
HelpForm form2 = new HelpForm(this);
With this approach, the second form will have total access to the first form. You could add the “back” button as you describe and simply execute the line…ParentForm.Show(); However, I recommend you also wire up the second forms FormClose event and show the first form, otherwise, if the user clicks the close button (top right) and doesn’t click the “back” button, then you will have LOST the first form again.
Without knowing “exactly” how you want these forms to interact it is difficult to proffer a complete solution.
There are also other ways to accomplish this, however these should work for most cases.
I hope this makes sense and helps.
I tried to solve this problem by placing a 'Back to Form1' button in Form2. Which works, and the solution is as follows:
on my Form1 I have:
private Form2 form2 = new HelpForm();
private void linkLabel_help_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
form2.Show();
}
and on my second form I have:
private void button_BackToForm1_Click(object sender, EventArgs e)
{
HelpForm form1 = new HelpForm();
this.Hide();
form1.Show();
}
But the problem is if I click the close button (on top right of the window) instead of the GoBack button on the second form, Form1 & Form2 both close in the same time.

Creating new pages in Visual Studio using C# Windows Forms

I am trying to write a Windows Forms application using C#, however I have never done this before. I have successfully created a login page which takes the user to a home page where 4 buttons are displayed. I am trying to find code to put inside each button that will take the user to a different page.
In windows forms application, you have to call Show method on the Form which you want to show.
Let's say on Button1 click you want to show Form2, then below code will bring Form 2 up on the screen.
private void button1_Click_1(object sender, EventArgs e)
{
Form2 obj = new Form2();
if (obj == null)
{
obj.Parent = this;
}
obj.Show();
this.Hide();
}
You need to create, initialize and show the other forms.
frmSecond frm = new frmSecond();//You should call any other constructor, may be with some parameters
frm.Text ="I wanted to change the title";//Optional: You can change any property value if you need
frm.Show();
If you want to show the form, collect some information from user and return some values then you can use ShowDialog method instead of Show method
if(frm.ShowDialog(this) == DialogResult.OK){
var myVar = frm.ReturnObject;
...
}
You can use below approach for one parent window and new child window.
When you press the button new form opens:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
{
frm2.ShowDialog();
}
}

how to open a form from another form in c#

i am writing a code for serial key registration.
if the serial key entered by the user is correct then anothr form must open and the present form must close.
please go thought the code.
namespace ExtTrigger
{
public partial class Activation : Form
{
public Activation()
{
InitializeComponent();
}
private void ActivateButton_Click(object sender, EventArgs e)
{
String key;
key = string.Concat(textBox1.Text,textBox2.Text,textBox3.Text,textBox4.Text);
if (key == "1234123412341234")
{
Properties.Settings.Default.Registered = true;
MessageBox.Show("hurray", "", MessageBoxButtons.OK);
Form1 f1= new Form1();
f1.ShowDialog();
this.Close();
}
else
MessageBox.Show("No Match", "", MessageBoxButtons.OK);
}
private void Activation_Load(object sender, EventArgs e)
{
}
}
my problem is: On clicking on ActivateBotton, Form1 opens but the present form doesnot close.
i have read in few threads that in VB we can change the property: ShutdownMode.
How can we do that in c#?
f1.ShowDialog(); blocks the call, it doesn't go to the next line until that new form has been closed.
An option would be to use:
f1.Show();
Show doesn't block the call, it passes to the next statement. It will not wait for the new form to be closed.
since you have show the second form as f1.ShowDialog() so first one remain open untile second one close, try this
Form1 f1= new Form1();
f1.Show();
this.Close();
The following code should do the trick:
using(Form1 f1 = new Form1())
{
this.Hide();
DialogResult result = f1.ShowDialog();
if(result == DialogResult.OK)
{
this.Show();
}
}
You create your new form within the using-block, then you hide your main form(or the form you are in at the moment) create a DialogResult that gets set by the newly opened form and open this form. Now you can set the results you want to check for inside of your new form and if everything went well inside of you new form you set the DialogResult to OK via:
this.DialogResult = DialogResult.OK;
Now back in our first form you check for the DialogResult and if it is okay you show your main form again. If it was not okay you could just reopen the 2nd form and let the user try again.
Opening a new form is very simple, but the way you do it really depends on your need.
Case 1: I would like to freeze/ block the calling form on secondary form call
In this case you should be using secondaryFormObj.ShowDialog();
Of course, when using this technique your called form, which now acts as a dialog, should "return" an answer to its caller parent on closure.
For example:
private void SecondaryForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Just a dummy code example.
// Always returns Yes result on form closure
this.DialogResult = System.Windows.Forms.DialogResult.Yes;
}
For more help and examples on this manner you can use MSDN:
DialogResult - MSDN
Case 2: I would like to have both forms responding at the same time
In this case you basically need to call secondaryFormObj.Show();
If you want the caller form to be hidden on secondary form call, just
invoke this.Hide();
after the call to secondaryFormObj.Show(); in the caller class.
You can also close the caller form using this.Close(); as long as the caller form is not the application's main form.
... And remember
Always make sure you initialized the secondary form object before
invoking it with either secondaryFormObj.Show(); or
secondaryFormObj.ShowDialog();
Initializing a form is done the same way like every typical object using the
new operator.
For example: secondaryFormObj = new Form();
Hopes this helps. Happy coding!

How I open a form at a time under MDI parent form?

I have a MDI form. Within this MDI there is multiple button to open new forms. Let buttons are btn1, btn2, btn3, btn4.... When I press btn1, form1 is load. when I press btn2, form2 is load... Now I press btn1, And form1 is loaded. If I press again btn1 then another form1 is open. Simultaneously let form1 is open, if I press btn2 form2 is open. But I want to open a form at a time. How I prevent this?
all the answers you got are good so i'm not going to repeat them, just give you an example of the member and method you can use to prevent that from happening:
private Form frm;
private void button1_Clicked(object sender, EventArgs e)
{
if (frm != null)
{
frm.Close();
frm.Dispose();
}
frm = new Form1();
frm.Show();
}
private void button2_Clicked(object sender, EventArgs e)
{
if (frm != null)
{
frm.Close();
frm.Dispose();
}
frm = new Form2();
frm.Show();
}
You can read up about mutual exclusion http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx
It is a general solution to make sure you only have 1 thing (thread, process, form, whatever) of something at the same time. You can even use it inter application.
An example is shown here: http://www.dotnetperls.com/mutex
You can create multiple mutexes, one for each form. Or one for a set of forms, in what ever combination suits you.
Example Scenario:
Form1 creates a mutex with name X
Form2 is being loaded checks whether mutex X is created, if so it closes itself.
Of course you will need to make sure the mutex is Disposed / released when the creator (Form1 in this example) closes, to allow other forms to show.
You can use some flag for this purpose OK, like this:
bool formOpened;
private void buttons_Click(object sender, EventArgs e){
if(!formOpened){
//Show your form
//..............
formOpened = true;
}
}
//This is the FormClosed event handler used for all your child forms
private void formsClosed(object sender, FormClosedEventArgs e){
formOpened = false;
}
At least this is a simple solution which works.
In general case, you need a int variable to count the opened forms, like this:
int openedForms = 0;
//suppose we allow maximum 3 forms opened at a time.
private void buttons_Click(object sender, EventArgs e){
if(openedForms < 3){
//Show your form
//..............
openedForms++;
}
}
private void formsClosed(object sender, FormClosedEventArgs e){
openedForms--;
}
Does this mean while you have Form1 open, you want to still be able to open a Form2 and 3 and etc?
It you don't want that, you can use the form1Instance.SHowDialog() instead of Show()...
But that generally means you can't access the parent form while form1 is open...
But King King's anwser might be more useable to you.

opening a window form from another form programmatically

I am making a Windows Forms application. I have a form. I want to open a new form at run time from the original form on a button click. And then close this new form (after 2,3 sec) programatically but from a thread other than gui main thread.
Can anybody guide me how to do it ?
Will the new form affect or hinder the things going on in the original main form ? (if yes than how to stop it ?)
To open from with button click please add the following code in the button event handler
var m = new Form1();
m.Show();
Here Form1 is the name of the form which you want to open.
Also to close the current form, you may use
this.close();
I would do it like this:
var form2 = new Form2();
form2.Show();
and to close current form I would use
this.Hide(); instead of
this.close();
check out this Youtube channel link for easy start-up tutorials you might find it helpful if u are a beginner
This is an old question, but answering for gathering knowledge.
We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close() will free the memory and we can never interact with that form again
form.hide() will just hide the form, where the code part can still run
For more details about timer refer this link, https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
You just need to use Dispatcher to perform graphical operation from a thread other then UI thread. I don't think that this will affect behavior of the main form. This may help you :
Accessing UI Control from BackgroundWorker Thread
This might also help:
void ButtQuitClick(object sender, EventArgs e)
{
QuitWin form = new QuitWin();
form.Show();
}
Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.
When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.
private void btnchangerate_Click(object sender, EventArgs e)
{
this.Hide(); //current form will hide
Form1 fm = new Form1(); //another form will open
fm.Show();
}
on click btn current form will hide and new form will open

Categories

Resources