我正在从Link开始学习本教程,并添加菜单,但是在最小化到系统托盘并将其还原后无法键入控制台应用程序。
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll")]
static extern IntPtr GetShellWindow();
[DllImport("user32.dll")]
static extern IntPtr GetDesktopWindow();
static NotifyIcon notifyIcon;
static IntPtr processHandle;
static IntPtr WinShell;
static IntPtr WinDesktop;
static MenuItem HideMenu;
static MenuItem RestoreMenu;
static Thread notifyThread;
static void Main(string[] args)
{
int Input;
do
{
Console.Clear();
Console.WriteLine("Please select");
Console.WriteLine("[1] Settings");
Console.WriteLine("[2] View Messages");
Console.WriteLine("[3] Run in background");
Console.WriteLine("[4] Exit");
while (!int.TryParse(Console.ReadLine(), out Input))
{
Console.WriteLine("Please enter a number only");
}
switch (Input)
{
case 1:
break;
case 2:
break;
case 3:
//notifyThread = new Thread(delegate ()
//{
notifyIcon = new NotifyIcon();
notifyIcon.Icon = new Icon("e_mail.ico");
notifyIcon.Text = "Email";
notifyIcon.Visible = true;
ContextMenu menu = new ContextMenu();
HideMenu = new MenuItem("Hide", new EventHandler(Minimize_Click));
RestoreMenu = new MenuItem("Restore", new EventHandler(Maximize_Click));
menu.MenuItems.Add(RestoreMenu);
menu.MenuItems.Add(HideMenu);
menu.MenuItems.Add(new MenuItem("Exit", new EventHandler(CleanExit)));
notifyIcon.ContextMenu = menu;
Task.Factory.StartNew(Run);
processHandle = Process.GetCurrentProcess().MainWindowHandle;
WinShell = GetShellWindow();
WinDesktop = GetDesktopWindow();
ResizeWindow(false);
Application.Run();
//});
//notifyThread.Start();
break;
case 4:
Environment.Exit(-1);
break;
default:
Input = 0;
break;
}
} while (Input == 0);
Console.ReadKey();
}
static void Run()
{
Console.WriteLine("Listening to messages");
while (true)
{
System.Threading.Thread.Sleep(1000);
}
}
private static void CleanExit(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
Environment.Exit(1);
}
static void Minimize_Click(object sender, EventArgs e)
{
ResizeWindow(false);
}
static void Maximize_Click(object sender, EventArgs e)
{
ResizeWindow();
}
static void ResizeWindow(bool Restore = true)
{
if (Restore)
{
RestoreMenu.Enabled = false;
HideMenu.Enabled = true;
SetParent(processHandle, WinDesktop);
}
else
{
RestoreMenu.Enabled = true;
HideMenu.Enabled = false;
SetParent(processHandle, WinShell);
}
}
如果我选择数字3,它将最小化到系统托盘,并且图标上有一个上下文菜单可以恢复该选项。从系统托盘中恢复控制台应用程序后,我该如何允许它再次键入?