... da ich nicht weiß wann ich das nächste mal hier hinein schau,
oder ob du hier überhaupt nochmal hinein schaust; irgendwie wirkte dein letzter Beitrag leicht resignierend auf mich - unbegründet.
Mein Ziel war es ohne Formular oder Konsolenfenster zu arbeiten.
Es ist eine Konsolenanwendung mit Ausgabetyp: Windows-Anwendnung.
Dann nimm besser eine Windows Forms App und lösche aus dem Projekt die Form1.cs heraus.
In der Program.cs steht dann das hier:
using System;
using System.Windows.Forms;
using System.Drawing;
namespace KalenderwocheImSystemTray
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
MyTray myTray = new MyTray(2000);
Application.Run();
myTray.Dispose();
}
internal class MyTray : IDisposable
{
private readonly Timer _timer = new Timer();
private readonly Bitmap _bitmap = new Bitmap(16, 16);
private readonly NotifyIcon _ni = new NotifyIcon();
private readonly ContextMenu _cm = new ContextMenu();
private readonly Graphics _graphics;
private bool _disposed;
/// <param name="updateInterval">in milliseconds</param>
public MyTray(int timerInterval)
{
_graphics = Graphics.FromImage(_bitmap);
//Contextmenu erzeugen [0]=Exit
_cm.MenuItems.Add("Close", new EventHandler(ContextMenuItemClose));
//Notifyicon
_ni.ContextMenu = _cm;
_ni.Visible = true;
//Timer erzeugen
_timer.Interval = timerInterval;
_timer.Tick += new EventHandler(ReFreshIcon);
_timer.Enabled = true;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_timer.Stop();
if (disposing)
{
_bitmap?.Dispose();
_graphics?.Dispose();
_ni?.Dispose();
_timer?.Dispose();
_cm?.Dispose();
}
_timer.Tick -= ReFreshIcon;
_disposed = true;
}
private void ReFreshIcon(object sender, EventArgs e)
{
if (_disposed)
{
return;
}
// zu Testzwecken wird nicht die KW, sondern ablaufende Sekunden anhand vom Interval gezeichnet
_graphics.Clear(Color.Transparent);
_graphics.DrawString(DateTime.Now.AddSeconds(2).Second.ToString(), new Font("Arial", 10.0f), Brushes.White, 0, 0);
_ni.Icon = Icon.FromHandle(_bitmap.GetHicon());
}
private void ContextMenuItemClose(object sender, EventArgs e)
{
Application.Exit();
}
}
}
}
Der Schnittstelle IDisposable kann ich in meiner Anwednung allerdings nicht erben, da ich in einer Konsolenanwendung unterwegs bin.
Hat miteinander absolut null zu tun.
Wenn du mit Klassen arbeitest, die das IDisposable Interface implementieren, dann musst du sicher stellen, dass du hinter dir richtig aufräumst (egal ob Konsolenanwendung, Windows Forms, WPF, WCF, etc. pp).
Das Bequeme bei dem Thema ist, als Privat-Mensch kann man das Thema IDisposable ignorieren - man muss es nicht mal kennen; bei den kleinen 0815 Anwendungen fällt das nämlich nicht auf. Nur weil man aber etwas existentes ignoriert, heißt das nicht, das es nicht da ist/ sich damit nicht außeinander setzen sollte. ;o)
Grüße
Trägheit
|