0

我想通过单击表单系统菜单中的条目将我的程序最小化到系统托盘。所以首先我创建了一个通知图标和一个上下文菜单:

private void InitializeComponent()
{
  this.components = new Container();
  ...
  this.notifyIcon = new NotifyIcon();
  this.contextMenu = new ContextMenu();
  this.contextMenuItem1 = new MenuItem();
  this.contextMenuItem2 = new MenuItem();
  this.SuspendLayout();

  this.notifyIcon.ContextMenu = this.contextMenu;
  this.notifyIcon.Text = "Test";

  this.contextMenu.Name = "contextMenu";
  this.contextMenu.MenuItems.AddRange(new MenuItem[]
  {
    this.contextMenuItem1,
    this.contextMenuItem2
  });

  this.contextMenuItem1.Name = "contextMenuItem1";
  this.contextMenuItem1.Text = "&Show";
  this.contextMenuItem1.Click += new EventHandler(this.contextMenuItem1_Click);

  this.contextMenuItem2.Name = "contextMenuItem2";
  this.contextMenuItem2.Text = "&Exit";
  this.contextMenuItem2.Click += new EventHandler(this.contextMenuItem2_Click);
}

然后我扩展了系统菜单:

private void Form_Load(object sender, EventArgs e)
{
  int hmenu = GetSystemMenu(Handle, 0);
  AppendMenu(hmenu, 0xA00, 0, null);
  AppendMenu(hmenu, 0, 111, "M&inimize to system tray");
}

单击此菜单项应淡出主窗口:

protected override void WndProc(ref Message m)
{
  base.WndProc(ref m);
  if (m.Msg == 0x112)
  {
    if (m.WParam.ToInt32() == 111)
    {
      Visible = false;
      Hide();
      notifyIcon.Visible = true;
    }
  }
}

单击上下文菜单必须重新显示程序窗口或关闭整个应用程序:

private void contextMenuItem1_Click(object sender, EventArgs e)
{
  notifyIcon.Visible = false;
  Show();
  Visible = true;
}

private void contextMenuItem2_Click(object sender, EventArgs e)
{
  Close();
}

我现在的问题如下:如果我单击新条目以最小化,则成功执行 WndProc 方法并且表单将被隐藏,但系统托盘中没有显示标题为“测试”的项目。然后还有另一个可见的窗口。我认为这来自.NET,但窗口完全是空的,所以我不确定。通常我应该回退到启动我的程序的 Windows 资源管理器中的 exe 文件,不是吗?

提前致谢!

+++ 编辑 +++

我发现我的应用程序后面的空窗口是控制台窗口。我只是忘了用 winexe 参数编译我的项目。

4

0 回答 0