C # winform-hide to system tray when minimized or disabled

Source: Internet
Author: User

Step 1. Add the tray icon control policyicon (you can drag it from the toolbox to add it)

Step 2. Add (override) the window size change function form1_resize

Private void form1_resize (Object sender, eventargs E)
{
If (this. windowstate = formwindowstate. Minimized) // minimize to System Tray
{
Policyicon1.visible = true; // display the tray icon
This. Hide (); // hide the window
}
}

 

Step 3. Add (overwrite) window close events

Private void form=formclosing (Object sender, formclosingeventargs E)
{
// Determine whether to close the event reason from the form button. Otherwise, the event cannot be exited when you exit with the menu!
If (E. closereason = closereason. userclosing)
{
E. Cancel = true; // cancel the "Close Window" event.
This. windowstate = formwindowstate. minimized; // indicates the effect of narrowing down the window to the lower right corner when the window is closed.
Policyicon1.visible = true;
This. Hide ();
Return;
}
}

Step 4. Add a double-click Tray Icon event (double-click the display window)

private void NotifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
NotifyIcon1.Visible = false;
this.Show();
WindowState = FormWindowState.Normal;
this.Focus();
}

Step 5. Right-click the tray icon

(Code omitted)
"Exit" menu: This. Close ();
"Display window" menu: see Step 4

 

PS: When you set "hide to system tray when off", you cannot exit by clicking the "exit" menu. -- Neither this. Close (); nor application. Exit (); can exit! -- The solution is to determine the reason for closing the window event/source (E. closereason), if it is closereason. userclosing clicks the close button in the upper-right corner of the window. Otherwise, the program hidden in the tray is not executed if you click the "exit" menu. (For details, see the if judgment in step 3)

 

Reprinted: http://hi.baidu.com/%B9% AB %D7%D3%D1%B8/blog/item/485c090d2b4931d43bc76392.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.