I am trying to call a very specific command, that I can call through cmd, using a service. I'm using a service because I want this command to run every single time I log in, so I inherit from ServiceBase
.
class Program
{
static void Main(string[] args)
{
ServiceBase.Run(new RestartService());
}
}
public class RestartService : ServiceBase
{
public RestartService()
{
CanHandleSessionChangeEvent = true;
}
protected override void OnStart(string[] args)
{
Log("Starting");
base.OnStart(args);
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
Log($"Session was changed: {changeDescription.Reason}");
if (changeDescription.Reason == SessionChangeReason.SessionLogon || changeDescription.Reason == SessionChangeReason.SessionUnlock)
{
Log("Logon/unlock detected");
try
{
var psi = new ProcessStartInfo()
{
FileName = "C:\\Windows\\system32\\cmd.exe",
Arguments = "/c msg %username% hello",
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var p = Process.Start(psi);
string result = p.StandardOutput.ReadToEnd();
Log(result);
}
catch (Exception e)
{
Log($"ERROR: {e}");
}
}
base.OnSessionChange(changeDescription);
}
public static void Log(string logMessage)
{
using (StreamWriter w = File.AppendText("C:\\Users\\username\\Desktop\\log.txt"))
{
w.Write("\r\nLog Entry : ");
w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
w.WriteLine(" :");
w.WriteLine($" :{logMessage}");
w.WriteLine("-------------------------------");
}
}
}
I have also tried using:
[DllImport("msvcrt.dll")]
public static extern int system(string format);
and then calling system("msg %username% hello")
but unfortunately that doesn't work either.
When I open the log.txt file, I can see this:
Log Entry : 12:29:44 PM Tuesday, September 15, 2020
:
:Session was changed SessionLock
-------------------------------
Log Entry : 12:29:45 PM Tuesday, September 15, 2020
:
:Session was changed SessionUnlock
-------------------------------
Log Entry : 12:29:45 PM Tuesday, September 15, 2020
:
:Logon/unlock detected
-------------------------------
Log Entry : 12:29:45 PM Tuesday, September 15, 2020
:
:
-------------------------------
So I lock the PC, unlock the PC, and then call cmd.exe /c msg %username% hello
. However, the popup doesn't appear. No matter which command I try, it doesn't work.
I did go in and tick the "Allow service to interact with desktop" option, but that unfortunately didn't work either.