[WPF] 컨텍스트 메뉴와 트레이 아이콘

2020. 3. 10. 15:35IT/C# WPF

프로그램을 최소화하거나 닫기를 눌렀을 때, 프로그램이 꺼지지않고 트레이에 머무르도록 기능 구현.

<Window x:Class="WpfApp3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height=".3*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Height="50" Width="200" Margin="5">의미없는버튼</Button>
            <Button Height="50" Width="200" Margin="5">의미없는버튼</Button>
        </StackPanel>

        <Border Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock Text="테스트페이지입니다." FontSize="25" />
        </Border>

    </Grid>
</Window>

 

보여지는 뷰는 의미없는 버튼과 의미없는 텍스트로 이루어져있습니다.

이 부분은 참고 안하셔도 될 것 같습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp3
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnStateChanged(EventArgs e)
        {
            if (WindowState.Minimized.Equals(WindowState))
            {
                this.Hide();
            }

            base.OnStateChanged(e);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            base.OnClosing(e);
        }
    }
}

 

닫기와 최소화 버튼을 눌렀을 때, 프로그램을 끄지않고 숨겨지게하는 코드입니다.

추가로 컨텍스트메뉴와 트레이아이콘을 구현해보겠습니다.

 

System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Forms.ContextMenu menu = new System.Windows.Forms.ContextMenu();

                //트레이아이콘 파일 경로 설정
                StreamResourceInfo iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/images/favicon.ico"));

                ni.Icon = new System.Drawing.Icon(iconStream.Stream);
                ni.Visible = true;
                ni.DoubleClick += delegate (object senders, EventArgs args)
                {
                    this.Show();
                    this.WindowState = WindowState.Normal;
                };

                ni.ContextMenu = menu;
                ni.Text = "의미없는 프로그램";

                System.Windows.Forms.MenuItem item1 = new System.Windows.Forms.MenuItem();
                System.Windows.Forms.MenuItem item2 = new System.Windows.Forms.MenuItem();

                menu.MenuItems.Add(item1);
                menu.MenuItems.Add(item2);

                item1.Index = 0;
                item1.Text = "의미없는 프로그램 종료";
                item1.Click += delegate (object click, EventArgs eClick)
                {
                    System.Windows.Application.Current.Shutdown();
                };
                item2.Index = 0;
                item2.Text = "의미없는 프로그램 열기";
                item2.Click += delegate (object click, EventArgs eClick)
                {
                    this.Show();
                    this.WindowState = WindowState.Normal;
                };
            }
            catch
            {

            }
        }

 

참조에 System.Windows.forms를 추가해주셔야합니다.

 

그 후에 메인윈도우에 한줄만 추가하시면 끝이 납니다.

        public MainWindow()
        {
            InitializeComponent();

            Loaded += Window_Loaded;
        }

 

참고 URL : https://glorymind.tistory.com/entry/WPF-Tray-%ED%8A%B8%EB%A0%88%EC%9D%B4-%EC%83%9D%EC%84%B1%ED%95%98%EA%B3%A0-%EC%A1%B0%EC%9E%91%ED%95%98%EA%B8%B0