Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Drawing;
- using System.Threading;
- using System.Windows.Forms;
- namespace Systraytest
- {
- public partial class Form1 : Form, IDisposable
- {
- private readonly NotifyIcon _icon;
- private readonly ContextMenu _trayMenu;
- private BackgroundWorker _worker;
- private readonly MenuItem _startItem;
- private readonly MenuItem _stopItem;
- private readonly MenuItem _exitItem;
- public Form1()
- {
- InitializeComponent();
- _startItem = new MenuItem("Start", OnStartClicked);
- _stopItem = new MenuItem("Stop", OnStopClicked);
- _exitItem = new MenuItem("Exit", OnExitClicked);
- _trayMenu = new ContextMenu();
- SetupTrayMenu(false);
- _icon = new NotifyIcon();
- _icon.Text = "SysTrayTest";
- _icon.Icon = new Icon(SystemIcons.Application, 40, 40);
- _icon.ContextMenu = _trayMenu;
- _icon.Visible = true;
- SetupWorker();
- }
- private void SetupWorker()
- {
- _worker = new BackgroundWorker();
- _worker.WorkerSupportsCancellation = true;
- _worker.DoWork += (s, ea) =>
- {
- var worker = s as BackgroundWorker;
- Debug.WriteLine("BWorker started!");
- while (!worker.CancellationPending)
- {
- Debug.WriteLine("PFFFT");
- Thread.Sleep(1000);
- }
- Debug.WriteLine("BWorker canceled!");
- };
- _worker.RunWorkerCompleted += (s, ea) =>
- {
- Debug.WriteLine("BWorker completed!");
- SetupTrayMenu(false);
- };
- }
- private void SetupTrayMenu(bool running)
- {
- _trayMenu.MenuItems.Clear();
- _trayMenu.MenuItems.Add(running ? _stopItem : _startItem);
- _trayMenu.MenuItems.Add(_exitItem);
- }
- private void OnStartClicked(object sender, EventArgs e)
- {
- _worker.RunWorkerAsync();
- SetupTrayMenu(true);
- }
- private void OnStopClicked(object sender, EventArgs e)
- {
- _worker.CancelAsync();
- }
- private void OnExitClicked(object sender, EventArgs e)
- {
- if (_worker.IsBusy && !_worker.CancellationPending)
- {
- _worker.CancelAsync();
- }
- Application.Exit();
- }
- protected override void OnLoad(EventArgs e)
- {
- Visible = false;
- ShowInTaskbar = false;
- base.OnLoad(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement