How can I set the default visibility of the main Winform - c#

I have run my program step by step, but still, I can't find where the form.visible is set.
Here is the code of "Form1.cs":
public Form1()
{
InitializeComponent();
this.Hide();
}
I added this.Hide(); but it didn't work at all.
and I even modified "Program.cs" from:
Application.Run(new Form1());
to:
Form1 form1=new Form1();
form1.Visible = false;
Application.Run(form1);
But the main form still showed, even adding form1.Enable=false; won't stop the form from showing. I have also tried adding this.Hide(); in Form1_Load(), it worked but the main form appeared and flashed before it was finally hidden.
I'm totally confused now. So how can I load the main form without showing it? And keep it hidden until I call this.Show();?

Why not override the SetVisibleCore method:
bool showForm = false;
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(showForm);
}
This will hide the form before it even opens up. With a lot of method's you see a brief flash of the form before its .Visible or similar property is set to "hide".
Obviously you will need another method to flip 'showForm' to true when you want to display it again i.e. NotifyIcon event.

you can not set form visible to false before load it try this code:
//In Main Function
Form1 form1 = new Form1();
form1.WindowState = FormWindowState.Minimized;
form1.ShowInTaskbar = false;
Application.Run(new Form1());
//In Form Shown
private void Form1_Shown(object sender, EventArgs e)
{
this.Visible = false;
}

The documentation for Application.Run(Form) clearly spells out that it will make the form visible. As long as you need to keep it hidden, you should therefore not pass that form to Application.Run. Depending on your needs, you may be able to use Application.Run() (no arguments) or Application.Run(context) (create a custom ApplicationContext) instead.
Edit: I just want to add that to not show the form, you should not show the form. I don't understand how so many users here think it's a good idea to show the form and then hide it really quickly, or make the code that shows the form not show the form. You shouldn't be doing the wrong thing and then fixing it after the fact, you should do the right thing in the first place.

You might be looking for the Opacity property. You can set Opacity to 0.0 from the IDE. It can take values between 0.0 and 1.0.

You could try something like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form1();
form.DoBeforeShow();
Application.Run(form);
}

First you can load the form you permanently want to show to the user. In the constructor only call the form which should be hidden. Afterwards you can close or hide it.

Related

Windows forms Form closed event not working with opening a new form

I have some code meant to open a new windows form when one is closed, and yet I get nothing, no error.
I've tried a few different methods for opening a new form on a Form.FormClosed event.
This is the code I have right now:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 myForm = new Form1();
myForm.Show();
}
But yet I get no error, nothing.
I'm expecting for a new windows form to be opened when I close another one.
Any help would be appreciated, thanks!
The problem is that as soon as the first Form1 instance closes, your application shuts down and exits because the application message loop is defined with the initial Form instance, and it is just waiting for events on that form until it closes. On closing, the application will exit, opening a new form doesn't stop this process.
You need to adjust the Main() method in Program.cs to look something like this:
[STAThread]
static void Main()
{
// ... Application configuration as required here
new Form1().Show(); // The first form instance is now no longer bound to the Application message loop. Start it before we begin the run loop
Application.Run(); // Don't pass in Form1
}
Your original code should now work. I might add however, this is not a great user experience. Carefully consider what you're trying to achieve, and perhaps consider alternatives - do you just need a "reset form" button? Or is the primary goal to prevent a user from closing the application? If the latter, you can remove the Close icon altogether.
Perhaps something simple to get your going forward.
private Form1 myForm = new Form1(); //Declare the form as a private member variable
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
e.Cancel = true; //Cancel the closing so this object stays alive
this.Visible = false; //Hide this form
myForm.Show(); //Show the next form
}
Please note #pcdevs comment. You'll need a way to indicate the form is being closed/application quiting vs progressing to the next step/form. You might want to look at some CodeProject articles about "C# Winform Wizards", those sequential dialog prompt apps...

C# unload and load form / hide and close

I am coding a simple sidescroller in C# using Windows Form Applications. I want it so when the player touches an exit point, this immediately loads a new level.
To implement this, I use the following code:
if (player.Bounds.IntersectsWith(exit.Bounds))
{
Form2 myNewForm = new Form2();
myNewForm.Visible = true;
this.Hide();
}
This works. However, it loads numerous instances of form2 - I only want it to load once. I don't know how to write this (sorry, I'm a newbie - it took me a while just to write this code!).
Also, loading a level via a new form is inefficient. Is there a way to unload the open form to load the next one in the same window/instance, rather than creating another separate window?
Sorry if this is unclear. I've done my best research + I'm new. Please don't mention XNA! Thanks.
You need a small modification to your project's Program.cs file to change the way your app decides to terminate. You simple exit when there no more windows left. Make it look like this:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var start = new Form1();
start.FormClosed += WindowClosed;
start.Show();
Application.Run();
}
static void WindowClosed(object sender, FormClosedEventArgs e) {
if (Application.OpenForms.Count == 0) Application.Exit();
else Application.OpenForms[0].FormClosed += WindowClosed;
}
}
Now it is simple:
if (player.Bounds.IntersectsWith(exit.Bounds))
{
new Form2().Show();
this.Close();
}
You can use Application.OpenForms[] collection to retrieve the Opened form instance and then Show it.
Try This:
Form2 frmMyForm = (Form2)Application.OpenForms["formName"];
frmMyForm.Show();
The actual problem is not in your form being loaded multiple times, but in your game logic not being suspended when the end of the level is reached. It means that your game keeps playing an old level when a new level is already loaded.
If Form1 is the main form then your whole application will shutdown. You need bootstraper which will be the entry point of your application, not the Form1. If you do that your Form1 will be a child in the same sense as will be Form2. You can open and close them without shutting down the application. If you don't know how to do that, just create another empty form, let's call it Main and make it the starting form of your application. Then hide it and open Form1 from Main form as Modal. Then when you complete level in Form1, close Form1, the code flow will return to Main form and you'll spawn Form2 from Main form as Modal. You'll have fully predictable logic, where all forms are opened from a single controlled place.

How to set active form for all time?

Is there a way to set a form to be active all the time? No matter if I open another forms, the form which I opened sets inactive and that other sets active.
For example:
I have two forms: "Main Form" and "Reminder Form". When I start the application it loads the "Reminder Form", then the "Main Form" loads and after that "Main Form" is active, but I want, that "Reminder Form" is active, but the sequence of how forms loads needs to be the same.
If by saying "active" you mean have a focus always, it's not possible in built-in way, it should be handled by you. If you want that it's always visible (it's on top of other forms), you can use TopMost=true attribute, so it will be always over all non TopMost forms, which, by the way, is not guranteed in case of appearance of another TopMost form.
Hope this helps.
You could use
public ReminderForm()
{
InitializeComponent();
MainForm frm2 = new MainForm();
MainForm.Show();
Activate();
}
If you want your form to stay always on top of other forms, set TopMost = true;
You could register to the Deactivate event and then call Activate to make the form active again:
public ReminderForm()
{
//other stuff
Deactivate += (s, e) => { if (/* check if really do it */) Activate(); };
}
If you just want the 'Reminder Form' to be visible, setting TopMost to true is the easier way.
set the TopMost property of the form to true.
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
this.Focus();
}
set TopMost property to True

How to hold previous opened form active in C#?

I have two forms ,for example form1 and form2
the form1 is parent form ,from form1 im calling form2 and show it ,but the problem is when second form "form2" has been opened the previous form will be inactive ?
Please tell me how to have multiple form active at same time.
You probably want to use Form.Show() instead of Form.ShowDialog(). The first one will show a form along side anther one while the other will "pause" the first form until you close the 2nd one.
Use
Form.Show()
Instead of
Form.ShowDialog()
set TopMost property of form2 to true
and then use form2.Show() instead of ShowDialog()
OR
you can open form 2 in another thread like what i done
private void ShowForm2()
{
new Form2().ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(ShowForm2));
th.Start();
}
How are you showing your 2nd form? Sounds like you're showing it in a modal way - you don't want to!
Copy and paste this code into your second form class:
protected override bool ShowWithoutActivation {
get {
return true;
}
}

C#/.NET - WinForms - Instantiate a Form without showing it

I am changing the Visibility of a Form to false during the load event AND the form still shows itself. What is the right event to tie this.Visible = false; to? I'd like to instantiate the Form1 without showing it.
using System;
using System.Windows.Forms;
namespace TestClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Visible = false;
}
}
}
Regardless of how much you try to set the Visible property before the form has been shown, it will pop up. As I understand it, this is because it is the MainForm of the current ApplicationContext. One way to have the form automatically load, but not show at application startup is to alter the Main method. By default, it looks something like this (.NET 2.0 VS2005):
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
If you instead do something like this, the application will start, load your form and run, but the form will not show:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 f = new Form1();
Application.Run();
}
I am not entirely sure how this is useful, but I hope you know that ;o)
Update: it seems that you do not need to set the Visible property to false, or supply an ApplicationContext instance (that will be automatically created for you "under the hood"). Shortened the code accordingly.
I know this is an old question, but I just stumbled upon it and am pretty surprised no one has mentioned SetVisibleCore:
bool isVisibleCore = false;
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(isVisibleCore);
}
In that code snippet, as long as isVisibleCore remains false, the form will remain invisible. If it's set to false when the form is instantiated, you won't get that brief flash of visibility that you'd get if you set Visible = false in the Shown event.
It took me some time to find a properly working Solution.
Set the properties named WindowState to Minimized and ShowInTaskbar to False under properties window. Once your form is completly loaded, Call below lines of code.
this.ShowInTaskbar = true;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
//this.WindowState = System.Windows.Forms.FormWindowState.Normal;
PS: This solution is Tested on Visual C# 2008 Express Edition
How about setting the Opacity property to 0 on design and back to 100 when you want to show the form?
a solution i can live with
so the form is created and on_load is called on createtion.
set WindowState to minimize then on load set visible to false and windowstate to normal
private void Form1_Load(object sender, EventArgs e)
{
this.Visible = false;
this.WindowState = FormWindowState.Normal;
}
what did not worked:
the SetVisibleCore override solution did not created the form
as also the
Application {
Form1 f = new Form1();
Application.Run();
):
For a flicker-free Shown solution, also set the form's location off-screen during load:
private Point startuplocation;
private void Form1_Load(object sender, EventArgs e)
{
this.startuplocation = this.Location;
this.Location = new Point(-1000, -1000);
}
private void Form1_Shown(object sender, EventArgs e) //fires first time shown
{
this.Visible = false;
this.Location = this.startuplocation;
}
Just create an instance of Form1 and do not call methods to show/display it. But I bet you're doing something wrong.
Try on the VisibleChanged event.
The shown event may give you want you want. Although the form will "flash" for a second before hiding.
private void Form1_Shown(object sender, EventArgs e)
{
this.Visible = false;
}
What I would suggest would be to instantiate the form in an event the precedes the _Show event, such as the constructor, after the IntializeComponent() call.
If this is your main form, there may not be a better place then the Shown event. But in that case you will get flicker.
I couldn't find a good place to stop a running main form from showing at least quickly. Even a timer activated in the load event won't do it.
If it is a secondary form just create it but don't show it.
Have you tried
this.Hide();
in the form_load or form_activated events
Set the visibilty on the constructor, after init and then this.Show() later
InitializeComponent() is setting this.Visible = true, since you specified that the form should be visible in the designer (or it defaulted to that). You should set Visible to false in the designer, and it won't be called by InitializeComponent(). You can then make it visible any time you like.
Having .Visible = false or Hide() in the Load event will cause your form to show briefly, as there is time between when it becomes physically visible and when the Load event gets fired, in spite of the fact that the documentation says the contrary.
Are you calling Show() or ShowDialog() somewhere? I'm not sure if this behavior is still present, but at least in past versions of the framework a call to ShowDialog() did not trigger the Load event, so perhaps that is your issue (though I think calling ShowDialog() then hiding a modal form would be a bad practice!)
If you have to have the handle created (and the handles for controls) for whatever it is you're trying to do, a better idea would be to set the StartLocation to Manual, then set the Position property to an offscreen location. This will create and show the form, while making it invisible to the user.
Yeah the really one elegant way in perspective to your code than your applications visual is to flicker the form by hiding in the constructor/load event.
I set these three property settings for the form:
ShowInTaskbar = false
ShowIcon = false
WindowState = Minimized

Categories