開発環境:visual studio2015
開発言語:C#.net
1.概要
タスクトレイに常駐しているアプリケーションを作成します。
タスクトレイとは画面右下にある下図のものです。
2.コントロールの追加
【NotifyIcon】【CntextMenuStrip】の2つを使用します。
この2つをツールボックスから選択しFormに貼り付けます。
3.【NotifyIcon】の設定
変更するプロパティは下記の3項目です。
【ContextMenuStrip】:先ほど追加した【CntextMenuStrip1】を指定します。
【Icon】:タスクトレイに表示したいアイコンを設定します。
【Text】:マウスをアイコン上に移動した時に表示されるテキストを設定します。
4.【CntextMenuStrip】の設定
こちらは【開く】と【閉じる】の2つを追加しました。
5.アプリケーションの動作
アプリケーションは下記のとおり動作するように作成します。
①アプリケーション起動時にはFormは表示せず、タスクバーにも表示しない。
②タスクトレイにある常駐アイコンを右クリックでメニューが表示される。
③タスクトレイにある常駐アイコンをダブルクリックでFORMが表示される。
④メニューの【開く】をクリックでFORMが表示される。
⑤メニューの【閉じる】をクリックでアプリケーションが終了する。
⑥FORMの×ボタンをクリックでタスクトレイに最小化される。
6アプリケーションの設定
上記①を満たすためにアプリケーションの設定をします。
アプリケーションのメインエントリポイントを変更します。
スクリプトに下記を追加します。
[STAThread] static void Main() { Form1 f1 = new Form1(); Application.Run(); }
プロジェクトのプロパティを開き
【スタートアップオブジェクト】を下図のとおり変更します。
これで設定は完了です。
7.スクリプト
スクリプトは下記のとおりです。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace contextMenuTest { public partial class Form1 : Form { [STAThread] static void Main() { Form1 f1 = new Form1(); Application.Run(); } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //this.Visible = false; } private void notifyIcon1_DoubleClick(object sender, EventArgs e) { this.Visible = true; //フォームの表示 if (this.WindowState == FormWindowState.Minimized) { this.WindowState = FormWindowState.Normal; } this.Activate(); } private void 開くToolStripMenuItem_Click(object sender, EventArgs e) { this.Visible = true; //フォームの表示 if (this.WindowState == FormWindowState.Minimized) { this.WindowState = FormWindowState.Normal; } this.Activate(); } private void 閉じるToolStripMenuItem1_Click(object sender, EventArgs e) { notifyIcon1.Visible = false; //アイコンをトレイから取り除く //notifyIcon1.Dispose(); Application.Exit(); //アプリケーションの終了 } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if(e.CloseReason != System.Windows.Forms.CloseReason.ApplicationExitCall) { e.Cancel = true; this.Visible = false; } } } }
8.結果
タスクトレイにアイコンが表示され
このアイコンから想定どおりの操作が出来れば完成です。