Within my application i am trying to use forms in tabpages. These forms are all data managing forms.
I edited the tabcontrol (created a custom tabcontrol) so i can remove tabpages by double clicking on the tabheader.
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
//* Default method of closing a tab.
if (Selectedtab != null)
TabPages.Remove(Selectedtab);
}
Although it works. Its actually not doing what I need.
Because any changes on the form in the tabpage, are lost, regardless of the below
public partial class SomeForm : Form
{
private void SomeForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (HasChanges() && CustomMessage.WarningBox("There is unsaved data. Are you sure you want to close"))
return;
((TabControl)((TabPage)this.Parent).Parent).TabPages.Remove((TabPage)this.Parent);
}
}
When setting a breakpoint at this function, it never enters.
Now my question: Is it possible to call the Close method of the form from Tabcontrol. Preferably something like below.
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
if (Selectedtab != null)
{
if (Selectedtab.EmbeddedForm != null)
TabPages.ASelectedtab.EmbeddedForm.Close();
}
}
The main problem I am facing is I don't know how to access a function on a form from only knowing the selected tab. And I cant find it either.
Solution after using KyleWangs answer as base:
Custom Control:
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
string frmSearchName = "Frm" + SelectedTab.Name.Substring(3);
Form f = (Form)Application.OpenForms[frmSearchName];
if (f != null)
f.Close();
else
TabPages.Remove(SelectedTab);
}
Form:
private void SomeForm_FormClosing(object sender, FormClosingEventArgs e)
{
SetChanges();
if (HasChanges() && !CustomMessage.WarningBox("There is unsaved data. Are you sure you want to close?"))
e.Cancel = true;
else
((TabControl)((TabPage)this.Parent).Parent).TabPages.Remove((TabPage)this.Parent);
}
You can use property Application.OpenForms to get the open form instance.
private void Form1_Load(object sender, EventArgs e)
{
tabControl1.TabPages.Clear();
PageForm1 f1 = new PageForm1();
AddNewTab(f1);
}
private void AddNewTab(Form frm)
{
TabPage tab = new TabPage(frm.Text);
frm.TopLevel = false;
frm.Parent = tab;
frm.Visible = true;
tabControl1.TabPages.Add(tab);
frm.Location = new Point((tab.Width - frm.Width) / 2, (tab.Height - frm.Height) / 2);
tabControl1.SelectedTab = tab;
}
private void tabControl1_DoubleClick(object sender, EventArgs e)
{
Form f = (Form)Application.OpenForms[tabControl1.SelectedTab.Text];
f.Close();
tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
}
Related
I am a beginner at windows forms, and I am having some issues with opening child forms.
My application has 2 buttons, one that goes to the main menu, and another that goes to the options.
The problem is that, if I click on a checkbox in the options menu and leave the options tab and come back, the checkbox will not be checked anymore.
This is my code:
private Form CurrentChildForm;
private void OpenChildForm(Form childForm)
{
if(CurrentChildForm != null)
{
CurrentChildForm.Visible = false;
}
CurrentChildForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
PanelForForm.Controls.Add(childForm);
PanelForForm.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void MainMenu_Click(object sender, EventArgs e)
{
OpenChildForm(new MenuForm());
}
private void OptionsMenu_Click(object sender, EventArgs e)
{
OpenChildForm(new OptionsForm());
}
through your Click-Events on the different buttons you are always creating a new instance of your Forms.
A possible solution is to cache the instance of your optionsMenu for example through a private field, because I consider it being SingleInstance.
private Form CurrentChildForm;
private OptionsForm _opForm;
private void OptionsMenu_Click(object sender, EventArgs e)
{
if (_opForm == null)
{
_opForm = new OptionsForm();
}
OpenChildForm(_opForm);
}
On button click, I open a new form (lets say Form2), but I don't want that Form2 to open more than 1time. And I don't want to use .ShowDialog(), because it wont allow me to go to the Previous Form. How can I do that ?
You can use Application.OpenForms property to check if form already opened:
if (!Application.OpenForms.OfType<Form2>().Any())
{
Form2 form2 = new Form2();
form2.Show();
}
You can show existing form instead of creating new:
Form2 _form2 = null;
void Button1_Click(object sender, EventArgs e)
{
if (_form2 == null)
{
_form2 = new Form2();
_form2.Closed += Form2_Closed;
}
_form2.Show();
_form2.BringToFront();
}
private void Form2_Closed(object sender, System.EventArgs e)
{
_form2 = null;
}
You can issue the Show method, which will show the form and allow the users to get back to the form, but then you can also override the OnClosing event of the form:
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
}
and that will keep the users from being able to literally close the form. Finally, if you wanted, you could Hide the form when the user closes it:
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
}
and then you'll need to hold on to that instance in the first form so that you can re-show it when the button is clicked. So in the first form you might have a class field like this:
private Form2 _form2 = new Form2();
and then in the button click it would look like this:
_form2.Show();
and since they can't actually close the form this will always work.
You can try something like
bool windowIsNotOpen;
Mutex mutext = new Mutex(true, "Form2", out windowIsNotOpen);
if (!windowIsNotOpen)
{
// Form2 is already open
return;
}
You can do a static property that tells you whether it's open or not. You'd set it when the form is opened, and turn it off when the form is closed.
class Form2 {
public static bool IsOpen { get;set; }
public Form2() {
Load += (sender, e) => { Form2.IsOpen = true; };
Closed += (sender, e) => { Form2.IsOpen = false; };
}
}
Whenever you want to open it, check the flag first.
Form2 f;
bool isOpen = false;
private void button1_Click(object sender, EventArgs e)
{
if (f == null)
{
f = new Form2(); ;
f.FormClosed += new FormClosedEventHandler(f_FormClosed);
}
if (!isOpen)
{
isOpen = true;
f.Show();
}
}
void f_FormClosed(object sender, FormClosedEventArgs e)
{
isOpen = false;
}
Try this or use Application.OpenForms and check which one opened
I am developing a C# Windows Forms application. I would like to have a single instance of all the forms.
So, when the user clicks on the Contact button, for instance, twice, instead of having two contact forms, I would to bring the single instance contact form to the front.
How can I achieve this?
Check if the form exists in collection of open forms before creating and showing the form using Application.OpenForms
if (System.Windows.Forms.Application.OpenForms["Form1"] as Form1 != null)
MessageBox.Show("Form1 is opened");
else
MessageBox.Show("Form1 is not opened");
public static Form GetOpenedForm<T>() where T: Form {
foreach (Form openForm in Application.OpenForms) {
if (openForm.GetType() == typeof(T)) {
return openForm;
}
}
return null;
}
And in your code, where you create the ContactForm:
ContactForm form = (ContactForm) GetOpenedForm<ContactForm>();
if (form == null) {
form = new ContactForm();
form.Show();
} else {
form.Select();
}
Simple as that:
Form fc = Application.OpenForms["Form1"];
if (fc != null)
{
fc.Focus();
}
else
{
Form1 f1 = new Form1();
f1.Show();
}
You can disable the contactButton when it is clicked and open the contactForm-
private void contactButton_Click(object sender, EventArgs e)
{
contactButton.Enabled=false;
//code to open the contactForm
}
When the contactForm is closed, you can re-enable the button-
contactButton.Enabled=true;
Try this combo
First make contact form a global object
private ContactForm contactForm;
Then your contact button handler:
private void contactButton_Click(object sender, EventArgs e)
{
if (contactForm == null)
{
contactForm = new ContactForm();
contactForm.FormClosing += new FormClosingEventHandler(contactForm_FormClosing);
}
contactForm.Show();
}
Then handle the FormClosing event of the ContactForm to hide it rather than close it:
private void contactForm_FormClosing(object sender, FormClosingEventArgs e)
{
contactForm.Hide();
e.Cancel = true;
}
Or if you want the contact form to close, and open as new next time, handle the FormClosed instead:
private void contactForm_FormClosed(object sender, FormClosedEventArgs e)
{
contactForm = null;
}
Then next time the button is clicked, the null if clause will be caught and the form will be set to a new instance and opened.
Form2 form2 = null;
private void button1_Click(object sender, EventArgs e)
{
bool isFormExists = false;
foreach (Form openForm in Application.OpenForms)
{
if (openForm == form2 && openForm!=null)
{
openForm.Focus();
isFormExists = true;
break;
}
}
if (!isFormExists)
{
form2 = new Form2();
form2.Show();
}
}
I'd go with Otiel's answer. Also you can add a WindowState, because if the form is minimized it won't be shown. this answer can be used to get the restore method.
ContactForm form = (ContactForm) GetOpenedForm<ContactForm>();
if (form == null) {
form = new ContactForm();
form.Show();
} else {
//use this (if you want it to be restored to normal and focused)
//no need of extension method
//form.WindowState = FormWindowState.Normal;
//form.Select();
//or use this if you want it to be restored as previous state and focused
//You need a Restore extension method that can be found in the link above
form.Focus();
form.Restore();
}
I have a form and I want to get an instance of the same form as stated in the code below. And I have a button: every time I press this button, if a new form is created, I want it to focus to that window, if not, I want to create a new form.
I managed to create a new form but if I want to focus on it, the code did not work, any ideas?
private void btn_Click(object sender, EventArgs e)
{
if (opened == false)
{
Text = "form1";
var form = new myformapp();
form.Show();
opened = true;
form.Text = "form2";
}
else
{
if (Application.OpenForms[1].Focused)
{
Application.OpenForms[0].BringToFront();
Application.OpenForms[0].Focus();
}
if (Application.OpenForms[0].Focused)
{
Application.OpenForms[1].BringToFront();
Application.OpenForms[1].Focus();
}
}
}
You can try shortening your code without the need to introduce more variables with this example:
void button1_Click(object sender, EventArgs e) {
bool found = false;
for (int i = 0; i < Application.OpenForms.Count; ++i) {
if (Application.OpenForms[i].GetType() == typeof(myformapp) &&
Application.OpenForms[i] != this) {
Application.OpenForms[i].Select();
found = true;
}
}
if (!found) {
myformapp form = new myformapp();
form.Show();
}
}
Updated code from Francesco Baruchelli's comment.
If I understand correctly what you are trying to do, you can keep a static List with the opened forms. Everytime an instance of your Form is opened you add it to the List, and everytime it is closed you remove it. The when you press the button you can check the size of the List. If it is 1 you create a new Form, open it and set the focus on it. If the size is already 2, you look in the List for the instance which is different from the one executing the click event. The code could be something like this:
private static List<Form1> openForms = new List<Form1>();
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = null;
if (openForms.Count == 2)
{
foreach (Form1 aForm in openForms)
if (aForm != this)
{
frm = aForm;
break;
}
}
else
{
frm = new Form1();
frm.Show();
}
frm.Focus();
}
private void Form1_Load(object sender, EventArgs e)
{
openForms.Add(this);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
openForms.Remove(this);
}
I use MDI in MainForm.cs
public Le_MainForm()
{
InitializeComponent();
this.IsMdiContainer = true;
this.Name = "MainUSER";
}
private void barButtonItem_ListeOrdres_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Close_AllForm();
Liste_Ordres f_Liste = new Liste_Ordres();
f_Liste.MdiParent = this;
f_Liste.Show();
}
private void barButtonItem_CreatOrdreAller_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Close_AllForm();
Program.AllerRetour = "Ordre Aller";
Fiche_Ordre f_Fiche = new Fiche_Ordre();
f_Fiche.MdiParent = this;
f_Fiche.Show();
}
the question now, when I am in other form Ex.:Liste_Ordres.cs or Fiche_Ordre.cs how can i redirect from Fiche_Ordre.cs into Liste_Ordres.cs and vice versa without loosing MDI ?
When I'm in Fiche_Ordres.cs to go to Liste_Ordres.cs I use:
private void simpleButton_Annluer_Click_1(object sender, EventArgs e)
{
Liste_Ordres f_Liste = new Liste_Ordres();
f_Liste.Show();
this.Close();
}
But as you can see I lose the MDI, that mean when I click the menu on MainForm, the Liste_Ordres form will disappear.
as you can see in this Video that when i redirect From Liste to fiche, and then maximize the window i lose the menu that mean i lose Mdi.
You just need to set the MdiParent again:
f_Liste.MdiParent = this.MdiParent;