Windowsタスクトレイ常駐型のアプリを作る(WPF版)
よく作るんですけどね。忘れるよね。
なお、ググるキーワードはNotifyIcon。
Component作成
Componentsフォルダを作って、右クリック→「追加」→「新しい項目」
「コンポーネントクラス」を探し出して、お好きな名前をつけて追加しましょう。
ここでは「NotifyIcon」としました。
NotifyIconクラスの編集
ツールボックスから「ContextMenuStrip」と「NotifyIcon」を追加します。
ツールボックスで検索して、ドラッグ&ドロップで持っていきましょう。
デフォルトの名前が嫌なので変えましたよ。
contextMenuStripの設定
contextMenuStripを右クリックで「項目の編集」
MenuItemを追加
「デザイン」→「(Name)」と「表示」→「Text」を編集
Nameはご自由に。Textはタスクトレイのアイコンを右クリックしたときに出るメニューに表示されますよ。
myNotifyIconの編集
プロパティを開いて、ContextMenuStripとIconを設定
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>