Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ready for Review - [Mouse Without Borders] - refactoring "Common" classes (Part 4) - #35155 #37579

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
[MouseWithoutBorders] - moving Common.Service.cs -> Core\Service.cs - #…
  • Loading branch information
mikeclayton committed Feb 21, 2025
commit 4885c30103f1ac80968f8c968b190125607446da
161 changes: 0 additions & 161 deletions src/modules/MouseWithoutBorders/App/Class/Common.Service.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/modules/MouseWithoutBorders/App/Class/Common.WinAPI.cs
Original file line number Diff line number Diff line change
@@ -269,7 +269,7 @@ internal static void StartMMService(string desktopToRunMouseWithoutBordersOn)
if (!Common.RunWithNoAdminRight)
{
Logger.LogDebug("*** Starting on active Desktop: " + desktopToRunMouseWithoutBordersOn);
StartMouseWithoutBordersService(desktopToRunMouseWithoutBordersOn);
Service.StartMouseWithoutBordersService(desktopToRunMouseWithoutBordersOn);
}
}

2 changes: 1 addition & 1 deletion src/modules/MouseWithoutBorders/App/Class/Program.cs
Original file line number Diff line number Diff line change
@@ -430,7 +430,7 @@ internal static void StartService()
Logger.Log(e);
}

Common.StartMouseWithoutBordersService();
Service.StartMouseWithoutBordersService();
}

internal static string User { get; set; }
159 changes: 159 additions & 0 deletions src/modules/MouseWithoutBorders/App/Core/Service.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Windows.Forms;

// <summary>
// Service control code.
// </summary>
// <history>
// 2008 created by Truong Do (ductdo).
// 2009-... modified by Truong Do (TruongDo).
// 2023- Included in PowerToys.
// </history>
using MouseWithoutBorders.Class;

[module: SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Scope = "member", Target = "MouseWithoutBorders.Common.#StartMouseWithoutBordersService()", Justification = "Dotnet port with style preservation")]

namespace MouseWithoutBorders.Core;

internal static class Service
{
private static bool shownErrMessage;
private static DateTime lastStartServiceTime = DateTime.UtcNow;

internal static void StartMouseWithoutBordersService(string desktopToRunMouseWithoutBordersOn = null, string startTag1 = "byapp", string startTag2 = null)
{
// NOTE(@yuyoyuppe): the new flow assumes we run both mwb processes directly from the svc.
if (Common.RunWithNoAdminRight || true)
Copy link
Preview

Copilot AI Feb 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use of '|| true' in the conditional always evaluates to true, bypassing the intended service start logic. Consider removing '|| true' or revising the condition to properly control service startup.

Suggested change
if (Common.RunWithNoAdminRight || true)
if (Common.RunWithNoAdminRight)

Copilot is powered by AI, so mistakes are possible. Review output carefully before use.

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (Common.RunWithNoAdminRight || true) was in the original Common.Service.cs file - Copilot's detected it as it thinks Service.cs is a new file rather than a rename and is treating this as a "new" issue. I'd suggest leaving as-is for this PR.

{
return;
}

Logger.Log($"{nameof(StartMouseWithoutBordersService)}: {Logger.GetStackTrace(new StackTrace())}.");

Task task = Task.Run(() =>
{
Process[] ps = Process.GetProcessesByName("MouseWithoutBordersSvc");

if (ps.Length != 0)
{
if (DateTime.UtcNow - lastStartServiceTime < TimeSpan.FromSeconds(5))
{
Logger.Log($"{nameof(StartMouseWithoutBordersService)}: Aborted.");
return;
}

foreach (Process pp in ps)
{
Logger.Log(string.Format(CultureInfo.InvariantCulture, "Killing process MouseWithoutBordersSvc {0}.", pp.Id));
pp.KillProcess();
}
}

lastStartServiceTime = DateTime.UtcNow;
ServiceController service = new("MouseWithoutBordersSvc");

try
{
Logger.Log("Starting " + service.ServiceName);
}
catch (Exception)
{
if (!shownErrMessage)
{
shownErrMessage = true;
_ = MessageBox.Show(
Application.ProductName + " is not installed yet, please run Setup.exe first!",
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}

return;
}

try
{
int c = 0;

while (service.Status != ServiceControllerStatus.Stopped && c++ < 5)
{
Thread.Sleep(1000);
service = new ServiceController("MouseWithoutBordersSvc");
}

if (string.IsNullOrWhiteSpace(desktopToRunMouseWithoutBordersOn))
{
startTag2 ??= Process.GetCurrentProcess().SessionId.ToString(CultureInfo.InvariantCulture);
service.Start(new string[] { startTag1, startTag2 });
}
else
{
service.Start(new string[] { desktopToRunMouseWithoutBordersOn });
}
}
catch (Exception e)
{
Logger.Log(e);

// ERROR_SERVICE_ALREADY_RUNNING
if (!(shownErrMessage || ((e?.InnerException as Win32Exception)?.NativeErrorCode == 1056)))
{
shownErrMessage = true;
_ = MessageBox.Show(
"Cannot start service " + service.ServiceName + ": " + e.Message,
Common.BinaryName,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}

return;
}
});

// Wait for the task while not blocking the UI thread.
do
{
Common.MMSleep(1);

if (task.IsCanceled || task.IsCompleted || task.IsFaulted)
{
break;
}
}
while (true);
}

internal static void StartServiceAndSendLogoffSignal()
{
try
{
Process[] p = Process.GetProcessesByName("winlogon");
Process me = Process.GetCurrentProcess();
string myWinlogon = p?.FirstOrDefault(item => item.SessionId == me.SessionId)?.Id.ToString(CultureInfo.InvariantCulture) ?? null;

if (string.IsNullOrWhiteSpace(myWinlogon))
{
StartMouseWithoutBordersService(null, "logoff");
}
else
{
StartMouseWithoutBordersService(null, "logoff", myWinlogon);
}
}
catch (Exception e)
{
Logger.Log($"{nameof(StartServiceAndSendLogoffSignal)}: {e.Message}");
}
}
}
4 changes: 2 additions & 2 deletions src/modules/MouseWithoutBorders/App/Form/frmScreen.cs
Original file line number Diff line number Diff line change
@@ -101,7 +101,7 @@ private void FrmScreen_FormClosing(object sender, FormClosingEventArgs e)
}
else
{
Common.StartServiceAndSendLogoffSignal();
Service.StartServiceAndSendLogoffSignal();
Quit(true, true);
}
}
@@ -831,7 +831,7 @@ protected override void WndProc(ref Message m)

case WM_QUERYENDSESSION:
Logger.LogDebug("WM_QUERYENDSESSION...");
Common.StartServiceAndSendLogoffSignal();
Service.StartServiceAndSendLogoffSignal();
break;

case WM_ENDSESSION: