1

I have made a simple port listener which listens to a port, and if the sent request is satisfactory, it will put the computer to sleep. The application works when started, however, when I put the computer to sleep, and then wake it up; before unlocking Windows application will not respond. Is there a way to make the application respond even before unlocking Windows? (Python console application will listen even before unlocking, but I don't want a cmd window open in taskbar.)

Code is available below

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace remoteShutdownandOtherStuffServer
{
    public partial class Form1 : Form
    {

        CancellationTokenSource ts = new CancellationTokenSource();
        public Form1()
        {

            InitializeComponent();
            //SystemEvents.PowerModeChanged += OnPowerChange;
        }

        //I have tried adding OnPowerChange event, but to no avail.

        //private void OnPowerChange(object s, PowerModeChangedEventArgs e)
        //{
        //    switch (e.Mode)
        //    {
        //        case PowerModes.Resume:
        //            ts.Cancel();
        //            CancellationToken ct = ts.Token;
        //            Task.Factory.StartNew(() =>
        //            {
        //                remoteShutdownListener(ct);
        //            }, ct);

        //            break;
        //        case PowerModes.Suspend:
        //            break;
        //    }
        //}

        private void remoteShutdownListener(CancellationToken ct)
        {
            TcpListener server = null;
            textBox1.Invoke((MethodInvoker)delegate {
                textBox1.Text = "";
                textBox2.Text = "";
            });
            try
            {
                Int32 port = 10000;
                IPAddress localAddr = IPAddress.Parse("192.168.1.5");
                server = new TcpListener(localAddr, port);
                server.Start();
                Byte[] bytes = new Byte[1024];
                String data = null;
                while (true)
                {
                    if (ct.IsCancellationRequested)
                        break;
                    TcpClient client = server.AcceptTcpClient();
                    data = null;
                    NetworkStream stream = client.GetStream();
                    int i;
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        bool allowed = false;
                        textBox1.Invoke((MethodInvoker)delegate {
                            textBox1.Text += "Received: " + data.ToString();
                            textBox2.Text += client.Client.RemoteEndPoint.ToString() ;
                        });

                        if(data.Contains("go to sleep"))
                        {
                            allowed = true;
                        }

                        var ipStrArray = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString().Split('.');

                        if(allowed && ipStrArray[0] =="192" && ipStrArray[1] == "168" && ipStrArray[2] == "1")
                        {
                            MessageBox.Show("it works");
                            Application.SetSuspendState(PowerState.Hibernate, true, true);
                        }

                    }

                    client.Close();
                }
            }
            catch (Exception exc1)
            {
                //Console.WriteLine("SocketException: {0}", exc1);
            }
            finally
            {
                server.Stop();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            notifyIcon1.Icon = (System.Drawing.Icon)Properties.Resources.remoteIcon;

            CancellationToken ct = ts.Token;
            Task.Factory.StartNew(() =>
            {
                remoteShutdownListener(ct);
            }, ct);

        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
            {
                notifyIcon1.Visible = true;
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                notifyIcon1.Visible = false;
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {
                Close();
            }
            else if (e.Button == MouseButtons.Left)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;

            }
        }

        //private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        //{
        //    this.Show();
        //    this.WindowState = FormWindowState.Normal;
        //}


    }
}
meougal
  • 21
  • 1
  • Without a good [mcve] that reliably reproduces the problem, it's not going to be clear how best to solve the issue. However, the first thing I notice is your use of `Invoke()` to marshal UI operations from your background thread. Try `BeginInvoke()` instead, to allow the background thread to continue to execute even if the UI thread is not responsive (e.g. because there's no active user session). For a more advanced approach, look at splitting your implementation into a Windows service to handle the network stuff, and a separate Winforms program that uses IPC to interact with the service. – Peter Duniho Apr 11 '20 at 23:37
  • 1
    Minimal reproducible example: Put the computer to sleep by sending a request containing "go to sleep". Wake computer up (mouse, keyboard, etc.) Wait for logon screen to appear. Send the request again: Nothing happens. – meougal Apr 11 '20 at 23:40
  • check below question, also i would like to suggest you to use a windows service for this . https://stackoverflow.com/questions/6975206/unlock-windows-programmatically – Deshan Apr 12 '20 at 04:32
  • I think this answers your question https://stackoverflow.com/questions/18206183/event-to-detect-system-wake-up-from-sleep-in-c-sharp – NavalRishi Jul 29 '20 at 08:29

0 Answers0