C#

[WPF] 소스로 트레이 아이콘 - 1 (Windows.Forms)

Dongmin Jang 2021. 2. 4. 12:58

WPF에 트레이 기능을 넣어보려고 했고 소스로는 나오긴하는데 예쁘지가 않아서 이 게시글에는 소스로 짧게 구현해보고 다음 게시글에서 xaml로 MaterialDesign 라이브러리와 함께 ContextMenu에 대한 템플릿을 만들어보고자 한다.

아이콘은 인터넷에서 아무거나 받아 사용하였음

 

윈도우
트레이 아이콘

// MainWindow.xaml.cs

using System.Windows;
using System.Windows.Forms;

namespace TrayApp
{
    public partial class MainWindow : Window
    {
        public NotifyIcon notifyIcon;

        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += (o, r) =>
            {
                // 아이콘 초기화
                notifyIcon = new NotifyIcon();
                notifyIcon.Icon = new System.Drawing.Icon(@"Graphicloads.ico");
                notifyIcon.ContextMenu = new ContextMenu();
                notifyIcon.Visible = true;

                // 예) 설정
                MenuItem itemSetting = new MenuItem();
                itemSetting.Index = 0;
                itemSetting.Text = "설정";
                itemSetting.Click += (s, e) => this.Show();
                notifyIcon.ContextMenu.MenuItems.Add(itemSetting);

                // 예) 종료
                MenuItem itemClose = new MenuItem();
                itemClose.Index = 1;
                itemClose.Text = "종료";
                itemClose.Click += (s, e) => System.Windows.Application.Current.Shutdown();
                notifyIcon.ContextMenu.MenuItems.Add(itemClose);

                // 아이콘 더블클릭시 윈도우 활성화
                notifyIcon.DoubleClick += (s, e) => this.Show();

                // 응용프로그램 종료시 아이콘 제거
                System.Windows.Application.Current.Exit += (s, e) => notifyIcon.Dispose();

                // 트레이버튼 클릭시 윈도우 비활성화
                ButtonTray.Click += (s, e) => this.Hide();
            };
        }
    }
}

 

// MainWindow.xaml
<Window x:Class="TrayApp.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:TrayApp"
        mc:Ignorable="d"
        Height="90" Width="240">
    <Button x:Name="ButtonTray" Content="트레이" HorizontalAlignment="Left" Margin="24,21,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.091,-0.79"/>
</Window>

 

소스: github.com/dogzz9445/CSharpTestExamples/tree/main/TrayApp