0

I am writting a program in vb.net that uses the systray and what I am trying to achieve is the following.

If the systray icon is clicked it should minimise/restore the form. (this I can do) the bit I am stuck on is that if the form is 'open' and not focused I want it to get focus rather than minimise.

I can't seem to find anything that does the test I need to see if the form is not in a minimised state and does not have focus.

Any suggestions welcome.

Thanks

  • After some searching I think I have an answer to my question. Though I have run into another related issue. In that the act of clicking the taskbar icon causes the form to lose focus so my test always returns focus=false. So I need to see if it had focus before the mouseclick. – user732467 Apr 30 '11 at 15:06

1 Answers1

0

Keep track of the form activation state by listening to the Activate and Deactivate events. One complication is that the form will be de-activated when you click the icon. Solve that by recording the time it happened. Like this:

Public Class Form1
    Private IsActivated As Boolean
    Private DeActivation As DateTime

    Protected Overrides Sub OnActivated(e As System.EventArgs)
        IsActivated = True
        MyBase.OnActivated(e)
    End Sub

    Protected Overrides Sub OnDeactivate(e As System.EventArgs)
        IsActivated = False
        DeActivation = DateTime.Now
        MyBase.OnDeactivate(e)
    End Sub

    Private Sub NotifyIcon1_MouseClick(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
        If Me.WindowState = FormWindowState.Minimized Then
            Me.WindowState = FormWindowState.Normal
        Else
            If IsActivated OrElse DateTime.Now - DeActivation < New TimeSpan(0, 0, 1) Then
                Me.WindowState = FormWindowState.Minimized
            Else
                Me.Activate()
            End If
        End If

    End Sub
End Class

This is otherwise a fairly unpleasant hack around having to set the form's ShowInTaskbar property to False. It is possible to have a taskbar button and still keep the form invisible at startup. Check this answer for the approach.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536