Prevent form from showing multiple times - c#

In windows form (c#), i am showing a form when user click on button, it is working fine form is visible to user, but if user click again on the same button the same form is opening again two forms are displaying. Is there any way to prevent this, please give me any reference for this thank you. This is my code....
private void button1_Click(object sender, EventArgs e)
{
Form2 obj = new Form2();
obj.Show();
}

You are most likely doing something like this:
void button1_OnClick(object sender, EventArgs e) {
var newForm = new MyForm();
newForm.Show();
}
So you are showing a new instance of the form every time it is clicked. You want to do something like this:
MyForm _form = new MyForm();
void button1_OnClick(object sender, EventArgs e) {
_form.Show();
}
Here you have just one instance of the form you wish to show, and just Show() it.

foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(MyFormType))
{
form.Activate();
return;
}
}
Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();
i tried more than a ways to compare which one is better.
but i think this solution must be better than the answer.

You can try something like
private Form f;
private void button2_Click(object sender, EventArgs e)
{
if (f == null)
{
f = new Form();
f.Closed += f_Closed;
f.Show();
}
}
void f_Closed(object sender, EventArgs e)
{
f = null;
}

You are most probably creating a new instance of the form every time in the Click handler of the Button.
So you ill need to move the Form object creation outside the Button_Click.

Here's a good example of a proven solution
This will open the form if it is not already open.
If it is already open, it will place it in the foreground.
namespace MainProgram
{
public partial class Form1 : Form
{
private Form formNew = new FormToShowSomething();
private void button1_Click(object sender, EventArgs e)
{
formNew.Show();
formNew.Activate();
}
}
}

the easiest solution to your problem is replacing the Show command with ShowDialog, that way you won't any problem when it comes to preventing a form to show up twice
Form2 obj = new Form2();
obj.ShowDialog();
the code: .ShowDialog(); is what we are currently looking for that will solve the issue

10 years after , like the band :p
Thought to share the code that works for me. Nothing fancy, just checking if the form instance exists. Also, I don't prefer the ShowDialog, because the user is 'trapped' in that form and I find it annoying. The user might want to check other info from another source, for example when filling an online form and needs to copy paste a field info.
private void button1_Click(object sender, EventArgs e)
{
var obj = Application.OpenForms.OfType<Form2>().Select(t => t).FirstOrDefault();
if (obj != null)
{
obj.BringToFront();
}
else
{
obj = new Form2();
obj.Show();
}
}

Related

Maximizing the main form when you close one

I have this project for school which requires me to use 2 forms, but I can't have both of them open at the same time.
This means when I open one form, the other one minimizes. When you close this one, I'd like to make it so that the minimized one is restored.
This is what I have now for minimizing it:
private void Mkbtn1_Click(object sender, EventArgs e)
{
var newForm = new form1();
newForm.Show();
this.WindowState = FormWindowState.Minimized;
}
In form1, which is opening the form2 do things like this
`private void button1_Click(object sender, EventArgs e)
{
Form2 newofrm = new Form2();
newofrm.parentForm = this;
newofrm.Show();
this.Hide();
}`
And then in form2 use this
`private void Form2_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized && parentForm != null)
{
// Do some stuff
parentForm.Show();
}
}`
Here parentForm is public member of form2 of type Form, also if you want this do be done when form is closed then add form closing event and add same code in the event handler

C# Windows Forms application showing background when opening new form

I am currently making a full-screen application in C# but I have a bit of a problem. I have a overview form which shows buttons. When you click a button it will open a new form. (Overview form and new form are both full-screen). The problem is when the new form opens it will show nothing for a second (It doesnt really look to good in a full screen application). So does anyone know how to fix this? You can find the code here:
Code for opening new form:
void NewForm(Form form)
{
form.FormClosing += new FormClosingEventHandler(form_Closed);
form.Show();
Hide();
}
void form_Closed(Object sender, EventArgs e)
{
Show();
}
One of the opened forms:
public AdminPanelForm()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
}
private void AdminPanelForm_Shown(object sender, EventArgs e)
{
List<User> users = User.GetAllUsers();
foreach(User user in users)
{
ListViewItem lvi = new ListViewItem(user.UserName);
lvi.SubItems.Add(user.Role);
listUsers.Items.Add(lvi);
}
}
private void btnBack_Click(object sender, EventArgs e)
{
Close();
}
Thanks in Advance!
After form.Show() add form.Update(). Otherwise, the real form redraw will be done with delay. It may be better to call Hide first.

How to close one FORM from another FORM in C# Winform Application

I'm working on C# winform application, in that I want to close one form from the another form i.e. I have 2 forms Form1 and Form2 and I want to close Form2 from Form1 for that I have written following code on button click event of Form1, but I'm getting the following exception-
"Object reference not set to an instance of an object."
private void button_click(object sender, eventArgs e)
{
Form2.ActiveForm.Disposed+= new EventHandler(closeForm2) // Getting Exception to ***closeForm2***
}
private void closeForm2(object sender, eventArgs e)
{
Form2.ActiveForm.Dispose();
}
For future readers!
You can use the following code to close one FORM from another FORM in C# Winform Application.
FrmToBeClosed obj = (FrmToBeClosed)Application.OpenForms["FrmToBeClosed"];
obj.Close();
Those 2 lines of code are self-explanatory!
That's it!
ActiveForm returns "Currently active form from this application" = Form you clicked...
How you start your Form2?
I think you should define it like
Form2 DetailsForm = null;
public void prepareForm2() //bind this to action to open new form
{
if (DetailsForm == null)
{
DetailsForm = new Form2(this);
}
}
Than you can just call close()/Dispose/Hide
by calling
private void closeForm2(object sender, eventArgs e)
{
DetailsForm.Close();
// or DetailsForm.Hide();
// or DetailsForm.Dispose();
}
See MSDN -> Form.ActiveForm Property
If your application is a multiple-document interface (MDI) application, use the ActiveMdiChild property to obtain the currently active MDI child form.
I think you need a void in your MDI-Form like
public void closeChild(Type FormType)
{
foreach(Form form in this.MdiChildren)
{
if(typeof(form) == FormType)
{
/* what ever you wanna do */
}
}
}
Hope I could help :)
CloseProgramForm closepf = new CloseProgramForm();
closepf.ShowDialog();
if (closeoption == 1)
e.Cancel = false;
else
e.Cancel = true;

C# Windows Forms switching

I got Form1, which creates another form when some button is clicked:
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f5 = new Form5();
f5.Show();
}
When it happens, i need to determine if this form f5 exists,so if it exists,when button is pressed,it simply switches to existing form instead of making new one.If it doesn't exist,then it has to create new form.
How do i do this,if i can't check whether some objects exist or not until i declare them?
How to check f5 existence before i declare it,so i can create it only when there is no such form and it is needed?
The correct way of doing this is to maintain a reference to the Form5 object when you create it. You can do this by, for example, declaring a class-level variable.
public class MyForm : Form
{
private Form5 m_frm5 = null;
// ...other code...
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_frm5 == null)
{
m_frm5 = new Form5();
}
m_frm5.Show();
}
}
Obviously you need to choose a scope appropriately, depending on where you need to access the form object. A static local variable might work equally as well, or you might need to make it global for the entire application.
Alternatively, you can iterate through the Application.OpenForms collection, checking to see if an instance of Form5 has already been created.
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form f in Application.OpenForms)
{
if (f.GetType() == typeof(Form5))
{
f.Show();
return;
}
}
Form5 frm5 = new Form5();
frm5.Show();
}
Pro tip: Choose more descriptive names for your form class than the defaults. Form5 tells me nothing.
Create Form5 as a private variable. Before you create a new one, check to see if it exists before creating a new one.
private Form5 form5 = null;
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
if(f5 == null || !f5.Visible)
f5 = new Form5();
f5.Show();
}
I'd simply make the instance part of the parent code:
Form f5 = null;
private void ToolStripMenuItem_Click(object sender, EventArgs e) {
if (f5 == null) {
f5 = new Form5();
f5.Show();
}
}
Later edit: You are right, you have captured the correct code sequence :). Mine will open it only once.
And I'd rather use ShowDialog() if your application is not MDI

How to close form

Ok, so a Windows Forms class, WindowSettings, and the form has a "Cancel"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the user if he is sure he wants to perform the action. The dialog has 2 buttons, a "Yes"-button and a "No"-button. If the user clicks the "Yes"-button, I want both DialogSettingsCancel and WindowSettings to be closed.
My button_Click event handler in DialogSettingsCancel:
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
WindowSettings settings = new WindowSettings();
this.Close();
settings.Close();
}
When I run my application, and go to the settings form, and click the "Cancel"-button, and then click the "Yes"-button, only DialogSettingsCancel closes without closing WindowSettings.
Why won't it work?
I've also tried changing
this.Close();
settings.Close();
to
settings.Close();
this.Close();
But still the same result.
You need the actual instance of the WindowSettings that's open, not a new one.
Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.
Something like this:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
You can also close the application:
Application.Exit();
It will end the processes.
new WindowSettings();
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
Why not use the DialogResult method to close the form?
if(DialogSettingsCancel.ShowDialog() == DialogResult.Yes)
{
//this will close the form but will keep application open if your
//application type is "console" in the properties of the project
this.Close();
}
For this to work however you will need to do it inside your "WindowSettings" form while you call the DialogSettingsCancel form. Much the same way you would call the OpenFileDialog, or any other Dialog form.
Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:
private void button1_Click(object sender, EventArgs e)
{
Settings newSettingsWindow = new Settings();
if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
{
newSettingsWindow.Close();
}
}
send the WindowSettings as the parameter of the constructor of the DialogSettingsCancel and then on the button1_Click when yes is pressed call the close method of both of them.
public class DialogSettingsCancel
{
WindowSettings parent;
public DialogSettingsCancel(WindowSettings settings)
{
this.parent = settings;
}
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
this.parent.Close();
this.Close();
}
}
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();
2.We can also hide form without closing it
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
int flag = 0;
string u, p;
u = textBox1.Text;
p = textBox2.Text;
if(u=="username" && p=="pasword")
{
flag = 1;
}
else
{
MessageBox.Show("enter correct details");
}
if(flag==1)
{
f2.Show();
this.Hide();
}
}
There are different methods to open or close winform.
Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed.
Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Form.Hide()
Application.Exit()
Some methods to Open/Start a form
Form.Show()
Form.ShowDialog()
Form.TopMost()
All of them act differently , Explore them !

Categories