Windowsタスクトレイ常駐型のアプリを作る(WPF版)


よく作るんですけどね。忘れるよね。
なお、ググるキーワードはNotifyIcon。

準備

icoファイルを用意しましょう。
ここにあげようと思ったら、HatenaBlogさんはicoファイルに対応してないようなので皆さん頑張って自力で用意しましょう。

icoファイルをプロジェクトに投入

Resourcesフォルダを作って、ドラッグ&ドロップで投入しましょう。

f:id:devdevdev:20180502212145p:plain

Component作成

Componentsフォルダを作って、右クリック→「追加」→「新しい項目」
コンポーネントクラス」を探し出して、お好きな名前をつけて追加しましょう。
ここでは「NotifyIcon」としました。
f:id:devdevdev:20180502212706p:plain
f:id:devdevdev:20180502212745p:plain

NotifyIconクラスの編集

ツールボックスから「ContextMenuStrip」と「NotifyIcon」を追加します。
ツールボックスで検索して、ドラッグ&ドロップで持っていきましょう。
デフォルトの名前が嫌なので変えましたよ。

f:id:devdevdev:20180502213314p:plainf:id:devdevdev:20180502213319p:plain
f:id:devdevdev:20180502213354p:plain



contextMenuStripの設定

contextMenuStripを右クリックで「項目の編集」

f:id:devdevdev:20180502213605p:plain

MenuItemを追加
「デザイン」→「(Name)」と「表示」→「Text」を編集
Nameはご自由に。Textはタスクトレイのアイコンを右クリックしたときに出るメニューに表示されますよ。

f:id:devdevdev:20180502213811p:plain
f:id:devdevdev:20180502213933p:plain

myNotifyIconの編集

プロパティを開いて、ContextMenuStripとIconを設定

f:id:devdevdev:20180502214154p:plain



NotifyIcon.csの編集

終了メニュークリックしたらアプリケーションを終了。

using System;
using System.ComponentModel;
using System.Windows;

namespace Hoge.Components
{
    public partial class NotifyIcon : Component
    {
        public NotifyIcon()
        {
            InitializeComponent();
            toolStripMenuItemExitApp.Click += delegate (object sender, EventArgs e)
            {
                Application.Current.Shutdown();
            };
        }

        public NotifyIcon(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
    }
}



App.xamlの編集

App.xaml.csのほうから

using Hoge.Components;
using System.Windows;

namespace Hoge
{
    /// <summary>
    /// App.xaml の相互作用ロジック
    /// </summary>
    public partial class App : Application
    {
        private NotifyIcon notifyIcon = new NotifyIcon();

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            notifyIcon.Dispose();
        }
    }
}

んで、App.xaml
StartupUri="MainWindow.xaml"って記載があるので削除しましょう。

<Application x:Class="Questionnaire.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Hoge">
    <Application.Resources>
         
    </Application.Resources>
</Application>

参照追加

「System.Drawing」への参照を追加しましょう。疲れたので詳細は説明しません。Windowsエンジニアならわかるでしょ!

いじょ。