Single Form Hide on Startup - c#

I have an application with one form in it, and on the Load method I need to hide the form.
The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.
Any suggestions?

I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
Application.Run(new MainForm());
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show() or Form.Hide() from handlers of NotifyIcon events will show and hide the form respectively.

Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.
Create a bool in your Form class that is defaulted to false:
private bool allowshowdisplay = false;
Then override the SetVisibleCore method
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);
}
Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.
Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
this.allowshowdisplay = true;
this.Visible = !this.Visible;
}
}

I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.

protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
Opacity = 0;
base.OnLoad(e);
}

At form construction time (Designer, program Main, or Form constructor, depending on your goals),
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
When you need to show the form, presumably on event from your NotifyIcon, reverse as necessary,
if (!this.ShowInTaskbar)
this.ShowInTaskbar = true;
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
Successive show/hide events can more simply use the Form's Visible property or Show/Hide methods.

Try to hide the app from the task bar as well.
To do that please use this code.
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
Opacity = 0;
base.OnLoad(e);
}
Thanks.
Ruhul

Extend your main form with this one:
using System.Windows.Forms;
namespace HideWindows
{
public class HideForm : Form
{
public HideForm()
{
Opacity = 0;
ShowInTaskbar = false;
}
public new void Show()
{
Opacity = 100;
ShowInTaskbar = true;
Show(this);
}
}
}
For example:
namespace HideWindows
{
public partial class Form1 : HideForm
{
public Form1()
{
InitializeComponent();
}
}
}
More info in this article (spanish):
http://codelogik.net/2008/12/30/primer-form-oculto/

I have struggled with this issue a lot and the solution is much simpler than i though.
I first tried all the suggestions here but then i was not satisfied with the result and investigated it a little more.
I found that if I add the:
this.visible=false;
/* to the InitializeComponent() code just before the */
this.Load += new System.EventHandler(this.DebugOnOff_Load);
It is working just fine.
but I wanted a more simple solution and it turn out that if you add the:
this.visible=false;
/* to the start of the load event, you get a
simple perfect working solution :) */
private void
DebugOnOff_Load(object sender, EventArgs e)
{
this.Visible = false;
}

You're going to want to set the window state to minimized, and show in taskbar to false. Then at the end of your forms Load set window state to maximized and show in taskbar to true
public frmMain()
{
Program.MainForm = this;
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void frmMain_Load(object sender, EventArgs e)
{
//Do heavy things here
//At the end do this
this.WindowState = FormWindowState.Maximized;
this.ShowInTaskbar = true;
}

Put this in your Program.cs:
FormName FormName = new FormName ();
FormName.ShowInTaskbar = false;
FormName.Opacity = 0;
FormName.Show();
FormName.Hide();
Use this when you want to display the form:
var principalForm = Application.OpenForms.OfType<FormName>().Single();
principalForm.ShowInTaskbar = true;
principalForm.Opacity = 100;
principalForm.Show();

This works perfectly for me:
[STAThread]
static void Main()
{
try
{
frmBase frm = new frmBase();
Application.Run();
}
When I launch the project, everything was hidden including in the taskbar unless I need to show it..

Override OnVisibleChanged in Form
protected override void OnVisibleChanged(EventArgs e)
{
this.Visible = false;
base.OnVisibleChanged(e);
}
You can add trigger if you may need to show it at some point
public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
{
this.hideForm = hideForm;
InitializeComponent();
}
...
protected override void OnVisibleChanged(EventArgs e)
{
if (this.hideForm)
this.Visible = false;
base.OnVisibleChanged(e);
}
...
}

Launching an app without a form means you're going to have to manage the application startup/shutdown yourself.
Starting the form off invisible is a better option.

This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.
More here: http://code.msdn.microsoft.com/TheNotifyIconExample

As a complement to Groky's response (which is actually the best response by far in my perspective) we could also mention the ApplicationContext class, which allows also (as it's shown in the article's sample) the ability to open two (or even more) Forms on application startup, and control the application lifetime with all of them.

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainUIForm mainUiForm = new MainUIForm();
mainUiForm.Visible = false;
Application.Run();
}

I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).
The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event.
Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
form1.Visible = false;
Application.Run();
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}

Here is a simple approach:
It's in C# (I don't have VB compiler at the moment)
public Form1()
{
InitializeComponent();
Hide(); // Also Visible = false can be used
}
private void Form1_Load(object sender, EventArgs e)
{
Thread.Sleep(10000);
Show(); // Or visible = true;
}

In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it.
A better paradigm is to not create an instance of the form until you need it.

Based on various suggestions, all I had to do was this:
To hide the form:
Me.Opacity = 0
Me.ShowInTaskbar = false
To show the form:
Me.Opacity = 100
Me.ShowInTaskbar = true

Why do it like that at all?
Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.
No need in being greedy and taking the memory needed for the form when you may not even need it.

I do it like this - from my point of view the easiest way:
set the form's 'StartPosition' to 'Manual', and add this to the form's designer:
Private Sub InitializeComponent()
.
.
.
Me.Location=New Point(-2000,-2000)
.
.
.
End Sub
Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.

Related

c# mainui drops behind other windows, issue with topmost

I have a problem with topmost level, found a solution that "works" but it don't look so nice. Is there another "cleaner" way to solve this?
Here's my code: comments of event in code.
OrderTemplateView template;
private void toolStripButton4_Click(object sender, EventArgs e)
{
if (template != null)
{
template.Close(); //must close to trigger close event.
template.Dispose();
}
mainUi.TopMost = true; // must set my mainUi topMost here othervise it drops in the background of other windows open at the computer.
template = new OrderTemplateView(this);
template.TopMost = true;// must set my dialog topmost othervise it drops behind my mainUi
template.StartPosition = FormStartPosition.CenterParent;
mainUi.TopMost = false;//must release my topmost so other windows on the computer can be called to front.
template.TopMost = false;
template.ShowDialog();
}
Updated code that does the same job:
private void toolStripButton4_Click(object sender, EventArgs e)
{
if (template != null)
{
template.Close();
template.Dispose();
}
template = new OrderTemplateView(mainUi);
template.StartPosition = FormStartPosition.CenterParent;
template.ShowDialog(mainUi);
}
`
Rather than setting TopMost, try the following:
Remove all your references to TopMost
Call mainUi.BringToFront()
Call template.ShowDialog(mainUi), noting that the parent control is passed to the dialog.

Show MessageBox immediately in Windows Forms?

Is there any way to have a messagebox immediately pop up when a form opens? I just want to display a short message about how to use the form when it opens. I tried
private void myForm_Load(object sender, EventArgs e)
{
DialogResult dialogOpen = MessageBox.Show("Use the navigation menu to get started.", "Welcome!", MessageBoxButtons.OK);
}
but it doesn't work.
Showing a MessageBox during Form_Load works just fine for me. I literally copy/pasted the code from your original post, and it worked. I'm on .NET Framework 4.5 on Windows 8.1.
Are you sure your Load event handler is getting called? Perhaps the it's not hooked up to the Load event properly.
I don't see why it wouldn't work in Form_Load. Definitely try doing as others have pointed out by putting it beneath form initialization.
Though, given that you're just showing a message box, I don't think there is any reason to store the result, so a simple MessageBox.Show(message); Should do the trick.
As #s.m. said, from a UX point of view, having a notification thrown in your face as soon as the app starts would be very obnoxious, at least if you have it EVERY time. Personally, I would create a boolean Settings variable, set it to true the first time the message is displayed, and only display it when the setting is false, i.e. the first time the message is displayed.
private boolean splashShown = Properties.Settings.Default.splashShown;
private void Form_Load(object sender, EventArgs e)
{
if (!splashShown)
{
MessageBox.Show("message");
myForm.Properties.Settings.Default.splashShown = true;
myForm.Properties.Settings.Default.Save();
}
}
And set up the splashShown Setting in your form properties.
If the problem is that your Form_Load() method isn't actually attached to your Form.Load() event, you can double click the form window in the designer and it will automatically created the Form_Load() base method for you and attach it to the Form.Load() event
Is there a reason to use the Load method of the form? If not you could to it in the constructor of form. If you want it to show up immediately after your form loads, you should do it in the constructor after the form is initialized. It should look something like this:
public partial class myForm : Form
{
public myForm()
{
InitializeComponent();
DialogResult dialogOpen = MessageBox.Show("Use the navigation menu to get started.", "Welcome!", MessageBoxButtons.OK);
}
}
The constructor (public myForm()) and the InitializeComponent(); should be automatically added to the form by Visual Studio after creating it.
Form_Load event occurs before the form is really visible.
I use:
static private bool splashShown = false;
private void Form1_Activated(object sender, System.EventArgs e)
{
if (!splashShown)
{
MessageBox.Show("message");
splashShown = true;
}
}
I have used this and it works fine. App start brings up messagebox first before all else.
InitializeComponent();
MessageBox.Show("put your message here");

C#: showing an invisible form

I have the following code in C#:
Form f = new MyForm();
f.Visible = false;
f.Show();
f.Close();
Despite the f.Visible = false, I am seeing a flash of the form appearing and then disappearing. What do I need to do to make this form invisible?
I need to show the form (invisibly) during the splash of my app because doing this removes a cold start delay when showing this form.
If you want to show the form without actually seeing it, you can do this:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.ShowInTaskbar = false;
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(0, 0);
}
If at a later point you want to show it, you can just change everything back. Here is an example after 10 seconds, it shows the form:
Timer tmr = new Timer();
public Form1()
{
tmr.Interval = 10000;
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Start();
InitializeComponent();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.ShowInTaskbar = false;
this.Load += new EventHandler(Form1_Load);
}
void tmr_Tick(object sender, EventArgs e)
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.ShowInTaskbar = true;
this.Size = new Size(300, 300);
}
void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(0, 0);
}
By far the simplest way to keep a form invisible is just by not showing it. It is a big deal in Winforms, calling Show() or setting the Visible property to true (same thing) does a lot of things. It is the way the native Windows window gets created. In typical .NET 'lazy' fashion. Any attempt to set Visible back to false (like in OnLoad) will be defeated.
Technically it is possible, you have to override the SetVisibleCore() method. Like this:
protected override void SetVisibleCore(bool value) {
if (!this.IsHandleCreated) {
this.CreateHandle();
value = false; // Prevent window from becoming visible
}
base.SetVisibleCore(value);
}
This ensures that the window doesn't become visible the first time you call Show(). Which is handy when you have NotifyIcon for example, you typically want the icon directly in the notification area and only display a window when the user clicks on the icon. Beware that OnLoad() doesn't run until the window actually becomes visible so move code to the constructor or the override if necessary.
Simply Because f.Show() is making the form Visible again and f.Close() is Closing it... so the flash.
If you see the MSDN doc for Form.Show() method it clearly mentions that:
Showing the control is equivalent to setting the Visible property to true. After the Show method is called, the Visible property returns a value of true until the Hide method is called.
If you don't want the flash just don't show the Form at all.
You need to edit the MyForm class, and add the following override method:
protected override void SetVisibleCore(bool value)
{
//just override here, make sure that the form will never become visible
if (!IsHandleCreated) CreateHandle();
value = false;
base.SetVisibleCore(value);
}
You should ask yourself if this is really necessary however - probably indicative of poor design really.
Edit:
It's pretty rare that you need to do this, the only situation I've used it is when I needed a form I could place a COM component on (since the COM component needed a Window handle), and I had to run Application.Run(formInstance) which calls the Show method of the form. By forcing the form to always be invisible, you get a window handle and a message loop without seeing anything on screen.
I've created helper method that will to show invisible form and subsequent Show calls will show window as usually:
public static class FormHelper
{
public static void ShowInvisible(this Form form)
{
// saving original settings
bool needToShowInTaskbar = form.ShowInTaskbar;
WindowState initialWindowState = form.WindowState;
// making form invisible
form.ShowInTaskbar = false;
form.WindowState = FormWindowState.Minimized;
// showing and hiding form
form.Show();
form.Hide();
// restoring original settings
form.ShowInTaskbar = needToShowInTaskbar;
form.WindowState = initialWindowState;
}
}
So form will be rendered (and Load event will trigger) without any blink.

How to start WinForm app minimized to tray?

I've successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs when trying to start with the app minimized. At first the problem was that the app would be minimized but would still appear in the alt-tab dialog. Changing the FormBorderStyle to one of the ToolWindow options (from the "None" option) fixed this, but introduced another problem. When the app first starts the titlebar of the minimized window is visible just above the start menu:
Opening the form and the closing it causes it to hide properly. I've tried lots of variations, but here's essentially how it's working right now...
WindowState is set to Minimized in the Designer. After some initialization in the constructor I have the following lines:
this.Visible = false;
this.ShowInTaskbar = false;
When the NotifyIcon is double-clicked I have the following:
this.WindowState = FormWindowState.Normal;
this.Visible = true;
this.ShowInTaskbar = true;
Like I said, I've tried lots of minor variations on this (this.Hide(), etc.). Is there a way to have the NotifyIcon be the primary component such that I can completely start and dispose of the form while leaving the NotifyIcon running? There's got to be a way to start the app with the form minimized without any of the weirdness. Please help me find it!
The right way to do this is to prevent the form from getting visible in the first place. That requires overriding SetVisibleCore(). Let's assume a context menu for the NotifyIcon with a Show and Exit command. You can implement it like this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
notifyIcon1.ContextMenuStrip = contextMenuStrip1;
this.showToolStripMenuItem.Click += showToolStripMenuItem_Click;
this.exitToolStripMenuItem.Click += exitToolStripMenuItem_Click;
}
private bool allowVisible; // ContextMenu's Show command used
private bool allowClose; // ContextMenu's Exit command used
protected override void SetVisibleCore(bool value) {
if (!allowVisible) {
value = false;
if (!this.IsHandleCreated) CreateHandle();
}
base.SetVisibleCore(value);
}
protected override void OnFormClosing(FormClosingEventArgs e) {
if (!allowClose) {
this.Hide();
e.Cancel = true;
}
base.OnFormClosing(e);
}
private void showToolStripMenuItem_Click(object sender, EventArgs e) {
allowVisible = true;
Show();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
allowClose = true;
Application.Exit();
}
}
Note a wrinkle with the Load event, it won't fire until the main form is first shown. So be sure to do initialization in the form's constructor, not the Load event handler.
I'm reading all the answers and see hacks and black magic... (no offense, mates)
No hacks needed. You don't even have to set "ShowInTaskbar=false" and other stuff. Just do this:
//"Form Shown" event handler
private void Form_Shown(object sender, EventArgs e)
{
//to minimize window
this.WindowState = FormWindowState.Minimized;
//to hide from taskbar
this.Hide();
}
NOTE: I strongly recommend NOT TOUCHING the "ShowInTaskbar" property. For example, if your application registers system-wide hotkeys or other similar stuff (hooks, etc) - setting ShowInTaskBar=false and minimizing your app will prevent Windows from sending some messages to your window... And your hooks/hotkeys/etc will stop working.
In the constructor, remove these two lines:
this.Visible = false;
this.ShowInTaskbar = false;
and add after InitializeComponent();:
this.WindowState = FormWindowState.Minimized;
In designer, set ShowInTaskbar to false & FormWindowState to Normal.
EDIT:
If you post the same in Load event, the window does get minimized but still shows minimized on the desktop. I think this is a bug.
When minimizing an application and you want to hide it from Alt+Tab:
You also need to set the Opacity to stop the titlebar showing near the Start Menu when you set the Border Style to a Tool Window.
On Minimize Event:
this.Visible = false;
this.Opacity = 0;
this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
this.ShowInTaskbar = false;
On Normalize Event:
this.Visible = true;
this.Opacity = 100;
this.FormBorderStyle = FormBorderStyle.FixedSingle; //or whatever it was previously set to
this.ShowInTaskbar = true;
Move the following code from the Form's constructor to Form_Main_Load(). With the same setup on Notification_Icon when Form_Resize().
// Hide the Form to System Tray
this.WindowState = FormWindowState.Minimized;
This "quick and dirty fix" worked for me:
$form1.FormBorderStyle = "fixedtoolwindow"
$form1.top = -1000000
$form1.Left = -1000000
$form1.Width = 10
$form1.Height = 10
$form1.WindowState = "normal"
$form1.ShowInTaskbar = $False
$form1.Opacity = 0
$form1.Hide()
Hope it helps someone else...

C# New form never gains focus

I have been trying to write a small app with its own option windows. When I try to launch the window I can never seem to set focus on the new form. This is not a mdi form, but merely a new form that I create when a user selects an option from the menu. It should be noted that Form.Show is return false, which means that the new form is never receiving focus.
I have tried multiple methods for loading the form and all have failed:
From Calling Form:
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show();
SF.Focus();
// Fails
Inside the form itself:
this.Show();
this.BringToFront();
this.Activate();
this.TopMost = true;
// Fails
Setting Form to selectable:
this.SetStyle(System.Windows.Forms.ControlStyles.Selectable, true);
...
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show();
SF.Focus();
// Fails
Using Old API:
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr handle, int nCmdShow);
ServerForm SF = new ServerForm(ref DataLoader, false);
ShowWindow(SF.Handle, 3);
SF.Show();
SF.Focus();
// Fails
Passing in Parent
ServerForm SF = new ServerForm(ref DataLoader, false);
SF.Show(this);
SF.Focus();
// Fails
In all of these cases the form will show up, but the form that spawned still will have focus over the new form. This happens even when I disable the old form before I create the new form.
Any suggestions?
It's because Form.canFocus() is false when the form loads. Use Form.Activate() on Form.Shown event. That's all.
private void ServerForm_Shown(object sender, EventArgs e)
{
this.Activate();
}
I solved with this (thanks to #Joel Coehoorn):
form.WindowState = FormWindowState.Minimized;
form.Shown += delegate(Object sender, EventArgs e) {
((Form)sender).WindowState = FormWindowState.Normal;
};
form.ShowDialog();
Set TopMost form property to true. Then
in program.cs:
var formLogin = new frmLogin();
formLogin.ShowDialog();
if (formLogin.DialogResult == DialogResult.Yes)
{
Application.Run(new frmMain());
}
in formLogin:
[DllImport("user32")]
public static extern int SetForegroundWindow(IntPtr hwnd);
...
private void frmLogin_Shown(object sender, EventArgs e)
{
SetForegroundWindow(this.Handle);
}
private void frmLogin_Deactivate(object sender, EventArgs e)
{
TopMost = false;
}
Remember that there is only a single user interface thread allowed in a winforms app.
Are you manipulating anything on the parent form after your call to Form.Show()? This
may cause the parent form to be focused again.
Remove everything you have used to try to focus, activate the form and rely just on the call to Form.Show(). This should be enough to load the form, and focus upon it. If anything, in your menu item handler. Comment out everything after your call to Show() and see if that works. Work backwards to see what caused your parent form to be refocused.
This seems to work. First I create the new form:
private void changeDefaultServerToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Enabled = false;
ServerForm SF = new ServerForm(ref DataLoader, true);
}
Then in the constructor for the new form I do the following:
this.BringToFront();
this.CenterToParent();
this.TopMost = true;
this.ShowDialog();
Apparently there is some sort of behind the scene difference between Form.Show and Form.ShowDialog. Not quites sure what it is, I can only think it has to do with setting the active parent somehow. Adding code after the call to construct the function does not seem to give back focus to the parent form. Which it shouldn't.
Have you tried setting the correct parent window in Form.Show()?
E.g.:
using(ServerForm SF = new ServerForm(ref DataLoader, false)) // if ServerForm is IDisposable
{
SF.Show(this);
}
Edit:
There's something going on that isn't in your question. Is your owning window a TopMost window?
Try to call ShowDialog(this). It helped in my case when I faced the same problem.

Categories

Resources