在NotifyIcon单击时切换表单可见性,而在其他位置单击时隐藏它 [英] Toggle form visibility on NotifyIcon click and hide it on click elsewhere

查看:79
本文介绍了在NotifyIcon单击时切换表单可见性,而在其他位置单击时隐藏它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在系统托盘中有一个应用程序.我想在用户单击 notifyIcon 时使它可见(如果尚不可见).如果已经可见,则应将其隐藏.同样,当用户单击除表单以外的其他任何位置时,表单也应隐藏(如果可见).

I have an application which is in system tray. I want to make it visible when the user clicks on the notifyIcon, if it's not visible already. If it is already visible it should be hidden. Also when the user clicks anywhere else except on the form the form should hide (if it's visible).

我的代码如下:

protected override void OnDeactivated(EventArgs e)
{
    showForm(false);
}

public void showForm(bool show)
{
    if(show)
    {
        Show();
        Activate();
        WindowState = FormWindowState.Normal;
    }
    else
    {
        Hide();
        WindowState = FormWindowState.Minimized;
    }
}

private void notifyIcon1_MouseClicked(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        if (WindowState != FormWindowState.Normal)
        {
            showForm(true);
        }
    }
}

该代码的问题在于,在单击调用之前调用了 onDeactivated ,这隐藏了表单,并

notifyIcon1_MouseClicked 而不是重新显示.如果我可以检测到是否由于单击 notifyIcon 或其他地方而失去了焦点,那就可以解决问题.

The problem with the code is that onDeactivated gets called before the click call, which hides the form and notifyIcon1_MouseClicked than just re-shows it. If I could detect if the focus was lost due to a click on notifyIcon or elsewhere it would solve the problem.

我已经进行了研究,发现了一个类似的线程,但是该解决方案只是在调用 onDeactivated 时检测到鼠标的位置是否在托盘上方:

I've done my research and found a similar thread, but the solution just detected if the mouse position is over the tray when onDeactivated gets called: C# toggle window by clicking NotifyIcon (taskbar icon)

更新:我发布的解决方案仅检测用户的鼠标是否在任务栏中的托盘图标上方,因此,如果单击任何其他托盘,则不会触发 onDeactivated 事件.我想获得与系统批量应用相同的功能.

UPDATE: The solution I posted only detects if the user's mouse is over the tray icons in the taskbar, so if you click on any other tray the onDeactivated event won't get fired. I want to get the same functionality as the system volume app.

推荐答案

只需跟踪上一次隐藏窗口的时间即可.如果最近发生,请忽略鼠标单击.像这样:

Simply keep track of the time when the window was last hidden. And ignore the mouse click if that happened recently. Like this:

int lastDeactivateTick;
bool lastDeactivateValid;

protected override void OnDeactivate(EventArgs e) {
    base.OnDeactivate(e);
    lastDeactivateTick = Environment.TickCount;
    lastDeactivateValid = true;
    this.Hide();
}

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) {
    if (lastDeactivateValid && Environment.TickCount - lastDeactivateTick < 1000) return;
    this.Show();
    this.Activate();
}

现在,反复单击该图标可以可靠地切换窗口的可见性.

Clicking the icon repeatedly now reliably toggles the window visibility.

这篇关于在NotifyIcon单击时切换表单可见性,而在其他位置单击时隐藏它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆