应用程序不会最小化到通知栏

时间:2013-04-22 07:50:11

标签: c# .net winforms notifyicon

我仍然无法使其工作,通知栏中没有任何内容。到目前为止,这是最小化的完整代码:

private void button6_Click(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Minimized;
}

private void Form_Resize(object sender, EventArgs e)
{
    if (WindowState == FormWindowState.Minimized)
    {
        this.Hide();
    }
}

private void notifyIcon_Click(object sender, EventArgs e)
{
    this.Show();
    this.WindowState = FormWindowState.Normal;
}

为什么这不起作用?

2 个答案:

答案 0 :(得分:4)

您永远不会在通知区域中显示任何内容。跟踪您的代码并尝试查看正在发生的事情。我添加了一些评论:

private void button6_Click(object sender, EventArgs e)
{
    // When button 6 is clicked, minimize the form.
    this.WindowState = FormWindowState.Minimized;
}

private void Form_Resize(object sender, EventArgs e)
{
    // Catch the case where the form is minimized, including but not limited to
    // clicks on button 6.
    if (WindowState == FormWindowState.Minimized)
    {
        // In that case, hide the form.
        this.Hide();
    }
}

private void notifyIcon_Click(object sender, EventArgs e)
{
    // If the notification icon is clicked, reshow the form as a normal window.
    this.Show();
    this.WindowState = FormWindowState.Normal;
}

现在注意问题?当表单最小化时,您所做的就是隐藏它。你永远不会告诉NotifyIcon显示它的图标!其Visible property的默认值为false。您必须将其设置为true以显示图标,并false使其消失。

所以修改你的代码如下:

private void Form_Resize(object sender, EventArgs e)
{
    // Catch the case where the form is minimized, including but not limited to
    // clicks on button 6.
    if (WindowState == FormWindowState.Minimized)
    {
        // In that case, hide the form.
        this.Hide();

        // And display the notification icon.
        notifyIcon.Visible = true;

        // TODO: You might also want to set other properties on the
        // notification icon, like Text and/or Icon.
    }
}

private void notifyIcon_Click(object sender, EventArgs e)
{
    // If the notification icon is clicked, reshow the form as a normal window.
    this.Show();
    this.WindowState = FormWindowState.Normal;

    // And hide the icon in the notification area.
    notifyIcon.Visible = false;
}

答案 1 :(得分:1)

试试这段代码:

private NotifyIcon notifyIcon;
public Form1()
{
    InitializeComponent();

    button6.Click += (sender, e) =>
        {
            this.WindowState = FormWindowState.Minimized;
        };

    this.Resize += (sender, e) =>
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                notifyIcon.Visible = true;
                notifyIcon.ShowBalloonTip(1000);
            }
        };

    notifyIcon = new NotifyIcon()
        {
            Text = "I'm here!",
            BalloonTipText = "I'm here!",
            Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath)
        };

    notifyIcon.Click += (sender, e) =>
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            notifyIcon.Visible = false;
        };
}