Событие щелчка NotifyIcon срабатывает позже, чем деактивация формы - PullRequest
0 голосов
/ 21 ноября 2018

Я установил форму невидимой при деактивации, а событие щелчка NotifyIcon как переключатель видимости.Если я щелкну NotifyIcon, когда форма станет видимой, форма будет скрыта, а затем быстро обнаружена, поскольку событие щелчка NotifyIcon сработало позже, чем событие деактивированной формы.Как я могу справиться с этим?


Код проблемы:

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 голосов
/ 22 ноября 2018

Вот рабочий пример того, что я имел в виду в своем комментарии.

В 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();
                }
            }
        }
    }      
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...