Alex
Alex

Reputation: 2609

DNS error during making network connection in background C# WinForms app on Windows logon screen

I have an application which makes network connections every 2 minutes. The app is not a Windows service, it's being run under the context of the current Windows user.

If Windows goes to Sleep mode and then wakes up (so that Windows logon screen gets displayed), I later see in the logs that any connection attempt my app makes fails with "The remote name could not be resolved" WebException. This error happens during the time the logon screen is active. Later, when the user logs in, they see my app complaining that "an error occurred".

Is it documented somewhere (that background apps cannot access network if they are executed under the context of the user which has the open session on this computer but currently this session is locked)? And can I detect this situation in my C# application (and don't try to access network if logon screen is active)?

Also, maybe there are more similar situations around which I should take of? I mean maybe I shouldn't check if logon screen is active, maybe there is a more universal approach, such as a WinAPI function which just tells me if Windows is in the state when I'm allowed to do things like accessing the network.

At the same time, I don't want just the function "network is available" because it wouldn't let me understand if there is no network at all (this is error for my app) or just that network is not available right now because the computer is locked or something (there is no error, I just should retry later).

I'm testing this on Windows 7 SP1 64-bit but I suspect this behavior can be consistent across all the versions and I need to find the way to handle it gracefully.

Upvotes: 1

Views: 78

Answers (1)

adrianbanks
adrianbanks

Reputation: 83004

To stop your application from trying to access the network, take a look at SystemEvents.SessionSwitch.

If you hook an event handler up to that, an event will fire every time the session changes. The properties of the event args will tell you whether the session is being locked/unlocked. You can then stop/start your network access as needed.

For example:

private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionLock)
    {
        // session was locked
    }
    else if (e.Reason == SessionSwitchReason.SessionUnlock)
    {
        // session was unlocked
    }
}

There are a few other reasons that can be handled also:

  • RemoteConnect/RemoteDisconnect for remote desktop connections
  • ConsoleConnect/ConsoleDisconnect for remote desktop connections directly to the console (mstsc /console)

Upvotes: 1

Related Questions