Minimize form to system tray - c#

I want to hide my form while keeping my application running in background.
I've used notifyIcon and it remains always visible.
I've used "this.Hide();" to hide my form but unfortunately my application gets close (no exception).
I am also using threading and this form is on second thread.
Please tell me how can I solve it.

I am also using threading and this form is on second thread.
My crystal ball says that you've used ShowDialog() to show the form. Yes, calling Hide() on a modal dialog will close it. Necessarily so, a modal dialog normally disables all of the windows in the application. If you hide it then there's no way for the user to get back to the program, there are no windows left to activate. That this form runs on another thread otherwise doesn't factor into the behavior.
You'll need to call Application.Run(new SomeForm()) to avoid this. Now it isn't modal and you can hide it without trouble. But really, do avoid showing forms on non-UI threads. There's no reason for it, your main thread is already quite capable.

add the following event handlers for form resize and notify icon click event
private void Form_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
private void notifyIcon_Click(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
but this is not close you application

Related

How to bring the main form back to the front after the file open dialog is closed

My C# application starts by opening a form. In the constructor for that form I "showDialog" an openfiledialog. After selecting a file to open, the openfile dialog closes, the file is loaded and the contents displayed in the main form but the main form is buried behind every other open window on my desktop.
I have to find it in the task bar and bring it to focus. I just started the application, I want the form to have focus.
I have written other applications that do not use the openfiledialog and when I start them the main form opens with focus as you would expect.
How do I make the main form get focus after the openfiledialog closes?
I have tried
this.focus(),
this.activate(),
this.bringtofront();
and this.TopMost = true;
None of them make any apparent difference at all.
I have research this problem extensively and this are the things everyone suggests and say work, but they don't work for me. Some have insinuated that I am violating all that is holy by trying to make my form topmost. However, I don't think very many people would like to open an application and have the main form for it show up behind everything else.
Any one have any other ideas about how to make sure my form is "in front", topmost, has focus?
When you do it this way, your application will have a brief moment where no window is available to receive the focus after the dialog closes. Windows is forced to find another window to give the focus to, that will be a window of another app. Your main window eventually appears, now behind that other's app window.
Display the dialog in an event handler of the Shown event instead. Or use the boilerplate File + Open command.
SOLUTION: this.Activate(); works but if called from the form Load event.
This will set the window on top:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
private void Form1_Load(object sender, EventArgs e)
{
....
//after your code place the call to the function at the end.
SetForegroundWindow(this.Handle);
}
Althought as Mr. hans said and very well you are better off with another design.
If you can, move the ShowDialog out of the constructor, or try putting this in the constructor:
this.Shown += OnShown;
and move your ShowDialog to here:
private void OnShown(object sender, EventArgs eventArgs)
{
var result = new OpenFileDialog().ShowDialog();
}

How do I open my closed form through the notifyicon in the taskbar?

Currently I am developing a windows form application in c# that has several forms.
I am running a background form that operates the notifyicon property that allows the icon to appear in the taskbar.
When I launch the program, it will launch a loginForm, after which logging in it will go into a mainForm. After closing the mainForm, the application does not close yet, which in this case works like Windows Live Messenger.
How do I make my program in a way that after I the mainForm, through double clicking it will bring the form back up? (Like how MSN works.)
Or is it a better solution for me to close the whole application when I press the X button in the title bar. Which brings up another problem for me as I cant seem to exit the application when I close other forms other than the main form.
Probably you have NotifyIcon on your main form. Subscribe on the DoubleClick event of this control and change state of your main form in the handler:
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Show();
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
Just set the Visible property of the form to true/false. Or you could call Show()/Hide().

How to prevent closing of a HIDDEN form in C#

I want to prevent closing of a form in some cases. I know the usage of OnFormClosing,
but when the form is hidden (Visible==false), the OnFormClosing method is not called.
Is there a way to intercept form closing in this case?
Edit (some more details):
The form is a child in a MdiParent, should stay invisible in the background and wait for calls from another thread (by Invoke).
The MdiParent closes all child windows when the user "disconnects", in this case the above form should stay open, but invisible and still waiting for calls.
When the MidParent itself is closed, all forms should close.
Edit2 (no solution?):
It seems that there is no solution to this. My workaround now is to exclude my not-to-be-closed form in the MdiParent-code, that closes all other forms.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// This will cancel the event
e.Cancel = true;
}
Regardless of the reason, this will effectively stop a form from closing.

How to ensure a Windows Form is "fully" closed?

I have a form in a Windows form application that I want to display on top of a main form, close it, and then immediately show a dialog box using MessageBox.Show(). But the first form is still showing when the message box is shown, and it does not disappear until I click OK on the message box. I tried waiting to show the message box in an event handler for the form's VisibleChanged event and even calling Refresh() on both the form and the main form. Is there a way I can determine when the first form has fully disappeared before displaying the message box?
Edit:
Here is some code that demonstrates how the forms are being shown.
static class Program
{
// The main form is shown like this:
static void Main()
{
Application.Run(new MainForm());
}
}
public class Class1
{
// _modalForm is the first form that is displayed that won't fully go away
// when it is closed.
ModalForm _modalForm;
BackgroundWorker _worker;
public Class1()
{
_modalForm = new ModalForm();
_worker = new BackGroundWorker();
_worker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted
}
public void Method1()
{
_worker.RunWorkerAsync();
// The first form is shown.
_modalForm.ShowDialog();
}
// This code runs in the UI thread.
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_modalForm.VisibleChanged += new EventHandler(_modalForm_visibleChanged);
_modalForm.Close();
}
void _modalForm_visibleChanged(object sender, EventArgs e)
{
// When the message box is shown, the other form is still visible
// and remains so until I click OK.
MessageBox.Show("The other form was just closed.");
// Note: I originally tried to use the FormClosed event instead of
// VisibleChanged. Then I tried Deactivate, in attempt to use an event
// that occurred later thinking that might do the trick. VisibleChanged
// is the latest event that I found.
//
}
I'll guess that you are running your code on Windows XP or Vista/Win7 with Aero turned off. Closing a form does not make the pixels on the screen disappear instantly. The Windows window manager sees that the window for the form got destroyed and that this revealed parts of other windows underneath it. It will deliver a WM_PAINT message to let them know that they need to repaint the parts of the window that got revealed.
This will not work properly if one or more of those windows isn't actively pumping a message loop. They can't see the WM_PAINT message. They won't repaint themselves, the pixels of the closed form will remain on the screen.
Find out why these windows are not responding. Hopefully it is your window and the debugger can show you what the UI thread is doing. Make sure it isn't blocking on something or stuck in a loop.
After seeing the edit: there's indeed blocking going on, of a different kind. The MessageBox.Show() call is modal, it prevents the VisibleChanged event from completing. That delays the closing of the form.
Use System.Diagnostics.Debug.WriteLine() or Console.WriteLine() to get diagnostics in a Window Forms app. You'll see it in the Output window. Or simply use a debugger breakpoint.
The Form.FormClosed event is raised when the form completes closing. At this point, all Form.FormClosing event handlers have been run, and none of them canceled the close.
Form.FormClosed replaced Form.Closed (which is deprecated) in the .NET 2.0 framework.
Form.Closed Event
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.closed(VS.71).aspx

Application window sent behind other windows on closing different thread (C#)

I'm writing a Windows Forms Application in C#.NET
On startup, the application displays a splash screen which is running in a separate thread. Whilst the splash screen is showing, the main application is initialising.
Once the main application has finished initialising, the main form of the application is displayed, and the splash screen still shows over the top.
Everything so far is as expected.
Then, the Splash screen is closed, which causes that thread to exit. For some reason, at the point, the main application windows gets sent behind all other open Windows, notably the Windows Explorer window where you clicked the .exe file to run the application in the first place!
What could be causing the windows to suddenly jump "behind" like this?
Try calling .Activate() on your main window when your thread closes.
It's never been active, and thus has low Z-Order, so whatever is higher will naturally be above it. I had to fix this exact scenario in our app.
Don't forget! You may need to marshal the call to the correct thread using an Invoke()!
I've had this happen at times too. Bob's response is the easiest and works for me in the majority of cases. However, there have been some times where I need to use brute force. Do this via interop like this:
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
Is the splash screen a Modal dialog?
I have seen this window 'jumping' if you dismiss a Modal dialog twice by setting both DialogResult and calling Hide() or close().
Code like this:
private void button1_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.Abort;
this.Hide();
}
See this blog entry for all of the cases...
You can use code like this :
private void button1_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.Abort;
this.Hide();
}
Thanks all!

Categories