NotifyIcon点击事件在表单停用之前触发

时间:2018-11-21 20:27:14

标签: c# .net winforms

我将停用状态设置为不可见,并将NotifyIcon click事件设置为可见性开关。如果在窗体可见时单击NotifyIcon,则该窗体将隐藏然后快速显示,因为NotifyIcon click事件晚于窗体停用事件而触发。我该如何处理?


问题代码:

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
    if (!Visible)
    {
        Visible = true;
    }
}

private void Form1_Deactivate(object sender, EventArgs e)
{
    Visible = false;
}

现在我正在使用计时器来防止快速更改,但这很丑陋:

private readonly Timer _timer = new Timer(200);
private bool _canChangeVisible = true;

在构造函数中:

_timer.Elapsed += (sender, args) =>
{
    _canChangeVisible = true;
    _timer.Stop();
};

事件处理程序:

private void Form1_Deactivate(object sender, EventArgs e)
{
    if (Visible)
    {
        _canChangeVisible = false;
        _timer.Start();
        Visible = false;
    }
}

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
    if (_canChangeVisible && e.Button == MouseButtons.Left)
    {
        Visible = !Visible;
    }
}

1 个答案:

答案 0 :(得分:0)

这是我在评论中暗示的可行示例。

form中,您应该具有以下内容。它所做的是记录上一次停用的时间。如果此人在停用时单击得太快,我们想跳过它,因为它已经关闭了,这是您要尝试的操作。

public DateTime LastDeactivate { get; set; } = DateTime.Now;
private void Form1_Deactivate(object sender, EventArgs e)
{
    this.Hide();
    LastDeactivate = DateTime.Now;
}

在应用程序上下文中,我不知道您的完整代码,但这是我的完整工作版本

public class MainContext : ApplicationContext
{
    private NotifyIcon notifyIcon = new NotifyIcon();
    private Form1 form = null;

    public MainContext()
    {           
        notifyIcon.Text = "test";
        // whatever the icon
        notifyIcon.Icon = Properties.Resources.Folder;
        notifyIcon.Click += NotifyIcon_Click;

        // make the icon visible
        notifyIcon.Visible = true;
    }

    private void NotifyIcon_Click(object sender, EventArgs e)
    {
        // special case for the first click
        if (form == null)
        {
            form = new Form1();
            form.ShowDialog();
        }
        else
        {
            // test if the form has been recently closed. Here i consider 1/10
            // of a second as "recently" closed. So we want only to handle the click
            // if the time is greater than that.
            if ((DateTime.Now - form.LastDeactivate).TotalMilliseconds >= 100)
            {
                // specially control the show hide as visibility on/off
                // does not trigger the activate event that screw up the
                // later hiding of the form
                if (form.Visible)
                {
                    form.Hide();
                }
                else
                {
                    form.Show();
                    form.Activate();
                }
            }
        }
    }      
}