Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
— |
windows:programming:net:code_snippsets:free_icon_systemtray [2021/08/26 09:19] (aktuell) raiser angelegt |
||
---|---|---|---|
Zeile 1: | Zeile 1: | ||
+ | ====== Erstelltes Icon für Systemtray wird nicht sauber freigegeben ====== | ||
+ | Wenn sich mal wieder was im -.Net verklemmt ;), dann muss man eben hart über die Win-API nachhelfen.\\ | ||
+ | Fehler ist, dass das erstelle Icon für den System-Tray nicht wieder freigegebn wird... auch wenn man schön sauber `Dispose` aufruft. | ||
+ | |||
+ | <code c#> | ||
+ | [DllImport("user32.dll", CharSet = CharSet.Auto)] | ||
+ | extern static bool DestroyIcon(IntPtr handle); | ||
+ | |||
+ | IntPtr intptrIcon = IntPtr.Zero; | ||
+ | |||
+ | private Icon _notifyText(string text, Color c) | ||
+ | { | ||
+ | Brush brush = new SolidBrush(c); | ||
+ | Bitmap bitmap = new Bitmap(16, 16); | ||
+ | Graphics graphics = Graphics.FromImage(bitmap); | ||
+ | int y = 1; | ||
+ | if (text.Length > 2) | ||
+ | { | ||
+ | font = new Font("Arial", 6.5f); | ||
+ | y = 3; | ||
+ | } | ||
+ | else | ||
+ | { | ||
+ | font = new Font("Arial", 8.0f); | ||
+ | } | ||
+ | |||
+ | graphics.FillRectangle(brush, new Rectangle(0, 0, 16, 16)); | ||
+ | graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; | ||
+ | graphics.DrawString(text, font, Brushes.Black, 0, y); | ||
+ | |||
+ | _releaseIcon(); | ||
+ | |||
+ | Icon icon = null; | ||
+ | intptrIcon = bitmap.GetHicon(); | ||
+ | try | ||
+ | { | ||
+ | icon = Icon.FromHandle(intptrIcon); | ||
+ | | ||
+ | } | ||
+ | catch (Exception) | ||
+ | { | ||
+ | System.Diagnostics.Trace.WriteLine(""); | ||
+ | } | ||
+ | | ||
+ | graphics.Dispose(); | ||
+ | bitmap.Dispose(); | ||
+ | return icon; | ||
+ | } | ||
+ | |||
+ | private void _releaseIcon() | ||
+ | { | ||
+ | if (intptrIcon != IntPtr.Zero) | ||
+ | { | ||
+ | DestroyIcon(intptrIcon); | ||
+ | intptrIcon = IntPtr.Zero; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | </code> |