0

The following event in a Winforms Form does not fire for me:

Public Class Form1
    Private Sub Form1_Enter(sender As Object, e As EventArgs) Handles Me.Enter
        Debug.Print("enter!")
    End Sub
End Class

I expect it to fire when I have another window open in the background (for example notepad.exe), and notepad is focussed, and then I click on my form or mouse-enter it to activate my app / form.

Does not fire for me. Why?

Thank you.

enter image description here

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
tmighty
  • 10,734
  • 21
  • 104
  • 218
  • According to [documentations](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.enter?view=net-5.0&WT.mc_id=DT-MVP-5003235): The `Enter` and `Leave` events are suppressed by the `Form` class. The equivalent events in the Form class are the [`Activated`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.activated?view=net-5.0&WT.mc_id=DT-MVP-5003235) and [`Deactivate`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.deactivate?view=net-5.0&WT.mc_id=DT-MVP-5003235) events. – Reza Aghaei Feb 20 '21 at 12:12
  • @RezaAghaei Activated doesn't fire either. – tmighty Feb 20 '21 at 12:37
  • Moving mouse over your form doesn't activate your form, but if you click on your form, it will be activated and the `Activated` event will be raised. – Reza Aghaei Feb 20 '21 at 12:52
  • @RezaAghaei Yes, I know, but I'm looking for an event that would allow me to still get the GetForegroundWindow() on the current window handle before my app is being activated."Activated" is already too late, so I was hoping that "Enter" would be fired by my app is being activated. – tmighty Feb 20 '21 at 15:28
  • This question is: *Why Enter event is not fired for form?* And I believe the first comment answers your question. And for the question in your comment, I've seen your [other question](https://stackoverflow.com/q/66291136/3110834) asking for a way to find handle of the window which is losing the focus when your form is getting activated. – Reza Aghaei Feb 20 '21 at 15:55

1 Answers1

0

According to documentations: The Enter and Leave events are suppressed by the Form class. The equivalent events in the Form class are the Activated and Deactivate events.

So here you need to handle Activated event instead of Enter:

Public Class Form1
    Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
        Debug.Print("Activated!")
    End Sub
End Class

Note about your question in the comments: I'm looking for an event that would allow me to still get the GetForegroundWindow() on the current window handle before my app is being activated."Activated" is already too late.

Yes, Activated is too late to find the previous foreground window. I've already answered your other question here: Find handle of the deactivated window when this window has been activated.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398