How do I make a WinForms app go Full Screen - c#

I have a WinForms app that I am trying to make full screen (somewhat like what VS does in full screen mode).
Currently I am setting FormBorderStyle to None and WindowState to Maximized which gives me a little more space, but it doesn't cover over the taskbar if it is visible.
What do I need to do to use that space as well?
For bonus points, is there something I can do to make my MenuStrip autohide to give up that space as well?

To the base question, the following will do the trick (hiding the taskbar)
private void Form1_Load(object sender, EventArgs e)
{
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
}
But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

A tested and simple solution
I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.
Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.
I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.
The code
I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
Usage example
private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
{
FullScreen fullScreen = new FullScreen();
if (fullScreenMode == FullScreenMode.No) // FullScreenMode is an enum
{
fullScreen.EnterFullScreenMode(this);
fullScreenMode = FullScreenMode.Yes;
}
else
{
fullScreen.LeaveFullScreenMode(this);
fullScreenMode = FullScreenMode.No;
}
}
I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

And for the menustrip-question, try set
MenuStrip1.Parent = Nothing
when in fullscreen mode, it should then disapear.
And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

You can use the following code to fit your system screen and task bar is visible.
private void Form1_Load(object sender, EventArgs e)
{
// hide max,min and close button at top right of Window
this.FormBorderStyle = FormBorderStyle.None;
// fill the screen
this.Bounds = Screen.PrimaryScreen.Bounds;
}
No need to use:
this.TopMost = true;
That line interferes with alt+tab to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)

I worked on Zingd idea and made it simpler to use.
I also added the standard F11 key to toggle fullscreen mode.
Setup
Everything is now in the FullScreen class, so you don't have to declare a bunch of variables in your Form. You just instanciate a FullScreen object in your form's constructor :
FullScreen fullScreen;
public Form1()
{
InitializeComponent();
fullScreen = new FullScreen(this);
}
Please note this assumes the form is not maximized when you create the FullScreen object.
Usage
You just use one of the classe's functions to toggle the fullscreen mode :
fullScreen.Toggle();
or if you need to handle it explicitly :
fullScreen.Enter();
fullScreen.Leave();
Code
using System.Windows.Forms;
class FullScreen
{
Form TargetForm;
FormWindowState PreviousWindowState;
public FullScreen(Form targetForm)
{
TargetForm = targetForm;
TargetForm.KeyPreview = true;
TargetForm.KeyDown += TargetForm_KeyDown;
}
private void TargetForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.F11)
{
Toggle();
}
}
public void Toggle()
{
if (TargetForm.WindowState == FormWindowState.Maximized)
{
Leave();
}
else
{
Enter();
}
}
public void Enter()
{
if (TargetForm.WindowState != FormWindowState.Maximized)
{
PreviousWindowState = TargetForm.WindowState;
TargetForm.WindowState = FormWindowState.Normal;
TargetForm.FormBorderStyle = FormBorderStyle.None;
TargetForm.WindowState = FormWindowState.Maximized;
}
}
public void Leave()
{
TargetForm.FormBorderStyle = FormBorderStyle.Sizable;
TargetForm.WindowState = PreviousWindowState;
}
}

I recently made a Mediaplayer application and I used API calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had the focus or was exited.
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer
Sub HideTrayBar()
Try
Dim tWnd As Integer = 0
Dim bWnd As Integer = 0
tWnd = FindWindow("Shell_TrayWnd", vbNullString)
bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
ShowWindow(tWnd, 0)
ShowWindow(bWnd, 0)
Catch ex As Exception
'Error hiding the taskbar, do what you want here..'
End Try
End Sub
Sub ShowTraybar()
Try
Dim tWnd As Integer = 0
Dim bWnd As Integer = 0
tWnd = FindWindow("Shell_TrayWnd", vbNullString)
bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
ShowWindow(bWnd, 1)
ShowWindow(tWnd, 1)
Catch ex As Exception
'Error showing the taskbar, do what you want here..'
End Try
End Sub

You need to set your window to be topmost.

I don't know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Your_Form_Name : Form
{
public Your_Form_Name()
{
InitializeComponent();
}
// CODE STARTS HERE
private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
private bool fullscreen = false;
/// <summary>
/// Goes to fullscreen or the old state.
/// </summary>
private void UpgradeFullscreen()
{
if (!fullscreen)
{
oldsize = this.Size;
oldstate = this.WindowState;
oldstyle = this.FormBorderStyle;
oldlocation = this.Location;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
fullscreen = true;
}
else
{
this.Location = oldlocation;
this.WindowState = oldstate;
this.FormBorderStyle = oldstyle;
this.Size = oldsize;
fullscreen = false;
}
}
// CODE ENDS HERE
}
Usage:
UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.
Notice:
You MUST place it inside your Form's class (Example: partial class Form1 : Form { /* Code goes here */ } ) or it will not work because if you don't place it on any form, code this will create an exception.

On the Form Move Event add this:
private void Frm_Move (object sender, EventArgs e)
{
Top = 0; Left = 0;
Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

If you want to keep the border of the form and have it cover the task bar, use the following:
Set FormBoarderStyle to either FixedSingle or Fixed3D
Set MaximizeBox to False
Set WindowState to Maximized

Related

Windows Application That Displays Pop-Ups While Other Programs Are Running

Firstly, I have zero experience programming with .NET so this could be a pretty nooby question...
I'm wondering if it's possible to build an application like xFire - which displays pop-ups in-game to a user.
As the primary application will have focus, how does my application manage to display it's message/popup? Does the primary application have to allow access or something?
Cheers!
Looks like you are looking for NotifyIcon, it displays little pop-ups just as know from Windows.
The example is a little long, but the documentation will surely help you understand.
using System;
using System.Drawing;
using System.Windows.Forms;
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.NotifyIcon notifyIcon1;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.ComponentModel.IContainer components;
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.components = new System.ComponentModel.Container();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
// Initialize contextMenu1
this.contextMenu1.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] {this.menuItem1});
// Initialize menuItem1
this.menuItem1.Index = 0;
this.menuItem1.Text = "E&xit";
this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
// Set up how the form should be displayed.
this.ClientSize = new System.Drawing.Size(292, 266);
this.Text = "Notify Icon Example";
// Create the NotifyIcon.
this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
// The Icon property sets the icon that will appear
// in the systray for this application.
notifyIcon1.Icon = new Icon("appicon.ico");
// The ContextMenu property sets the menu that will
// appear when the systray icon is right clicked.
notifyIcon1.ContextMenu = this.contextMenu1;
// The Text property sets the text that will be displayed,
// in a tooltip, when the mouse hovers over the systray icon.
notifyIcon1.Text = "Form1 (NotifyIcon example)";
notifyIcon1.Visible = true;
// Handle the DoubleClick event to activate the form.
notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
}
protected override void Dispose( bool disposing )
{
// Clean up any components being used.
if( disposing )
if (components != null)
components.Dispose();
base.Dispose( disposing );
}
private void notifyIcon1_DoubleClick(object Sender, EventArgs e)
{
// Show the form when the user double clicks on the notify icon.
// Set the WindowState to normal if the form is minimized.
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
// Activate the form.
this.Activate();
}
private void menuItem1_Click(object Sender, EventArgs e) {
// Close the form, which closes the application.
this.Close();
}
}
See MSDN.
"As the primary application will have focus, how does my application manage to display it's message/popup? Does the primary application have to allow access or something?"
An application can set itself as "TopMost" which means it appears in front of other "normal" applications that are not TopMost. A well behaved notification will appear without stealing focus from the current application (this is usually achieved with the ShowWindow() API and the SW_SHOWNA flag). This does not require any permission from the currently active application.
Take a look at TaskbarNotifier, a skinnable MSN Messenger-like popup in C# and now in VB.NET too.

full screen mode, but don't cover the taskbar

I have a WinForms application, which is set to full screen mode when I login.
My problem is it's covering the Windows taskbar also. I don't want my application to cover the taskbar.
How can this be done?
The way I do it is via this code:
this.MaximizedBounds = Screen.FromHandle(this.Handle).WorkingArea;
this.WindowState = FormWindowState.Maximized;
This is probably what you want. It creates a 'maximized' window without hiding the taskbar.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load( object sender, EventArgs e )
{
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
Left = Top = 0;
Width = Screen.PrimaryScreen.WorkingArea.Width;
Height = Screen.PrimaryScreen.WorkingArea.Height;
}
}
I had answer it here:
One thing I left out of the description--I'd turned off the maximize button. When I tested turning that property back on, the task bar showed up again. Apparently it assumes if you don't want a maximize button you are creating a kiosk-style application where you don't want your users to see anything but the application screen. Not exactly what I'd expect, but works I guess.
I had this problem and solved it by Jeff's help. First, set the windowstate to Maximized. but Do not disable the MaximizeBox. Then if you want MaximizeBox to be disabled you should do it programmatically:
private void frmMain_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
}
Arcanox's answer is great for a single monitor, but if you try it on any screen other than the leftmost, it will just make the form disappear. I used the following code instead.
var workingArea = Screen.FromHandle(Handle).WorkingArea;
MaximizedBounds = new Rectangle(0, 0, workingArea.Width, workingArea.Height);
WindowState = FormWindowState.Maximized;
The only difference is I'm overriding the top & left values to be 0, 0 since they will be different on other screens.
If you have multiple screens, you have to reset location of MaximizedBounds :
Rectangle rect = Screen.FromHandle(this.Handle).WorkingArea;
rect.Location = new Point(0, 0);
this.MaximizedBounds = rect;
this.WindowState = FormWindowState.Maximized;
I'm not good at explaining but this is the code I used to maximize or to full screen the winforms which would not cover up the taskbar. Hope it helps. ^^
private void Form_Load(object sender, EventArgs e)
{
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
this.Location = Screen.PrimaryScreen.WorkingArea.Location;
}
If you want to use WindowState = Maximized;, you should first indicate the size limits of the form maximized by the MaximizedBounds property...
Example:
MaximizedBounds = Screen.FromHandle(this.Handle).WorkingArea;
WindowState = FormWindowState.Maximized;
Where are you limiting the size of your form to the work area that is the desktop area of ​​the display
If Maximizing isn't what you're looking for, then you'll need to calculate the window size yourself by checking for the location and size of the taskbar:
find-out-size-and-position-of-the-taskbar
Try without FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; and comment line like :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load( object sender, EventArgs e )
{
// FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
Left = Top = 0;
Width = Screen.PrimaryScreen.WorkingArea.Width;
Height = Screen.PrimaryScreen.WorkingArea.Height;
}
}
private void frmGateEntry_Load(object sender, EventArgs e)
{
// set default start position to manual
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
// set position and size to the Form.
this.Bounds = Screen.PrimaryScreen.WorkingArea;
}
This was very useful to me:
private void Form1_Load(object sender, EventArgs e)
{
this.MaximizedBounds = Screen.FromHandle(this.Handle).WorkingArea;
this.WindowState = FormWindowState.Maximized;
}
I know it's a bit too late, but it will help others too in the future.
the answered code above is working but still in my case if the taskbar is auto-hiding and showing it wont show the taskbar once it hides from the screen. I solved this problem by adding -1` to the working area height.
var workingArea = Screen.FromHandle(Handle).WorkingArea;
MaximizedBounds = new Rectangle(0, 0, workingArea.Width, workingArea.Height - 1);

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...

Single Form Hide on Startup

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.

Categories

Resources