Minimizing/Closing Application to system tray using WPF

前端 未结 2 1049
情话喂你
情话喂你 2021-02-05 19:31

I want to add application in System Tray when user minimize or close the form. I have done it for the Minimize case. Can anyone tell me that how i can keep my app running and ad

相关标签:
2条回答
  • 2021-02-05 19:58

    You need not use OnStateChanged(). Instead, use the PreviewClosed event.

    public MainWindow()
    {
        ...
        PreviewClosed += OnPreviewClosed;
    }
    
    private void OnPreviewClosed(object sender, WindowPreviewClosedEventArgs e)
    {
        m_savedState = WindowState;
        Hide();
        e.Cancel = true;
    }
    
    0 讨论(0)
  • 2021-02-05 20:05

    You can also override OnClosing to keep the app running and minimize it to the system tray when a user closes the application.

    MainWindow.xaml.cs

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        // Minimize to system tray when application is minimized.
        protected override void OnStateChanged(EventArgs e)
        {
            if (WindowState == WindowState.Minimized) this.Hide();
    
            base.OnStateChanged(e);
        }
    
        // Minimize to system tray when application is closed.
        protected override void OnClosing(CancelEventArgs e)
        {
            // setting cancel to true will cancel the close request
            // so the application is not closed
            e.Cancel = true;
    
            this.Hide();
    
            base.OnClosing(e);
        }
    }
    
    0 讨论(0)
提交回复
热议问题