我已经为你们编写了一个快速解决方案,这可能不是最有效的方法(我不确定),但它绝对有效!
下面的解决方案成功地将您的 Winforms 应用程序最小化到系统托盘,并使用通知图标在系统托盘中创建一个带有上述菜单项的小图标。而不是我们使用内置库来获取窗口(在这种情况下为 GUI),然后使用布尔值的适当方法,然后我们将窗口最小化到托盘。
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();
}