Created
May 15, 2022 15:23
-
-
Save emoacht/0085ca35aa614abc60ccd05d2aad7f49 to your computer and use it in GitHub Desktop.
Hold and show NotifyIcon from WPF app.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using System.Windows; | |
using System.Windows.Forms; | |
public class NotifyIconHolder | |
{ | |
public event EventHandler<Point>? MouseRightClick; | |
public event EventHandler<Point>? MouseLeftClick; | |
public event EventHandler<Point>? MouseDoubleClick; | |
[DllImport("User32.dll", SetLastError = true)] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
private static extern bool GetCursorPos(out POINT lpPoint); | |
[StructLayout(LayoutKind.Sequential)] | |
private struct POINT | |
{ | |
public int x; | |
public int y; | |
public static implicit operator System.Windows.Point(POINT p) => new(p.x, p.y); | |
} | |
private NotifyIcon? _notifyIcon; | |
public void ShowIcon(System.Drawing.Icon icon, string text) | |
{ | |
if (_notifyIcon is null) | |
{ | |
_notifyIcon = new NotifyIcon() | |
{ | |
Icon = icon, | |
Text = text | |
}; | |
_notifyIcon.MouseClick += (_, e) => | |
{ | |
if (GetCursorPos(out POINT position)) | |
{ | |
switch (e.Button) | |
{ | |
case MouseButtons.Left: | |
MouseLeftClick?.Invoke(null, position); | |
break; | |
case MouseButtons.Right: | |
MouseRightClick?.Invoke(null, position); | |
break; | |
} | |
} | |
}; | |
_notifyIcon.MouseDoubleClick += (_, _) => | |
{ | |
if (GetCursorPos(out POINT position)) | |
{ | |
MouseDoubleClick?.Invoke(null, position); | |
} | |
}; | |
_notifyIcon.Visible = true; | |
} | |
} | |
public void HideIcon() | |
{ | |
_notifyIcon?.Dispose(); | |
_notifyIcon = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment