So I'm making a video editor and I want the program to open a new window when creating a file. So I created a new form and I wrote something like this:
Form fm = create_file(); fm.Show();
And I got an error, which said that create_file cannot be used as a method. I tried deleting the brackets, and it said that it's incorrect in the current context. How am I supposed to do this?
First you should write:
Form fm = new create_file();
then:
fm.Show();
Do not forget to write new when you create an Object from the Form fm!
public Form FormIsOpen(string name)
{
FormCollection forms = Application.OpenForms;
foreach (Form form in forms)
if (form.Name.Equals(name))
return form;
return null;
}
public void OpenForm(Form instance, string name)
{
Form form = FormIsOpen(name);
if (form == null)
instance.Show();
else
{
instance.Dispose();
form.Show();
form.WindowState = FormWindowState.Maximized;
form.Activate();
}
}
You can call by using below code
OpenForm(new MyForm(), nameof(MyForm));
Related
This is my code so far:
TickTock frmTick = new TickTock();
frmTick.Show();
frmTick.Activate();
this.Hide();
Basically, I want to change the code above, so that I can use parameters to determine the Forms that are shown/hidden.
Something like;
static void changeForm(object form, string i)
{
form i = new form()
i.show
}
I am not sure what part of this is causing you trouble, but the simplest way to write such a method would look like this:
public void SwitchTo<T>() where T : Form, new()
{
var form = new T();
form.Show();
this.Hide();
}
If you need to be able to implement this method outside of the form that is to be closed (meaning that the line this.Hide() wouldn't work), you can iterate all open forms and close them first:
public void SwitchTo<T>() where T : Form, new()
{
foreach (var f in Application.OpenForms) f.Hide();
var form = new T();
form.Show();
}
And you'd call it with:
SwitchTo<TickTock>();
How to Close background Forms whenever a new form is opened in Windows Forms C#?
It should not be the specific form to be closed.
It should close all the background forms whenever a form is opened.
Two approaches.
First is using Application.OpenForms like this:
foreach (Form form in Application.OpenForms)
{
if(Form is YourMainFormClassName) //Check if current form is your main form and do not close it since your app would close. You can use .Hide() if you want
return;
form.Close();
}
Other approach is using List but you cannot do List<Form> because when removing you will have problem if you want to remove specific form and you go like yourList.Remove(this) it will remove all items with class of that form. Of course it will happen only if you open one form multiple times but to avoid that we will use Form.Tag property.
An Object that contains data about the control. The default is null
So we will use it to store our Id of the form.
So now when we prepared system let's write it:
First we need List<Form> that is accessible from all classes so we will create it like public static property.
public static class Settings //Class is also static
{
public static List<Form> OpenedForms = new List<Form>();
public static int MaxIdOfOpenedForm() //With this method we check max ID of opened form. We will use it later
{
int max = -1;
foreach(Form f in OpenedForms)
{
if(Convert.ToInt32(f.Tag) > max)
max = Convert.ToInt32(f.Tag);
}
return max;
}
public static void RemoveSpecificForm(Form form) //Remove specific form from list
{
for(int i = 0; i < OpenedForms.Count; i++)
{
if((OpenedForms[i] as Form).Tag == form.Tag)
{
OpenedForms.Remove(form);
return;
}
}
}
public static void CloseAllOpenedForms()
{
for(int i = 0; i < OpenedForms.Count; i++)
{
OpenedForms.Remove(OpenedForms[i]);
}
}
}
Now we have list but need to populate it every time we open new form so we will do it like this:
public partial class YourForm
{
public YourForm()
{
InitializeComponents();
this.Tag = Settings.MaxIdOfOpenedForm() + 1; //We are setting Tag of newly opened form
Settings.OpenedForms.Add(this); //Adding new form to opened forms.
}
}
And when we close form we need to remove form from list:
private void YourFormClosed(object sender, EventArgs e)
{
RemoveSpecificForm(this);
}
and when we set this up just call CloseAllOpenedForms().
This method could have some improvements in performance but this is basic and you expand it further.
well as only one form can be active and in the foreground, so when openening a new form you can close the previous one:
In your main form:
Form previous_form = null;
and when creating any form:
if( previous_form != null)
previous_form.Close();
SomeForm someform = new SomeForm();
previsous_form = some_form;
someform.Show();
I have 2 projects in 1 solution first one to log into database second one have my main project my second project 'Class Library' Output.
I am trying send User Name from first project log in form to main project main form
I am using code
public string MyValue;
{
get { return txtUserName.Text; }
}
in log in window
and use
var frm1 = new DS4ERP .Core .Lanch .frmLogin ();
radLabel2.Text = frm1.MyValue;
i get nothing in second form
what is wrong ?
You are creating new Form instance. When you opening your second form use this:
Form2 f2 = new Form2(); // change Form2 with your second Form name
f2.Show(this);
Then change this code:
var frm1 = new DS4ERP.Core.Lanch.frmLogin ();
radLabel2.Text = frm1.MyValue;
To:
radLabel2.Text = ((frmLogin)Owner).MyValue;
I want to check if an instance of a form is opened and open the existing instance to update a textbox else create a new instance.
After searching I found : How to check if a windows form is already open, and close it if it is?
From the accepted answer I tried
try
{
foreach (Form fm in Application.OpenForms)
{
if (fm is Form2)
{
Form2 n1 = (Form2)Application.OpenForms["Form2"];
n1.textBox1.Text = textBox1.Text;
break;
}
else
{
Form2 n1 = new Form2();
n1.textBox1.Text = textBox1.Text;
n1.Show();
}
}
}
catch (InvalidOperationException)
{
}
Apart from that this code throws an InvalidOperationException (which i am already catching), The code doesn't work because if an instance already exists it still creates a new instance.
What am i doing wrong?
A better approach would be to filter the OpenForms based on the form type:
var form2collection = Application.OpenForms.OfType<Form2>();
You can then loop over those, or if the collection is empty, open a new form. The advantage is that you aren't relying on the form name, but the actual class definition of the form, which is more reliable.
Additionally, I tend to avoid direct manipulation of controls from other code. I find it more reliable if others call a method, such as
public void setSomeControl(string value)
{
this.controlName.Text = value;
}
then call
form2collection[0].setSomeControl("new value");
which allows your form to do all the housekeeping and the calling code can ignore those details.
I'm writing an application that uses a wizard-like series of 5 simple forms. The first form, NewProfile, is opened from a menu item on the main application, MainForm, so is a subform of MainForm. The second form, TwoProfile, is opened from a button on NewProfile. The third form, ThreeProfile is opened from a button on TwoProfile, and so on for all 5 forms. Here is the sequence:
MainForm --> NewProfile <--> TwoProfile <--> ThreeProfile <--> FourProfile <--> FiveProfile. My problem is that when any form (NewProfile, TwoProfile, ThreeProfile, FourProfile or FiveProfile) is open, I don't want a user to be able to create an instance of NewProfile.
I started out by implementing a Singleton pattern, which half-way works. It works if NewProfile is open and I go to MainForm and try to create another instance of NewProfile. It does not work if NewProfile has been destroyed, by advancing to the next form and one of TwoProfile, ThreeProfile, FourProfile or FiveProfile is open. It tells me that NewProfile.IsDisposed is true, giving me a bad reference to the Singleton instance.
What I can't figure out is how to do my logic so that NewProfile won't be created if one of TwoProfile, ThreeProfile, FourProfile or FiveProfile is open or if NewProfile itself is open.
I hope this made sense. I don't really have much code to post, except what I did for my Singleton.
private static NewProfile _instance = null;
public static NewProfile Instance
{
get
{
if (_instance == null)
{
_instance = new NewProfile();
}
return _instance
}
}
Thank you :)
As suggested in the comments, each "form" could actually be a usercontrol you swap. That way, you only have one form and multiple pages. Alternatively, you can hide the form.
If you want multiple forms instead, then you could loop through all the open forms and see if the the ones you want to check are open. If not, you can open NewProfile.
bool shouldOpenNewDialog = true;
foreach (Form f in Application.OpenForms)
{
//give each dialog a Tag value of "opened" (or whatever name)
if (f.Tag.ToString() == "opened")
shouldOpenNewDialog = false;
}
if(shouldOpenNewDialog)
np = new NewProfile();
It's untested, but it should loop through all open forms and look for any that has a Tag saying opened. If it comes across one, then it set the shouldOpenNewDialog flag to false and NewProfile won't be called.
The way that we handle this is to have a static window manager class that keeps track of the open form instances. When the user performs an action that would cause a new window to open, we first check the window manager to see if the form is already open. If it is, we set focus on it rather than creating a new instance.
Every form that is opened inherits from a base form implementation that automatically registers itself with the window manager when it is opened and removes its registration when it is closed.
Here is a rough outline of the WindowManager class:
public class WindowManager
{
private static Dictionary<string, Form> m_cOpenForms = new Dictionary<string, Form>();
public static Form GetOpenForm(string sKey)
{
if (m_cOpenForms.ContainsKey(sKey))
{
return m_cOpenForms[sKey];
}
else
{
return null;
}
}
public static void RegisterForm(Form oForm)
{
m_cOpenForms.Add(GetFormKey(oForm), oForm);
oForm.FormClosed += FormClosed;
}
private static void FormClosed(object sender, FormClosedEventArgs e)
{
Form oForm = (Form)sender;
oForm.FormClosed -= FormClosed;
m_cOpenForms.Remove(GetFormKey(oForm);
}
private static string GetFormKey(Form oForm)
{
return oForm.Name;
}
}
And you can use it as follows:
Form oForm = WindowManager.GetOpenForm("Form1");
if (oForm != null)
{
oForm.Focus();
oForm.BringToFront();
}
else
{
oForm = new Form1();
WindowManager.RegisterForm(oForm);
// Open the form, etc
}