C#C
C#2y ago
Rémi

Hide console app but still show tray Icon

Hey, i'm making a tray icon only app, the tray icon works fine,but not when I set the output to Windows Application to hide the console.
using System.Runtime.InteropServices;

class Program
{
    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    public static extern bool Shell_NotifyIcon(int dwMessage, NOTIFYICONDATA lpData);
    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SW_HIDE = 0;
    const int NIM_ADD = 0x00000000;
    const int NIM_DELETE = 0x00000002;
    const int NIF_MESSAGE = 0x00000001;
    const int NIF_ICON = 0x00000002;
    const int NIF_TIP = 0x00000004;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct NOTIFYICONDATA
    {
        public int cbSize;
        public IntPtr hWnd;
        public int uID;
        public int uFlags;
        public int uCallbackMessage;
        public IntPtr hIcon;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
        public string szTip;
    }

    static void Main()
    {
        NOTIFYICONDATA nid = new NOTIFYICONDATA();
        nid.cbSize = Marshal.SizeOf(nid);
        nid.hWnd = GetConsoleWindow();
        nid.uID = 1;
        nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
        nid.uCallbackMessage = 0x8000;

        // Specify the path to your custom icon
        nid.hIcon = LoadIcon("ico.ico");
        nid.szTip = "";

        Shell_NotifyIcon(NIM_ADD, nid);
        ShowWindow(GetConsoleWindow(), SW_HIDE);
        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();

        Shell_NotifyIcon(NIM_DELETE, nid);
        Thread.Sleep(5000);
    }

    // Load icon from file
    private static IntPtr LoadIcon(string path)
    {
        IntPtr hIcon = IntPtr.Zero;
         hIcon = new System.Drawing.Icon(path).Handle;

        return hIcon;
    }
}
Was this page helpful?