Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Toggle between minimize to tray or taskbar (but not both)

Status
Not open for further replies.

GEAK

Instructor
Feb 1, 2001
90
US
I have a form with a fixed dialog border; it can either be on-screen normally or minimized. I want to allow the user to (optionally) minimize it to the tray. To that end I have a context menu with a menu item "Minimize to tray" which toggles its check mark when you click it.

[pre]private bool m_MinimizeToTray;

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
minimizeToTrayToolStripMenuItem.Checked = m_MinimizeToTray;
}

private void minimizeToTrayToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MinimizeToTray = !m_MinimizeToTray;
}[/pre]

Then in the form's Resize event handler I tackle minimizing to the tray (based upon the state of the Boolean) and restoring (and simultaneously hiding the tray icon):

[pre]
private void Form1_Resize(object sender, EventArgs e)
{
if(WindowState == FormWindowState.Minimized && m_MinimizeToTray)
{
m_NotifyIcon.Visible = true;
Hide();
}
else
{
m_NotifyIcon.Visible = false;
Show();
}
}[/pre]
Finally, I wanted to restore to normal size when the user left-clicks the tray icon:
[pre]private void m_NotifyIcon_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
WindowState = FormWindowState.Normal;
Show();
}
}[/pre]

It almost works, but only almost. You have to click the tray icon twice to restore the window. The first click restores the icon in the task bar, the second click restores the app. To make matters worse, if you single click the tray icon and then click the task bar icon, it gets into a state where you can't ever restore the window. Any ideas how to get this to work properly (so that a single click on the tray icon will restore the window)?
 
I figured it out. Apparently I needed to call Show() before setting the WindowState to Normal. The following works:

[pre]private void m_NotifyIcon_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Show();
WindowState = FormWindowState.Normal;
}
}[/pre]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top