Running Processes When Your Screen is Locked Only Using C#

Imagine the following situation. You have a heavy process that execute some tasks not so important during your regular day. However, you would like to keep this processing running when your screen is locked and kill when your screen is unlocked.

A typical example is mining blockchains. Some cryptocoins like Monero can be mined using CPU .. yeah.. I know GPUs are better but mining Monero is still feasible using CPUs (specially Intel Xeon).

This is a very simple but useful software written in C# and runs as a hidden Windows console application in order to avoid any annoyance.

using System;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace dws
{
    class Program
    {

        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_HIDE = 0;
        const int SW_SHOW = 5;

        private static SessionSwitchEventHandler sseh;

        static void Main(string[] args)
        {

            var handle = GetConsoleWindow();
            ShowWindow(handle, SW_HIDE);

            sseh = new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
            SystemEvents.SessionSwitch += sseh;

            while (true) {
                System.Threading.Thread.Sleep(2000);
            }

        }

        static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                //desktop locked
                startMiner();
            }
            else if (e.Reason == SessionSwitchReason.SessionUnlock)
            {
                //desktop unlocked
                killProcess();
            }

        }

        private static void startMiner()
        {
            
            Process process = new Process();
            process.StartInfo.FileName = "your_process.exe";
            process.StartInfo.Arguments = "your_arguments";
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.Start();
            
        }

        private static void killProcess()
        {
            try
            {
                foreach (Process proc in Process.GetProcessesByName("your_process"))
                {
                    proc.Kill();
                }
            }
            catch (Exception ex)
            {
            }
        }


    }
}