C#: Close and Open two forms from a separate form - c#

I have 3 forms. How can I make it so that one form is shown with .Show() and the other is hidden with .Hide() from a separate form?
This is part of my code
private void buttonYes_Click(object sender, EventArgs e)
{
LoggedIn loggedinform = new LoggedIn();
loggedinform.Hide(); // Hides another form that is in the background
MainForm mainform = new MainForm();
mainform.Show(); // Show first form
this.Hide(); // Hides current form
}
One problem, the LoggedIn form does not hide itself. From the looks of it it skips it and just goes for the mainform.Show();
Is this a bug or do I need to do something else?

The line LoggedIn loggedinform = new LoggedIn() is going to create a new instance of that login window. That might be useful if, say, you intended to show 5 "Login" windows onscreen all at once. I think what you want to do is retrieve a reference to the login window that is already showing, and hide that; so, avoid creating a new one.
Properly passing references to existing objects around the program is kind of a structural problem, and one that I ran into quite a bit in my early programming days. The quick, unclean, and generally not-recommended way is to declare instances of those singular objects (like, maybe, your login window) as static, so they can be retrieved anywhere. However, to fully answer your question in the best way, maybe you could describe the structure of your program a bit more (full code isn't necessary, just generally-speaking, what the flow is between classes)

Ok I figured it out. I can use
Application.OpenForms[1].Hide();
[1] is the form I'm trying to hide. And it worked.
I also realized thanks to Katana that it makes sense why it wasn't working because it was basically making a new instance of the form instead of finding the current one. Sorry that my code is a mess.

Related

Showing and Hiding forms all over the project

I want to hide and close a form from every form of the project. I mean, if I am in form2, at clicking a button, I want form1 to be shown or hidden, depends of necesities. I can't find a way, I searched everywhere I could about OOP of doing this, but I still can't figure it out. Do I have to create a new instance of every form everytime?
Hmm, The reshowing i don't know 100% sure, but hiding them should be easy with the following code:
YourFormName newYourFormName = new YourFormName();
newYourFormName.Parent = this;
newYourFormName.ShowDialog();
this.Hide(); // or to close it:
this.Close();
Add this to the button, replace YourFormName for your form that you want to close.
For re-show you could try an if statement, im not at my PC atm so cant check for working code on that. but this should work.

Costum, code generated buttons and forms, and linking them together in C#

Hello Everyone
In the following, I am going to give you a routh idea of what I am trying to accomplish with the program I am trying to code at the moment bevor describing the problem I am struggeling to solve. Thanks for your help!
The Program
Purpose
Timers. Multiple of them. Each timer should be displayed on an individual form, being controlled by individual buttons and having a unique design, once again set up by user settings.
Layout
The program itself should be made up by one main form, containing all "start" and "stop" buttons for each timer. However, the timer forms should be open at all time. Meaning, once the user has changed the properties, all timer forms should be closed again and depending on the settings new forms should open.
Question
In generell, I know how to open a form in such a way to change properties and componants from another form. Example:
namespace example
{
public partial class Form1 : Form
{
Form2 timerForm1;
private void Form1_Load(object sender, EventArgs e)
{
timerForm1 = new Form();
timerForm1.Show();
}
//now you are able to access Form2 in different functions, like:
{
timerForm1.label1.Text = "00:02:56";
}
}
}
However, I need to open as many forms as the user declares, meaning I can not set up variables in fore hand. However, I need to access those opend forms just like in the given example.
I would like to store the different, user declared timers inside an array or list if possible, if there is a smarter, easier or faster way i can adapt and change it to whatever is required to get it working.
I didn't really understand what or if you have an issue with the timers. But controlling various amount of forms from each individual is not that hard.
As I understand that you want to control various amount of Form2 instances from one Form1. In that case you can make a List of Form2 and add each Form2 you creat to that list.

How to make an application which has another screen in the extended screen?

I want to make an application which has another screen in the extended screen in another monitor (or in my case projector), similar to the presenter view in power point.
I want to use C#, and I guess in windows form application or wpf template there is no dual screen application support.
My first guess is to make 2 separate project and connect them, but I'm not sure about it either.
Any idea how to do it, or at least someone has a tutorial related to it?
I've looked at google, but still not sure what the right question to the issue, since google always showed "how to set up dual screen" for users.
Please clarify anything if my question is unclear. Thanks.
The easiest method I can think of is to simply create a second form (assuming you use Window Forms for your project), so you'd have Form1 as the default, and Form2 as your second form.
Run Form1 by default, and then while loading Form1, do something like this:
if(System.Windows.Forms.Screen.AllScreens.Length > 1)
{
Form2 form2 = new Form2();
form2.Show();
}
Then within form2's shown event, set it's position to the second screen (and perhaps maximize it, depending on what you need).
private void Form2_Shown(object sender, EventArgs e)
{
this.Location = Screen.AllScreens[1].Bounds.Location;
this.WindowState = FormWindowState.Maximized;
}
From that point on (and provided you keep a reference to Form2 within Form1), you can easily exchange information between the two forms as needed. You could even expand it to support 3-4 monitors, simply by making multiple Form2's, one for each screen

How to create navigation inside program Form

Warning! This is noob question probably! Sorry in advance.
I'm learning C# (using MS Studio 2013) and I'm having hard time creating some kind of decent navigation in simple desktop program.
Basically what I want is this: MenuStrip with options like "calculate something", "Calculate somethingelse"... and other (that I can easily add later - like dynamic menu on a webpage). If you click first option inside the Form connected with the StripMenu you will get some controls that allows you to do something(like inputs on a webpage). If you click the second all these options will disappear and you will get a fresh set of controls where you can do somethingelse (simply another webpage to play with).
What is the best way to do it (I find it amazing hard to find out :) ). Only way I figured out (more from experience in js then tutorials) is to use show/hide like in javascript/html.
ExamplePanel.Visible = false;
ExampleOtherPanel.Visible = true;
But this doesn't seem right - I think it would be impossible to manage in bigger program (not only in code, but visual designer too - you can only fit that much Panels inside Form).
Any advice? Or at least a link to material where I can find out?
EDIT:
Finaly I gave up and used multiple Forms as sugested in answer.
private void MenuStripExample_Click_1(object sender, EventArgs e)
{
SomeForm SomeForm = new SomeForm();
this.Hide(); //Hide the main form before showing the secondary
SomeForm.ShowDialog(); //Show secondary form, code execution stop until SomeForm is closed
//this.Show(); //You may uncomment this if you want to have the previous Form to get back after you close new one
}
You normaly don't hide and show panels with different layouts. This is not a good design.
If you have complete different navigations/control sets, then create a new Form which is responsible for the control set.
If you don't want to use new Forms take a look at the TabControl.
You may also want to take a look at MDI-Container. You can use a Form as a MDI-Container and display various other Forms as child-elements inside of this container.

Load a form without showing it

Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:
tasksForm.Visible = false;
tasksForm.Show();
Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.
When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:
tasksForm.WindowState = FormWindowState.Minimized;
tasksForm.Show();
I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.
Perhaps it should be noted here that you can cause the form's window to be created without showing the form. I think there could be legitimate situations for wanting to do this.
Anyway, good design or not, you can do that like this:
MyForm f = new MyForm();
IntPtr dummy = f.Handle; // forces the form Control to be created
I don't think this will cause Form_Load() to be called, but you will be able to call f.Invoke() at this point (which is what I was trying to do when I stumbled upon this SO question).
It sounds to me like you need to sit down and re-think your approach here. I cannot imagine a single reason your public methods need to be in a form if you are not going to show it. Just make a new class.
I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist.
It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.
From MSDN:
Form.Load
Occurs before a form is displayed for the first time.
Meaning the only thing that would cause the form to load, is when it is displayed.
Form.Show(); and Form.Visible = true; are the exact same thing. Basically, behind the scenes, Show checks for various conditions, then sets Visible to true. So obviously, setting visible to false (which it already is) before showing the form is meaningless.
But let's forget the technicalities. I completely agree with Rich B and Shaun Austin - the logic shouldn't be in that form anyway.
Sometimes this would be useful without it being bad design. Sometimes it could be the start of a migration from native to managed.
If you were migrating a c++ app to .NET for example, you may simply make yourwhole app a child window of the .NET form or panel, and gradually migrate over to the .NET by getting rid of your c++ app menu, status bar, toolbar and mapping teh .NEt ones to your app using platform invoke etc...
Your C++ app may take a while to load, but the .NET form doesn't..in which you may like to hide the .NEt form until your c++ app has initialised itself.
I'd set opacity=0 and visible=false to false after calling show, then when your c++ app loads, then reverse.
If you make the method public, then you could access it directly.... however, there could be some unexpected side effects when you call it. But making it public and calling it directly will not draw the screen or open the form.
Move mandatory initialization code for the form class out of the Load event handler into the constructor. For a Form class, instantiation of an instance (via the constructor), form loading and form visibility are three different things, and don't need to happen at the same time (although they do obviously need to happen in that order).
None of the answers solved the original question, so, add the below, call .Show() to load the form without showing it, then call .ShowForm() to allow it to be visible if you want to after:
private volatile bool _formVisible;
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(_formVisible);
}
public void ShowForm()
{
_formVisible = true;
if (InvokeRequired)
{
Invoke((Action) Show);
}
else
{
Show();
}
}

Categories