单击 NotifyIcon 时切换表单可见性,单击其他位置时隐藏它
我有一个位于系统托盘中的应用程序。我希望当用户单击 notifyIcon
时使其可见(如果它尚不可见)。如果它已经可见,则应将其隐藏。此外,当用户单击表单之外的其他任何位置时,表单应该隐藏(如果它可见)。
我的代码如下所示:
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
在 click 调用之前被调用,这会隐藏表单和 notifyIcon1_MouseClicked
而不是重新显示它。如果我能够检测到焦点是否由于点击 notifyIcon
或其他地方而丢失,那么问题就可以解决。
我已经完成了研究并发现了类似的线程,但解决方案只是在调用 onDeactivated
时检测鼠标位置是否位于托盘上:C# 通过单击 NotifyIcon(任务栏图标)切换窗口
更新: 我发布的解决方案仅检测用户的鼠标是否位于任务栏中的托盘图标上,因此如果您单击任何其他托盘,则不会触发 onDeactivated
事件。 我想获得与系统音量应用程序相同的功能。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需跟踪窗口上次隐藏的时间即可。如果最近发生过这种情况,请忽略鼠标单击。像这样:
重复单击图标现在可以可靠地切换窗口可见性。
Simply keep track of the time when the window was last hidden. And ignore the mouse click if that happened recently. Like this:
Clicking the icon repeatedly now reliably toggles the window visibility.