2014-12-03 57 views
8

我想在用戶最小化或關閉表單時在系統托盤中添加應用程序。我爲Minimize案做了這件事。任何人都可以告訴我,當我關閉表單時,如何保持我的應用程序運行並將其添加到系統托盤中?使用WPF最小化/關閉應用程序到系統托盤

public MainWindow() 
    { 
     InitializeComponent(); 
     System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon(); 
     ni.Icon = new System.Drawing.Icon(Helper.GetImagePath("appIcon.ico")); 
     ni.Visible = true; 
     ni.DoubleClick += 
      delegate(object sender, EventArgs args) 
      { 
       this.Show(); 
       this.WindowState = System.Windows.WindowState.Normal; 
      }; 
     SetTheme(); 
    } 

    protected override void OnStateChanged(EventArgs e) 
    { 
     if (WindowState == System.Windows.WindowState.Minimized) 
      this.Hide(); 
     base.OnStateChanged(e); 
    } 
+1

我建議您:https://visualstudiogallery.msdn.microsoft.com/aacbc77c-4ef6-456f-80b7-1f157c2909f7/ – Xaruth 2014-12-03 11:08:50

回答

1

您不需要使用OnStateChanged()。而是使用PreviewClosed事件。

public MainWindow() 
{ 
    ... 
    PreviewClosed += OnPreviewClosed; 
} 

private void OnPreviewClosed(object sender, WindowPreviewClosedEventArgs e) 
{ 
    m_savedState = WindowState; 
    Hide(); 
    e.Cancel = true; 
} 
4

您還可以覆蓋OnClosing保持應用程序的運行,並在用戶關閉應用程序最小化到系統托盤。

MainWindow.xaml.cs

public partial class MainWindow : Window 
{ 
    public MainWindow(App application) 
    { 
     InitializeComponent(); 
    } 

    // minimize to system tray when applicaiton is minimized 
    protected override void OnStateChanged(EventArgs e) 
    { 
     if (WindowState == WindowState.Minimized) this.Hide(); 

     base.OnStateChanged(e); 
    } 

    // minimize to system tray when applicaiton 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); 
    } 
} 
相關問題