开发者

Toggle form visibility on NotifyIcon click and hide it on click elsewhere

开发者 https://www.devze.com 2023-04-02 07:18 出处:网络
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 hi

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).

My code looks like this:

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);
        }
    }
}

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.

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)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号