I have programmed a quick solution for you guys, this might not be the most efficient way (I'm not sure), but it definitely works !
The below solution successfully minimizes your Winforms application to the system Tray, and by using the notify Icon you create a small icon in the system tray with the aforementioned menu items. than we use the in-built libraries to fetch the Window (GUI in this case), and using the appropriate methods with Booleans we then minimize the window to the tray.
private void TransformWindow()
{
ContextMenu Menu = new ContextMenu();
Menu.MenuItems.Add(RestoreMenu);
Menu.MenuItems.Add(HideMenu);
Menu.MenuItems.Add(new MenuItem("Exit", new EventHandler(CleanExit)));
notifyIcon = new NotifyIcon()
{
Icon = Properties.Resources.Microsft_Icon,
Text = "Folder Watcher",
Visible = true,
ContextMenu = Menu
};
processHandle = Process.GetCurrentProcess().MainWindowHandle;
ResizeWindow(false);
}
#region Getting Libraries
[DllImport("user32.dll")]
public static extern IntPtr GetShellWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
public const Int32 SwMINIMIZE = 0;
public const Int32 SwMaximize = 9;
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern IntPtr GetConsoleWindow();
[DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow([In] IntPtr hWnd, [In] Int32 nCmdShow);
public static void MinimizeConsoleWindow()
{
IntPtr hWndConsole = processHandle;
ShowWindow(hWndConsole, SwMINIMIZE);
}
public static void MaximizeConsoleWindow()
{
IntPtr hWndConsole = processHandle;
ShowWindow(hWndConsole, SwMaximize);
}
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public static void ResizeWindow(bool show)
{
RestoreMenu.Enabled = !show;
HideMenu.Enabled = show;
SetParent(processHandle, WinDesktop);
if (show)
MaximizeConsoleWindow();
else
MinimizeConsoleWindow();
}
public static void MinimizeClick(object sender, EventArgs e) => ResizeWindow(false);
public static void MaximizeClick(object sender, EventArgs e) => ResizeWindow(true);
public static IntPtr processHandle;
public static IntPtr WinShell;
public static IntPtr WinDesktop;
public static NotifyIcon notifyIcon;
public static MenuItem HideMenu = new MenuItem("Hide", new EventHandler(MinimizeClick));
public static MenuItem RestoreMenu = new MenuItem("Restore", new EventHandler(MaximizeClick));
public void CleanExit(object sender, EventArgs e)
{
notifyIcon.Visible = false;
this.Close();
}