본문 바로가기

WPF/NotifyIcon

[WPF] NotifyIcon 등록 후 자동 숨김

[WPF] NotifyIcon 등록 후 자동 숨김

App-Launcher-icon.ico
0.35MB

1. 참조에 System.Drawing 추가하기

2. 아이콘 추가 (icon은 Content로 등록 후 아이콘 이미지 속성에서 "새 버전이면 복사"로 변경)

	#region NotifyIcon && ContextMenu
        private void SetNotifyIcon()
        {
            System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
            ni.Icon = new System.Drawing.Icon("App-Launcher-icon.ico");
            System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
            contextMenu.MenuItems.Add("&Show").Click += MainWindow_Click;
            contextMenu.MenuItems.Add("&Exit").Click += MainWindow_Click;
 
            ni.Visible = true;
            ni.ContextMenu = contextMenu;
 
            ni.DoubleClick += Ni_DoubleClick;
 
            this.Hide();
        }
 
        private void MainWindow_Click(object sender, EventArgs e)
        {
            var str = ((System.Windows.Forms.MenuItem)sender).Text;
            if (str.Contains("Show"))
            {
                this.Show();
                this.WindowState = WindowState.Normal;
            }
            else
            {
                this.Close();
            }
        }
 
        private void Ni_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = WindowState.Normal;
        }
 
        protected override void OnStateChanged(EventArgs e)
        {
            if (WindowState == System.Windows.WindowState.Minimized)
                this.Hide();
 
            base.OnStateChanged(e);
        } 
        #endregion

 

 

프로그램 종료시 NotifyIcon 없애기

private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (ni != null)
    {
        ni.Icon = null;
    }
}