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

后端 未结 1 1465
执念已碎
执念已碎 2021-01-16 15:16

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

相关标签:
1条回答
  • 2021-01-16 15:38

    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 讨论(0)
提交回复
热议问题