Hide Windows form from everywhere (taskbar, task switcher, etc) - c#

I have Windows Application form I need to hide Form on form_Load event and it should be hidden from task bar and also from task switcher (i.e. when I press Alt + Tab). means it would not be showing anywhere .

So you should try this:
public void Form1_Load(object sender, EventArgs e)
{
ShowInTaskbar = false;
Hide();
}
ShowInTaskbar indicates wether your Form should appear in the task bar.
To hide it from Alt+Tab I found this solution on StackOverflow:
protected override CreateParams CreateParams
{
get
{
var Params = base.CreateParams;
Params.ExStyle |= 0x80;
return Params;
}
}
Simply overwrite the CreateParams property of your Form as shown above.
UPDATE The order of events when opening a Form leads to the problem that your visibility is restored after the Load event. So you will need to overwrite something like this:
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
// if you still want to hide
Hide();
}

Related

Windowless tray icon application

OK I am a total newbie at WPF but I have to develop what's in the title with wpf but not relying on MVVM.
I have followed this:
WPF Application that only has a tray icon
I found the first answer the one with the hardcodet lib but find it too difficult and MVVM biased.
So followed the second one and everything seemed fine except that in the end it doesn't work.
So in my App.xaml.cs I have put:
public partial class App : Application
{
private System.Windows.Forms.NotifyIcon notifyIcon = null;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
UnityCore.Initialize();
}
protected override void OnActivated(EventArgs e)
{
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += NotifyIcon_Click;
notifyIcon.DoubleClick += NotifyIcon_DoubleClick;
Stream iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/Images/ITA.png")).Stream;
notifyIcon.Icon = new System.Drawing.Icon(iconStream);
notifyIcon.Visible = true;
base.OnActivated(e);
}
private void NotifyIcon_DoubleClick(object sender, EventArgs e)
{
Console.Beep();//show main window
}
private void NotifyIcon_Click(object sender, EventArgs e)
{
Console.Beep();//show main window
}
}
The main window at start is transparent of minimized to make it invisible.
At this stage I hoped to see the ITA flag in the tray icon and then at click or double click restore the main window.
But I don't see a damn thing in the tray.
I think that the flag resource is properly set here's my solution
Thanx for any help.

Executing code when my form is closed

My program makes some changes in the registry while it's running, and if they are not properly rolled back, they might cause the user some problems. FOr example, they might not be able to use their Internet connection.
So I need to make sure that when they close the application, I return everything back to normal. To do this, I need to know when they have pressed the Close button of the form. How can I do that? Is there an event that I can handle?
There is an event you can subscribe to called FormClosing this fire before FormClose and allows you to validate/change the settings you need before the form closes
public Form1()
{
InitializeComponent();
FormClosing += Form1_FormClosing;
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Reset values
}
I think that what you need is not access to the close button, but rather access to the event which is fired when the form is closed.
Taken from this previous SO post, what you might need is something like so:
void FormClosed(object sender, FormClosedEventArgs e)
{
// do something useful
}
There are more possibilites here.
1) Use the FormClosing event of the form:
private void form_FormClosing(object sender, FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) { // User clicked 'X' button
if (someThing) e.Cancel = true; // Disable Form closing
}
}
2) You can also hide the 'X' button by set ControlBoxto false. But this will also hide the minimize and maximize buttons.
3) This disables only the 'X' button. Place it in your form.
private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams {
get {
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
CreateParams cp = base.CreateParams;
cp.ClassStyle |= CP_NOCLOSE_BUTTON;
return cp;
}
}

Minimized application showing above the task bar

I have an application that I do not want to show in the taskbar. When the application is minimized it minimizes to the SysTray.
The problem is, when I set ShowInTaskbar = false the minimized application shows above the task bar, just aboe the Windows 7 start button. If I set ShowInTaskbar = true the application minimizes correctly, but obviously the application shows in the taskbar.
Any idea why this is happening and how I can fix it?
EDIT: For the sake of clarity, here is the code I'm using:
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized) {                                                                                    
this.Hide();
this.Visible = false;
notifyIcon1.Visible = true;
     }
else
{
notifyIcon1.Visible = false;
}
}
private void btnDisable_Click(object sender, EventArgs e)
{
// Minimize to the tray
notifyIcon1.Visible = true;
WindowState = FormWindowState.Minimized; // Minimize the form
}
There is no event handler to establish when a form's minimise request has been fired. So to 'get in' before the form has been minimised you'll have to hook into the WndProc procedure
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MINIMIZE = 0xF020;
[SecurityPermission(SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_SYSCOMMAND:
int command = m.WParam.ToInt32() & 0xfff0;
if (command == SC_MINIMIZE && this.minimizeToTray)
{
PerformYourOwnOperation(); // For example
}
break;
}
base.WndProc(ref m);
}
and then you can merely hide the form in the PerformYourOwnOperation(); method
public void PerformYourOwnOperation()
{
Form form = GetActiveForm();
form.Hide();
}
You will then need some mechanism to Show() the hidden form otherwise it will be lost.
Another way is using the the form's resize event. However, this fires after the form is minimised. To do this you can do something like
private void Form_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
// Do some stuff.
}
}
I hope this helps.
My guess is that you also have to hide the window. To get this behavior in WPF, I have to do the following:
WindowState = WindowState.Minimized;
Visibility = Visibility.Hidden;
ShowInTaskbar = false;
Since WPF and WinForms both ultimately come down to Win32 windows, you probably have to do the same thing.
Here is one of the simplest solutions (I think so):
//Deactivate event handler for your form.
private void Form1_Deactivate(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized) Hide();
}
You can use a NotifyIcon to get the program to show up in the system tray, and watch for the window's resize event to toggle the visibility to hidden.
Here is how to watch for the window's resize event.
How to detect when a windows form is being minimized?
Here is a tutorial for using the NotifyIcon provided by CodeProject. The NotifyIcon is a windows forms element so it will still work in your application.
http://www.codeproject.com/Articles/36468/WPF-NotifyIcon
Add handler for resizing:
private void Form1_Resize(object sender, EventArgs e)
{
Visible = WindowState != FormWindowState.Minimized;
}

Disabling the exit button on a windows form?

Is there a way to disable the exit button on a windows form without having to import the some external .dll's? I disable the exit button by importing dll's using the following code but I don't like it. Is there a simpler (built-in) way?
public Form1()
{
InitializeComponent();
hMenu = GetSystemMenu(this.Handle, false);
}
private const uint SC_CLOSE = 0xf060;
private const uint MF_GRAYED = 0x01;
private IntPtr hMenu;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern int EnableMenuItem(IntPtr hMenu, uint wIDEnableItem, uint wEnable);
// handle the form's Paint and Resize events
private void Form1_Paint(object sender, PaintEventArgs e)
{
EnableMenuItem(hMenu, SC_CLOSE, MF_GRAYED);
}
private void Form1_Resize(object sender, EventArgs e)
{
EnableMenuItem(hMenu, SC_CLOSE, MF_GRAYED);
}
You can't easily disable the exit button (the one in the top right that closes the form).
You can, however, hide the button completely, by setting the ControlBox property to false.
ControlBox can be turned on and off at any time, so you can use this if you want to dynamically allow closing at some times, and not at others.
Alternatively, you can handle the FormClosing event and cancel the close if you choose.
Here's a demo.
Create a new Windows Forms project.
Drop a CheckBox control on the form, with Text "ControlBox". Hook up its Click event to this:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
ControlBox = checkBox1.Checked;
}
Then, drop a second CheckBox control on the form with Text "Cancel Close". Hook up the FormClosing event of the form to this:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = checkBox2.Checked;
}
Run the application and start playing around with the checkboxes. You'll soon see how things work.
To disable the close button on the form just write the below code on the form closing event.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
A little poking around found this handy helper class:
Disable Close Button and Prevent Form Being Moved (C# version)
It actually does more than what you're looking for, but essentially does it very nearly the same way you do in your sample code. The helper class hooks into the load/resize events for you so you don't have to remember to do it yourself.
Yes.
Setting the form.ControlBox = false will hide the close button. Although, it will also hide the minimize and maximize button.
You can also set form.FormBorderStyle = FormBorderStyle.None, which will hide the whole title bar.
If you want to show the X button but just stop the form from closing, override OnClosing and set the e.Cancel property to true.
Catch the FormClosing event and cancel it in the arguments.
Using visual studio select the form go to the properties and set the ControlBox property to false or try this.ControlBox = false; or frmMainForm.ControlBox = false;
Disabling the button is possible without importing dlls. ControlBox = false causes minimise and maximise buttons and the border to disappear as well and it does not disable the close 'X' button - it hides. This solution disables it:
private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
{
get
{
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON ;
return myCp;
}
}
Source: https://www.codeproject.com/kb/cs/disableclose.aspx

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