.Net Console Application in System tray

Melursus picture Melursus · Apr 15, 2009 · Viewed 32.9k times · Source

Is there a way I can put a console application in the system tray when minimizing ?

Answer

CLaRGe picture CLaRGe · Apr 15, 2009

Yes, you can do this. Create a Windows Forms application and add a NotifyIcon component.

Then use the following methods (found on MSDN) to allocate and display a Console

[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();

[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();

[DllImport("kernel32.dll")]
public static extern Boolean AttachConsole(Int32 ProcessId);

When your console is onscreen, capture the minimize button click and use it to hide the console window and update the Notify icon. You can find your window using the following methods (found on MSDN):

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
// Also consider whether you're being lazy or not.
[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

Be sure to call FreeConsole whenever you're ready to close the app.