I have this block of code:
Form1 newForm = new Form1();
newForm.Show();
//The rest of this code has been omitted
more or less. Form1 is just for example purposes. My issue is that I am creating a text editor (continuation of my last question, basically) and I want to be able to have more than one copy of Form1 open at once.
This code allows me to do that, which is great, but I want to be able to close the old one and still have the newForm on the screen. Currently, if I close Form1, I say goodbye to newForm.
Is this possible? I don't want to have to just white-out all the next like Notepad does.
I'm guessing your Form1 is also the one created and passed to Application.Run() in your main method, correct? Something like Application.Run(new Form1());
In that case (which is the default), you are telling the framework to exit the application when that form closes.
You probably want to change your main method to use the overload of Application.Run() that takes an ApplicationContext, and within the app context, create your forms - then when your last form closes, you can exit the application. The example in the link to MSDN shows a very similar case.
You could simply change main to:
Form1 newForm = new Form1();
newForm.Show();
Application.Run();
but the issue with this is that the application may not exit correctly without more housekeeping by you.
Added:
This is a simple example, but shows the concept. Create a ApplicationContext class like this one:
public class CustomContext : ApplicationContext
{
private readonly List<Form1> _openForms = new List<Form1>();
public CustomContext()
{
CreateForm();
}
private void CreateForm()
{
Form1 form = new Form1();
form.OpenNewForm += (sender, args) => CreateForm();
form.Closed += (sender, args) => FormClosed(sender as Form1);
_openForms.Add(form);
form.Show();
}
private void FormClosed(Form1 form)
{
_openForms.Remove(form);
if (_openForms.Count == 0)
{
ExitThread();
}
}
}
In your Program class, change main to Run(..) your new context class:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CustomContext());
}
And then in your Form1, make sure you have an event, and trigger that event to open new forms (note that in "real" code I'd probably abstract this away, or most likely let my DI container handle registration, but this shows the point much clearer) :
public event EventHandler OpenNewForm;
private void ButtonClick(object sender, EventArgs e)
{
//instead of showing a new form, we just raise this event
if (OpenNewForm != null) OpenNewForm(this, EventArgs.Empty);
}
What this does, is let the ApplicationContext manage your open forms, so that closing the first one (or any of them) does not exit the application until you close the last one. Once the last form closes, it exits the app.
You could do this so many different ways. For a working example of what you want to do, in the Program.cs file change the Main method():
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
Form1 frm = new Form1();
GlobalVariables.FormsList = new List<Form1>(); //new
GlobalVariables.FormsList.Add(frm); //new
frm.Show();
Application.Run();
}
Then on each of your Form1's have a button (or other event) that instantiates a new instance of the form1:
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
GlobalVariables.FormsList.Add(frm); //new
frm.Show();
}
Edit: Also add the following code to the FormClosing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (GlobalVariables.FormsList.Count == 1)
{
Application.Exit();
}
else
{
GlobalVariables.FormsList.RemoveAt(GlobalVariables.FormsList.Count - 1);
}
}
Edit: Here is the new GlobalVariables class with the list of Forms to aid form management:
public class GlobalVariables
{
public static List<Form1> FormsList { get; set; }
}
If you are closing the form using it's 'x' button it will not affect the other form.
If you are closing by code you should get the object of that form properly and close it. It would be better if you can keep a catalog of forms so that the management will be easy.
If there are any static variables involved in between try changing that logic without static variables as they are shared across the objects.
Depending on what exactly you want to do, you can have the form launched by Application.Run be a form that just launches other forms, (e.g. your text-editor form).
Something like: (This is just an example to demonstrate the idea.)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Shown += Form1_Shown;
}
void Form1_Shown(object sender, EventArgs e)
{
TextEditorForm frm2 = new TextEditorForm(this);
frm2.Show();
this.Hide();
}
}
And:
public partial class TextEditorForm : Form
{
Form1 frm1;
public TextEditorForm(Form1 frm1)
{
InitializeComponent();
this.frm1 = frm1;
}
private void button1_Click(object sender, EventArgs e)
{
frm1.Show();
this.Close();
}
}
Related
Whenever I need to show another Form, I always instantiate a new Form Object to show another Form (then hiding the current form).
/*Code in Form1*/
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
this.Hide();
}
After I instantiated and showed the second Form, I want to dispose the previous form (to free up some memory usage) but it is not working on the main context form.
However, the Dispose() method is working on other WinForms which is
not the main context form.
/*Code in Form2*/
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Show();
this.Dispose();
}
Is it possible to instantiate a Form Object once only, then eventually to call/show it whenever I need it?
You can start your own ApplicationContext, and pass that to every form you want to make the MainForm. You shouldn't keep forms in memory and open and close them at will in my opinion. This could lead to potential memory leaks.
ApplicationContext ac = new ApplicationContext();
ac.MainForm = new Form1(ac);
Application.Run(ac);
(You will put this in the place of Application.Run(new Form1());)
In Form1, when you want to make Form2 the main form:
ac.MainForm = new Form2(ac);
this.Close();
This way, the form can be disposed (since you called Close() and used Show it will automatically dispose) and memory can be cleared. The instance of Form2 will be the new main form.
/*Code in Form1*/
Form2 frm2; // --> Inside the class
private void button1_Click(object sender, EventArgs e)
{
if (frm2 == null)frm2 = new Form2();
frm2.Show();
this.Hide();
}
.
/*Code in Form2*/
Form1 frm1;
//Constructor
public Form2(Form1 frm)
{
frm1= frm;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frm1.Show();
this.Hide();
}
I would create a class called "FormHandler"
this may have a method like
here some prototype code (not tested)
public static class FormHandler
{
private static readonly Dictionary<string,Form> Instances = new Dictionary<string,Form>();
public TForm CreateFrom<TForm>()
{
string typeName = typeof(TForm).FullName;
if(Instances.ContainsKey(typeName))
{
return Instances[typeName]
}
else
{
// Create Instace with Activator.CreateInstance,
// and bind the dispose event to remove the form from the collection
// on dispose . Also make sure that you unbind the dispose Event
[...]
}
}
Now the buttonClick would just call
FormHandler.CreateForm<Form2>().Show();
with seperating the code to a new class you can avoid copy and paste in all buttons
In my project I have a Settings form and a Main form.
I'm trying to call the Main form's MasterReset function from the Setting form, but nothing happens.
The Master form's Masterreset function looks like this.
public void MasterReset()
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to perform master reset? All settings will be set to default.", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Yes)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string phonebook_path = path + "\\Phonebook\\Contacts.xml";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(phonebook_path);
XmlNode xNode = xDoc.SelectSingleNode("People");
xNode.InnerXml = "";
xDoc.Save(phonebook_path);
listView1.Clear();
people.Clear();
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
And I'm accessing it from the Settings form like this
private void btn_MasterReset_Click(object sender, EventArgs e)
{
Main f1 = new Main();
f1.MasterReset();
}
Why am I not seeing any results?
Do you know what composition over inheritance is?
In the form where you have MasterReset you should do something like this:
Llet's suppose that in your second form you have something like this, and let's suppose your "mainform" will be called "MasterForm".
public partial class Form1 : Form
{
private MasterForm _masterForm;
public Form1(MasterForm masterForm )
{
InitializeComponent();
_masterForm = masterForm;
}
}
Here's the code in your masterForm Class:
private void button2_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1(this);
}
Here's in your form1:
private void btn_MasterReset_Click(object sender, EventArgs e)
{
_masterForm.MasterReset();
}
Hope this helps!
This worked for me: In your Program class, declare a static instance of Main (The class, that is) called Form. Then, at the beginning of the Main method, use Form = new Main(); So now, when starting your app, use
Application.Run(Form);
public static Main Form;
static void Main() {
Form = new Main();
Application.Run(Form)
}
Now, calling a function from another form is simple.
Program.Form.MasterReset(); //Make sure MasterReset is a public void
namespace F1
{
// Method defined in this class
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//This method I would like to call in other form
public void function()
{
MessageBox.Show("Invoked");
}
// opening the new form using button click
private void OpenNewForm_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
}
// This is second form
public partial class Form2: Form
{
public Form2()
{
InitializeComponent();
}
// on button click Form1 method will be called
private void button1_Click(object sender, EventArgs e)
{
var mainForm = Application.OpenForms.OfType<Form1>().Single();
mainForm.function();
}
}
}
There are multiple solutions possible. But the problem itself arise from the bad design. If you need something to be accessed by many, then why should it belong to someone? If, however, you want to inform something about anything, then use events.
Your mistake is what you are creating another instance of form1, thus MasterReset is operating with form, which is not even shown.
What you can do:
Make (as Ravshanjon suggest) a separate class to handle that MasterReset (and maybe something else). But also add to it an event. form1 and form2 can both subscribe to it and whenever either of them call MasterReset - both will react.
Create form dependency (as BRAHIM Kamel suggested): when you create form2, then pass to it form1 instance (as constructor parameter or by setting public property), to be able to call public non-static methods of form1.
As a quick, but relatively legimate solution, make this method static:
private static Form1 _instance;
public Form1()
{
InitializeComponents();
_instance = this;
}
public static void MasterReset()
{
// alot of code
_instance.listView1.Clear();
// alot of code
}
this way you can call MasterReset from any other form like this Form1.MasterReset(). Disadvantage of this method is what you can not have more than one instance of form2 (which is more likely anyway).
I understand your problem, you can declare your function as public static void(also listView1 and people should be static too). Then when you want to call to like this:
private void btn_MasterReset_Click(object sender, EventArgs e)
{
Main.MasterReset();
}
How would you make an instance of a form open itself in a Modal way?
I tried this.ShowDialog() but it doesn't make the form appear modal (you can still access other forms). I guess this is because it is it's own parent form in if it shows itself, but I'm not sure.
My problem:
I have an application made of 2 forms:
MainForm
LoginForm
MainForm creates an instance of and opens LoginForm to ask the user to authenticate. LoginForm has a timer to regularly check and log the user in - I want this timer to open LoginForm modally. I know this could be achieved by putting the timer in MainForm but I would like to know how to make a form ShowDialog() an instance of itself.
Thanks in advance.
Make sure you call ShowDialog after InitializeComponent:
public newForm()
{
InitializeComponent();
this.ShowDialog();
}
MY TEST
I made new class named Form2:
public partial class Form2 : Form
{
public Form2()
{
//this may not call in constractor
//InitializeComponent();
}
public void ShowModalForm()
{
InitializeComponent();
ShowDialog();
}
}
and start it on main without any parent and it starts modally:
static class Program
{
[STAThread]
static void Main()
{
new Form2().ShowModalForm();
//Application.Run(new Form1());
}
}
Form won't be modal if it's a top-level window (has no parent). On the other hand, if your form will have other form as a parent, then it will open modally (blocking parent) on .ShowDialog().
Here is option for you - define LoginExpired event on your LoginForm. Raise this event on timer tick event handler:
public partial class LoginForm : Form
{
public event EventHandler LoginExpired;
public LoginForm()
{
InitializeComponent();
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
OnLoginExpired();
}
protected virtual void OnLoginExpired()
{
if (Visible)
return; // if this form visible, then user didn't authenticate yet
if (LoginExpired != null)
LoginExpired(this, EventArgs.Empty);
}
}
Then subscribe on this event on your Main method:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (LoginForm loginForm = new LoginForm())
{
if (loginForm.ShowDialog() != DialogResult.OK)
return;
loginForm.LoginExpired += new EventHandler(loginForm_LoginExpired);
Application.Run(new MainForm());
}
}
static void loginForm_LoginExpired(object sender, EventArgs e)
{
LoginForm loginForm = (LoginForm)sender;
if (loginForm.ShowDialog() != DialogResult.OK)
throw new NotAuthenticatedException();
}
There is two Forms in my project : Form1 and Form2.
There is a button in Form1, and what I want to do is closing Form1 and showing Form2 when that button clicked.
First, I tried
Form2 frm = new Form2();
frm.Show();
this.Close();
but as Form1 was closed, Form2 also got closed.
Next, I tried
Form2 frm = new Form2();
frm.Show();
this.Hide();
but there is a disadvantage that the application does not exit when the Form2 is closed.So, I had to put in additional sources in form_FormClosing section of Form2.
Hmm.... I wonder whether this is the right way....So, what is the proper way of handling this problem?
The auto-generated code in Program.cs was written to terminate the application when the startup window is closed. You'll need to tweak it so it only terminates when there are no more windows left. Like this:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var main = new Form1();
main.FormClosed += new FormClosedEventHandler(FormClosed);
main.Show();
Application.Run();
}
static void FormClosed(object sender, FormClosedEventArgs e) {
((Form)sender).FormClosed -= FormClosed;
if (Application.OpenForms.Count == 0) Application.ExitThread();
else Application.OpenForms[0].FormClosed += FormClosed;
}
By default, the first form controls the lifetime of a Windows Forms application. If you want several independent windows forms your application context should be a separate context from the forms.
public class MyContext : ApplicationContext
{
private List<Form> forms;
private static MyContext context = new MyContext();
private MyContext()
{
forms = new List<Form>();
ShowForm1();
}
public static void ShowForm1()
{
Form form1 = new Form1();
context.AddForm(form1);
form1.Show();
}
private void AddForm(Form f)
{
f.Closed += FormClosed;
forms.Add(f);
}
private void FormClosed(object sender, EventArgs e)
{
Form f = sender as Form;
if (form != null)
forms.Remove(f);
if (forms.Count == 0)
Application.Exit();
}
}
To use the context, pass it to Application.Run (instead of the form). If you want to create another Form1, call MyContext.ShowForm1() etc.
public class Program
{
public void Main()
{
Application.Run(new MyContext());
}
}
You can take this way:
form2 f2=new form2()
this.Hide();
f2.Show();
Hope it was helpful.
Write that into your method which is executed while FormClosing event occure.
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Display a MsgBox asking the user if he is sure to close
if(MessageBox.Show("Are you sure you want to close?", "My Application", MessageBoxButtons.YesNo)
== DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = false;
// e.Cancel = true would close the window
}
}
For example, Assume that I'm in form 1 then I want:
Open form 2( from a button in form 1)
Close form 1
Focus on form 2
Steve's solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().
private void OnButton1Click(object sender, EventArgs e)
{
this.Hide();
var form2 = new Form2();
form2.Closed += (s, args) => this.Close();
form2.Show();
}
Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main, form2 can simply be created using Application.Run just like form1 before. Here's an example scenario:
I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I'm using two forms: LogingForm and MainForm. The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here's the code for this:
class LoginForm : Form
{
public bool UserSuccessfullyAuthenticated { get; private set; }
void LoginButton_Click(object s, EventArgs e)
{
if(AuthenticateUser(/* ... */))
{
UserSuccessfullyAuthenticated = true;
Close();
}
}
}
static class Program
{
[STAThread]
static void Main()
{
LoginForm loginForm = new LoginForm();
Application.Run(loginForm);
if(loginForm.UserSuccessfullyAuthenticated)
{
// MainForm is defined elsewhere
Application.Run(new MainForm());
}
}
}
Try to do this...
{
this.Hide();
Form1 sistema = new Form1();
sistema.ShowDialog();
this.Close();
}
The problem beings with that line:
Application.Run(new Form1());
Which probably can be found in your program.cs file.
This line indicates that form1 is to handle the messages loop - in other words form1 is responsible to keep executing your application - the application will be closed when form1 is closed.
There are several ways to handle this, but all of them in one way or another will not close form1.
(Unless we change project type to something other than windows forms application)
The one I think is easiest to your situation is to create 3 forms:
form1 - will remain invisible and act as a manager, you can assign it to handle a tray icon if you want.
form2 - will have the button, which when clicked will close form2 and will open form3
form3 - will have the role of the other form that need to be opened.
And here is a sample code to accomplish that:
(I also added an example to close the app from 3rd form)
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); //set the only message pump to form1.
}
}
public partial class Form1 : Form
{
public static Form1 Form1Instance;
public Form1()
{
//Everyone eveywhere in the app should know me as Form1.Form1Instance
Form1Instance = this;
//Make sure I am kept hidden
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false;
Visible = false;
InitializeComponent();
//Open a managed form - the one the user sees..
var form2 = new Form2();
form2.Show();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form3 = new Form3(); //create an instance of form 3
Hide(); //hide me (form2)
form3.Show(); //show form3
Close(); //close me (form2), since form1 is the message loop - no problem.
}
}
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.Form1Instance.Close(); //the user want to exit the app - let's close form1.
}
}
Note: working with panels or loading user-controls dynamically is more academic and preferable as industry production standards - but it seems to me you just trying to reason with how things work - for that purpose this example is better.
And now that the principles are understood let's try it with just two forms:
The first form will take the role of the manager just like in the previous example but will also present the first screen - so it will not be closed just hidden.
The second form will take the role of showing the next screen and by clicking a button will close the application.
public partial class Form1 : Form
{
public static Form1 Form1Instance;
public Form1()
{
//Everyone eveywhere in the app show know me as Form1.Form1Instance
Form1Instance = this;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Make sure I am kept hidden
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false;
Visible = false;
//Open another form
var form2 = new Form2
{
//since we open it from a minimezed window - it will not be focused unless we put it as TopMost.
TopMost = true
};
form2.Show();
//now that that it is topmost and shown - we want to set its behavior to be normal window again.
form2.TopMost = false;
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.Form1Instance.Close();
}
}
If you alter the previous example - delete form3 from the project.
Good Luck.
You weren't specific, but it looks like you were trying to do what I do in my Win Forms apps: start with a Login form, then after successful login, close that form and put focus on a Main form. Here's how I do it:
make frmMain the startup form; this is what my Program.cs looks like:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
in my frmLogin, create a public property that gets initialized to false and set to true only if a successful login occurs:
public bool IsLoggedIn { get; set; }
my frmMain looks like this:
private void frmMain_Load(object sender, EventArgs e)
{
frmLogin frm = new frmLogin();
frm.IsLoggedIn = false;
frm.ShowDialog();
if (!frm.IsLoggedIn)
{
this.Close();
Application.Exit();
return;
}
No successful login? Exit the application. Otherwise, carry on with frmMain. Since it's the startup form, when it closes, the application ends.
use this code snippet in your form1.
public static void ThreadProc()
{
Application.Run(new Form());
}
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}
I got this from here
If you have two forms: frm_form1 and frm_form2 .The following code is use to open frm_form2 and close frm_form1.(For windows form application)
this.Hide();//Hide the 'current' form, i.e frm_form1
//show another form ( frm_form2 )
frm_form2 frm = new frm_form2();
frm.ShowDialog();
//Close the form.(frm_form1)
this.Close();
I usually do this to switch back and forth between forms.
Firstly, in Program file I keep ApplicationContext and add a helper SwitchMainForm method.
static class Program
{
public static ApplicationContext AppContext { get; set; }
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Save app context
Program.AppContext = new ApplicationContext(new LoginForm());
Application.Run(AppContext);
}
//helper method to switch forms
public static void SwitchMainForm(Form newForm)
{
var oldMainForm = AppContext.MainForm;
AppContext.MainForm = newForm;
oldMainForm?.Close();
newForm.Show();
}
}
Then anywhere in the code now I call SwitchMainForm method to switch easily to the new form.
// switch to some other form
var otherForm = new MyForm();
Program.SwitchMainForm(otherForm);
private void buttonNextForm(object sender, EventArgs e)
{
NextForm nf = new NextForm();//Object of the form that you want to open
this.hide();//Hide cirrent form.
nf.ShowModel();//Display the next form window
this.Close();//While closing the NextForm, control will come again and will close this form as well
}
//if Form1 is old form and Form2 is the current form which we want to open, then
{
Form2 f2 = new Form1();
this.Hide();// To hide old form i.e Form1
f2.Show();
}
This code may help you:
Master frm = new Master();
this.Hide();
frm.ShowDialog();
this.Close();
this.Visible = false;
//or // will make LOgin Form invisivble
//this.Enabled = false;
// or
// this.Hide();
Form1 form1 = new Form1();
form1.ShowDialog();
this.Dispose();
I think this is much easier :)
private void btnLogin_Click(object sender, EventArgs e)
{
//this.Hide();
//var mm = new MainMenu();
//mm.FormClosed += (s, args) => this.Close();
//mm.Show();
this.Hide();
MainMenu mm = new MainMenu();
mm.Show();
}
Everyone needs to participate in this topic :). I want to too!
I used WPF (Windows Presentation Foundation) to close and open windows.
How I did:
I used clean code, so I deleted App.xaml and create Program.cs
Next, a window manager was created
The program analyzes the keys and the manager can launch either 1 window or 2 windows (1 informational, then when the button is pressed, it closes and a new main window 2 opens)
internal class Program
{
[STAThread]
public static void Main(string[] args)
{
Mgm mgm = new Mgm(args);
mgm.SecondaryMain();
}
}
internal class Mgm
{
private Dictionary<string, string> argsDict = new Dictionary<string, string>();
private InformWindow iw = null;
private MainWindow mw = null;
private Application app = null;
public Mgm(string[] args)
{
CheckInputArgs(args);
}
private void CheckInputArgs(string[] strArray)
{
if (strArray.Length == 0)
return;
for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i].StartsWith("-") && !argsDict.ContainsKey(strArray[i]))
argsDict.Add(strArray[i], null);
else
if (i > 0 && strArray[i - 1].StartsWith("-"))
argsDict[strArray[i - 1]] = strArray[i];
}
}
public void SecondaryMain()
{
if (!argsDict.ContainsKey("-f"))
return;
if (argsDict.ContainsKey("-i"))
{
if (String.IsNullOrEmpty(argsDict["-i"]) || !int.TryParse(argsDict["-i"], out _))
iw = new InformWindow();
else
iw = new InformWindow(int.Parse(argsDict["-i"]));
iw.PleaseStartVideo += StartMainWindow;
app = new Application();
app.Run(iw);
}
else
{
app = new Application();
mw = new MainWindow(argsDict["-f"]);
app.Run(mw);
}
}
private void StartMainWindow(object o, EventArgs e)
{
mw = new MainWindow(argsDict["-f"]);
app.MainWindow = mw;
app.MainWindow.Show();
iw.Close();
}
}
The most important thing in this matter is not to get confused with the system.windows.application class
In my case I have three windows: mainWindow, form1, form2. The mainWindow and form1 are shown. Form2 should be additionaly displayed. Form1 should get hidden. But when calling form1.Hide(); the form1 and the mainWindow get hidden.
The solution in my case was:
var form2 = new Form2();
form2.Shown += (s, args) => form1.Hide(); // here only the form1 is hidden not the mainWindow
form2.Closed += (s, args) => form1.Close();
form2.Show();
Suppose you have two Form, First Form Name is Form1 and second form name is Form2.You have to jump from Form1 to Form2 enter code here. Write code like following:
On Form1 I have one button named Button1, and on its click option write below code:
protected void Button1_Click(Object sender,EventArgs e)
{
Form frm=new Form2();// I have created object of Form2
frm.Show();
this.Visible=false;
this.Hide();
this.Close();
this.Dispose();
}
Hope this code will help you
I would solve it by doing:
private void button1_Click(object sender, EventArgs e)
{
Form2 m = new Form2();
m.Show();
Form1 f = new Form1();
this.Visible = false;
this.Hide();
}