WinForms application stops working if the computer goes into hibernation

3

I have an application in winforms , which stays on the company server, then I pull the shortcut to the work area and the employee runs normally.

The problem began to happen, when we switched some computers (Desktop) to notebook computers, when the notebook goes into hibernation, when the application returns to work.

At the moment, I make a palliative solution, which I detect when windows is about to hibernate and I finish the application, but that's not quite right ..

Would anyone have another alternative? or could you give me some hint?

    
asked by anonymous 18.05.2018 / 20:33

1 answer

1

You can make your application not allow windows to hibernate while it is open. Something like this:

public partial class Window1 : Window
{
    private uint m_previousExecutionState;

    public Window1()
    {
        InitializeComponent();

        // Set new state to prevent system sleep (note: still allows screen saver)
        m_previousExecutionState = NativeMethods.SetThreadExecutionState(
            NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
        if (0 == m_previousExecutionState)
        {
            MessageBox.Show("Call to SetThreadExecutionState failed unexpectedly.",
                Title, MessageBoxButton.OK, MessageBoxImage.Error);
            // No way to recover; fail gracefully
            Close();
        }
    }

    protected override void OnClosed(System.EventArgs e)
    {
        base.OnClosed(e);

        // Restore previous state
        if (0 == NativeMethods.SetThreadExecutionState(m_previousExecutionState))
        {
            // No way to recover; already exiting
        }
    }
}

internal static class NativeMethods
{
    // Import SetThreadExecutionState Win32 API and necessary flags
    [DllImport("kernel32.dll")]
    public static extern uint SetThreadExecutionState(uint esFlags);
    public const uint ES_CONTINUOUS = 0x80000000;
    public const uint ES_SYSTEM_REQUIRED = 0x00000001;
}
    
18.05.2018 / 22:15