Compare commits
17 Commits
498251ad79
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30da1680f2 | ||
|
|
ad9a9021cc | ||
|
|
4f6c1e2060 | ||
|
|
cbbadd547d | ||
|
|
32ef8fb1ac | ||
|
|
0611966be9 | ||
|
|
4caa21c4d2 | ||
|
|
4f6e817a76 | ||
|
|
1b335d720d | ||
|
|
046a27ecf9 | ||
|
|
0c2cbbfccd | ||
|
|
ddd15f1067 | ||
|
|
6b3e8e02f2 | ||
|
|
1b4267a6ff | ||
|
|
a6602206c5 | ||
|
|
d4b7a23e38 | ||
|
|
4c314c510b |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,10 +1,11 @@
|
|||||||
bin/
|
bin/
|
||||||
obj/
|
obj/
|
||||||
|
publish/
|
||||||
.vs/
|
.vs/
|
||||||
.vscode/
|
.vscode/
|
||||||
*.user
|
*.user
|
||||||
*.suo
|
*.suo
|
||||||
*.log
|
*.log
|
||||||
|
*.lscache
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
|
|
||||||
|
|||||||
22
README.md
22
README.md
@@ -18,3 +18,25 @@ dotnet run --project .\WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csp
|
|||||||
|
|
||||||
The initial server listens on `ws://0.0.0.0:8181`.
|
The initial server listens on `ws://0.0.0.0:8181`.
|
||||||
|
|
||||||
|
## Release Build
|
||||||
|
|
||||||
|
Build a Windows x64 single-file executable:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dotnet publish .\WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csproj `
|
||||||
|
-c Release `
|
||||||
|
-r win-x64 `
|
||||||
|
--self-contained true `
|
||||||
|
-p:PublishSingleFile=true `
|
||||||
|
-p:EnableCompressionInSingleFile=true `
|
||||||
|
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||||
|
-o .\publish\win-x64-single
|
||||||
|
```
|
||||||
|
|
||||||
|
The runnable app is written to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
publish\win-x64-single\WirelessTextSyncer.Windows.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
This build includes the .NET runtime, so the target Windows machine does not need .NET installed. The generated `.pdb` file is only for debugging and is not required to run the app.
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ VisualStudioVersion = 17.0.31903.59
|
|||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WirelessTextSyncer.Windows", "WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csproj", "{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WirelessTextSyncer.Windows", "WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csproj", "{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WirelessTextSyncer.Windows.Tests", "WirelessTextSyncer.Windows.Tests\WirelessTextSyncer.Windows.Tests.csproj", "{FD53F0F1-EAE0-4CB2-9AC8-57797F0B95D1}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -18,5 +20,9 @@ Global
|
|||||||
{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}.Release|Any CPU.Build.0 = Release|Any CPU
|
{7AD6081A-F4EB-45AA-917B-2CCFA54E0A67}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{FD53F0F1-EAE0-4CB2-9AC8-57797F0B95D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{FD53F0F1-EAE0-4CB2-9AC8-57797F0B95D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{FD53F0F1-EAE0-4CB2-9AC8-57797F0B95D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{FD53F0F1-EAE0-4CB2-9AC8-57797F0B95D1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|||||||
154
WirelessTextSyncer.Windows.Tests/SyncMessageTests.cs
Normal file
154
WirelessTextSyncer.Windows.Tests/SyncMessageTests.cs
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using WirelessTextSyncer.Windows.Models;
|
||||||
|
using WirelessTextSyncer.Windows.Services;
|
||||||
|
|
||||||
|
namespace WirelessTextSyncer.Windows.Tests;
|
||||||
|
|
||||||
|
[TestClass]
|
||||||
|
public sealed class SyncMessageTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void DeserializeAndroidInsertTextMessage()
|
||||||
|
{
|
||||||
|
var message = JsonSerializer.Deserialize<SyncMessage>(
|
||||||
|
"""{"action":"insertText","text":"hello"}""",
|
||||||
|
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||||
|
|
||||||
|
Assert.IsNotNull(message);
|
||||||
|
Assert.AreEqual(SyncAction.InsertText, message.Action);
|
||||||
|
Assert.AreEqual("hello", message.Text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DeserializeAndroidBackspaceMessage()
|
||||||
|
{
|
||||||
|
var message = JsonSerializer.Deserialize<SyncMessage>(
|
||||||
|
"""{"action":"backspace"}""",
|
||||||
|
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||||
|
|
||||||
|
Assert.IsNotNull(message);
|
||||||
|
Assert.AreEqual(SyncAction.Backspace, message.Action);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DeserializeAndroidReplaceAllMessage()
|
||||||
|
{
|
||||||
|
var message = JsonSerializer.Deserialize<SyncMessage>(
|
||||||
|
"""{"action":"replaceAll","text":"final text"}""",
|
||||||
|
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||||
|
|
||||||
|
Assert.IsNotNull(message);
|
||||||
|
Assert.AreEqual(SyncAction.ReplaceAll, message.Action);
|
||||||
|
Assert.AreEqual("final text", message.Text);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ReplaceAllAppendsSubmittedText()
|
||||||
|
{
|
||||||
|
var keyboard = new RecordingKeyboardInjectionService();
|
||||||
|
var handler = new SyncMessageHandler(keyboard, new RecordingAudioControlService());
|
||||||
|
|
||||||
|
handler.Handle(new SyncMessage
|
||||||
|
{
|
||||||
|
Action = SyncAction.ReplaceAll,
|
||||||
|
Text = "final text"
|
||||||
|
});
|
||||||
|
|
||||||
|
CollectionAssert.AreEqual(
|
||||||
|
new[] { "insert:final text" },
|
||||||
|
keyboard.Calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DeserializeAndroidSetMuteMessage()
|
||||||
|
{
|
||||||
|
var message = JsonSerializer.Deserialize<SyncMessage>(
|
||||||
|
"""{"action":"setMute","muted":true}""",
|
||||||
|
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||||
|
|
||||||
|
Assert.IsNotNull(message);
|
||||||
|
Assert.AreEqual(SyncAction.SetMute, message.Action);
|
||||||
|
Assert.AreEqual(true, message.Muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SetMuteForwardsToAudioService()
|
||||||
|
{
|
||||||
|
var audio = new RecordingAudioControlService();
|
||||||
|
var handler = new SyncMessageHandler(new RecordingKeyboardInjectionService(), audio);
|
||||||
|
|
||||||
|
handler.Handle(new SyncMessage
|
||||||
|
{
|
||||||
|
Action = SyncAction.SetMute,
|
||||||
|
Muted = true
|
||||||
|
});
|
||||||
|
|
||||||
|
CollectionAssert.AreEqual(new[] { "mute:True" }, audio.Calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DiscoveryResponseContainsServiceEndpoint()
|
||||||
|
{
|
||||||
|
using var discovery = new DiscoveryResponderService(() => "192.168.1.10", () => 8181, "Desktop-WIN11");
|
||||||
|
|
||||||
|
using var document = JsonDocument.Parse(discovery.BuildResponseJson());
|
||||||
|
var root = document.RootElement;
|
||||||
|
|
||||||
|
Assert.AreEqual("wirelessTextSyncer.service", root.GetProperty("type").GetString());
|
||||||
|
Assert.AreEqual(1, root.GetProperty("version").GetInt32());
|
||||||
|
Assert.AreEqual("Desktop-WIN11", root.GetProperty("name").GetString());
|
||||||
|
Assert.AreEqual("192.168.1.10", root.GetProperty("host").GetString());
|
||||||
|
Assert.AreEqual(8181, root.GetProperty("port").GetInt32());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void WebSocketServiceInfoContainsDeviceName()
|
||||||
|
{
|
||||||
|
using var server = new WebSocketServerService(new SyncMessageHandler(new RecordingKeyboardInjectionService(), new RecordingAudioControlService()), "Desktop-WIN11");
|
||||||
|
|
||||||
|
using var document = JsonDocument.Parse(server.BuildServiceInfoJson());
|
||||||
|
var root = document.RootElement;
|
||||||
|
|
||||||
|
Assert.AreEqual("wirelessTextSyncer.service", root.GetProperty("type").GetString());
|
||||||
|
Assert.AreEqual(1, root.GetProperty("version").GetInt32());
|
||||||
|
Assert.AreEqual("Desktop-WIN11", root.GetProperty("name").GetString());
|
||||||
|
Assert.AreEqual(8181, root.GetProperty("port").GetInt32());
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingKeyboardInjectionService : IKeyboardInjectionService
|
||||||
|
{
|
||||||
|
public List<string> Calls { get; } = [];
|
||||||
|
|
||||||
|
public void InsertText(string text)
|
||||||
|
{
|
||||||
|
Calls.Add($"insert:{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ReplaceFocusedText(string text)
|
||||||
|
{
|
||||||
|
Calls.Add($"replace:{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Backspace()
|
||||||
|
{
|
||||||
|
Calls.Add("backspace");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Enter()
|
||||||
|
{
|
||||||
|
Calls.Add("enter");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingAudioControlService : IAudioControlService
|
||||||
|
{
|
||||||
|
public List<string> Calls { get; } = [];
|
||||||
|
|
||||||
|
public bool IsMuted => Calls.Count > 0 && Calls[^1] == "mute:True";
|
||||||
|
|
||||||
|
public void SetMute(bool muted)
|
||||||
|
{
|
||||||
|
Calls.Add($"mute:{muted}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0-windows</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||||
|
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
|
||||||
|
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\WirelessTextSyncer.Windows\WirelessTextSyncer.Windows.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
namespace WirelessTextSyncer.Windows.Models;
|
namespace WirelessTextSyncer.Windows.Models;
|
||||||
|
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
[JsonConverter(typeof(SyncActionJsonConverter))]
|
||||||
public enum SyncAction
|
public enum SyncAction
|
||||||
{
|
{
|
||||||
InsertText,
|
InsertText,
|
||||||
|
ReplaceAll,
|
||||||
Backspace,
|
Backspace,
|
||||||
Enter,
|
Enter,
|
||||||
Ping
|
Ping,
|
||||||
|
SetMute
|
||||||
}
|
}
|
||||||
|
|||||||
45
WirelessTextSyncer.Windows/Models/SyncActionJsonConverter.cs
Normal file
45
WirelessTextSyncer.Windows/Models/SyncActionJsonConverter.cs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace WirelessTextSyncer.Windows.Models;
|
||||||
|
|
||||||
|
public sealed class SyncActionJsonConverter : JsonConverter<SyncAction>
|
||||||
|
{
|
||||||
|
public override SyncAction Read(
|
||||||
|
ref Utf8JsonReader reader,
|
||||||
|
Type typeToConvert,
|
||||||
|
JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
var value = reader.GetString();
|
||||||
|
|
||||||
|
return value switch
|
||||||
|
{
|
||||||
|
"insertText" => SyncAction.InsertText,
|
||||||
|
"replaceAll" => SyncAction.ReplaceAll,
|
||||||
|
"backspace" => SyncAction.Backspace,
|
||||||
|
"enter" => SyncAction.Enter,
|
||||||
|
"ping" => SyncAction.Ping,
|
||||||
|
"setMute" => SyncAction.SetMute,
|
||||||
|
_ => throw new JsonException($"Unsupported sync action: {value}")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Write(
|
||||||
|
Utf8JsonWriter writer,
|
||||||
|
SyncAction value,
|
||||||
|
JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
var action = value switch
|
||||||
|
{
|
||||||
|
SyncAction.InsertText => "insertText",
|
||||||
|
SyncAction.ReplaceAll => "replaceAll",
|
||||||
|
SyncAction.Backspace => "backspace",
|
||||||
|
SyncAction.Enter => "enter",
|
||||||
|
SyncAction.Ping => "ping",
|
||||||
|
SyncAction.SetMute => "setMute",
|
||||||
|
_ => throw new JsonException($"Unsupported sync action: {value}")
|
||||||
|
};
|
||||||
|
|
||||||
|
writer.WriteStringValue(action);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,4 +9,7 @@ public sealed record SyncMessage
|
|||||||
|
|
||||||
[JsonPropertyName("text")]
|
[JsonPropertyName("text")]
|
||||||
public string? Text { get; init; }
|
public string? Text { get; init; }
|
||||||
|
|
||||||
|
[JsonPropertyName("muted")]
|
||||||
|
public bool? Muted { get; init; }
|
||||||
}
|
}
|
||||||
|
|||||||
BIN
WirelessTextSyncer.Windows/Resources/Icons/app-icon.png
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/app-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 106 KiB |
BIN
WirelessTextSyncer.Windows/Resources/Icons/app.ico
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/app.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-connected.png
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-connected.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-wait.png
Normal file
BIN
WirelessTextSyncer.Windows/Resources/Icons/tray-wait.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.7 KiB |
32
WirelessTextSyncer.Windows/Services/AppLogger.cs
Normal file
32
WirelessTextSyncer.Windows/Services/AppLogger.cs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
namespace WirelessTextSyncer.Windows.Services;
|
||||||
|
|
||||||
|
public static class AppLogger
|
||||||
|
{
|
||||||
|
private static readonly object SyncRoot = new();
|
||||||
|
private static readonly string LogDirectory = Path.Combine(
|
||||||
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||||
|
"WirelessTextSyncer");
|
||||||
|
|
||||||
|
public static string LogPath => Path.Combine(LogDirectory, "desktop.log");
|
||||||
|
|
||||||
|
public static void Info(string message)
|
||||||
|
{
|
||||||
|
Write("INFO", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Error(string message, Exception? exception = null)
|
||||||
|
{
|
||||||
|
Write("ERROR", exception is null ? message : $"{message}{Environment.NewLine}{exception}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Write(string level, string message)
|
||||||
|
{
|
||||||
|
lock (SyncRoot)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(LogDirectory);
|
||||||
|
File.AppendAllText(
|
||||||
|
LogPath,
|
||||||
|
$"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff zzz} [{level}] {message}{Environment.NewLine}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
52
WirelessTextSyncer.Windows/Services/AudioControlService.cs
Normal file
52
WirelessTextSyncer.Windows/Services/AudioControlService.cs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using NAudio.CoreAudioApi;
|
||||||
|
|
||||||
|
namespace WirelessTextSyncer.Windows.Services;
|
||||||
|
|
||||||
|
public sealed class AudioControlService : IAudioControlService, IDisposable
|
||||||
|
{
|
||||||
|
private readonly MMDeviceEnumerator enumerator = new();
|
||||||
|
private bool disposed;
|
||||||
|
|
||||||
|
public bool IsMuted
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
|
||||||
|
return device.AudioEndpointVolume.Mute;
|
||||||
|
}
|
||||||
|
catch (COMException exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error("Failed to read audio mute state.", exception);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetMute(bool muted)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
|
||||||
|
device.AudioEndpointVolume.Mute = muted;
|
||||||
|
AppLogger.Info($"Audio mute set to {muted}.");
|
||||||
|
}
|
||||||
|
catch (COMException exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error($"Failed to set audio mute to {muted}.", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
disposed = true;
|
||||||
|
enumerator.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
115
WirelessTextSyncer.Windows/Services/DiscoveryResponderService.cs
Normal file
115
WirelessTextSyncer.Windows/Services/DiscoveryResponderService.cs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace WirelessTextSyncer.Windows.Services;
|
||||||
|
|
||||||
|
public sealed class DiscoveryResponderService : IDisposable
|
||||||
|
{
|
||||||
|
public const int DiscoveryPort = 8182;
|
||||||
|
public const string DiscoveryRequestType = "wirelessTextSyncer.discovery";
|
||||||
|
public const string ServiceResponseType = "wirelessTextSyncer.service";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||||
|
private readonly Func<string> hostProvider;
|
||||||
|
private readonly Func<int> portProvider;
|
||||||
|
private readonly string deviceName;
|
||||||
|
private readonly CancellationTokenSource cancellation = new();
|
||||||
|
private UdpClient? udpClient;
|
||||||
|
private Task? listenTask;
|
||||||
|
|
||||||
|
public DiscoveryResponderService(Func<string> hostProvider, Func<int> portProvider, string? deviceName = null)
|
||||||
|
{
|
||||||
|
this.hostProvider = hostProvider;
|
||||||
|
this.portProvider = portProvider;
|
||||||
|
this.deviceName = string.IsNullOrWhiteSpace(deviceName) ? Environment.MachineName : deviceName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start()
|
||||||
|
{
|
||||||
|
if (udpClient is not null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
udpClient = new UdpClient(AddressFamily.InterNetwork);
|
||||||
|
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||||
|
udpClient.EnableBroadcast = true;
|
||||||
|
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryPort));
|
||||||
|
listenTask = Task.Run(ListenAsync);
|
||||||
|
AppLogger.Info($"Discovery responder listening on UDP {DiscoveryPort}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
cancellation.Cancel();
|
||||||
|
udpClient?.Dispose();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
listenTask?.Wait(TimeSpan.FromSeconds(1));
|
||||||
|
}
|
||||||
|
catch (AggregateException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
cancellation.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string BuildResponseJson()
|
||||||
|
{
|
||||||
|
return JsonSerializer.Serialize(
|
||||||
|
new DiscoveryResponse(ServiceResponseType, 1, deviceName, hostProvider(), portProvider()),
|
||||||
|
JsonOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ListenAsync()
|
||||||
|
{
|
||||||
|
var token = cancellation.Token;
|
||||||
|
while (!token.IsCancellationRequested && udpClient is not null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await udpClient.ReceiveAsync(token);
|
||||||
|
if (!IsDiscoveryRequest(result.Buffer))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var responseBytes = Encoding.UTF8.GetBytes(BuildResponseJson());
|
||||||
|
await udpClient.SendAsync(responseBytes, result.RemoteEndPoint, token);
|
||||||
|
AppLogger.Info($"Answered discovery request from {result.RemoteEndPoint}.");
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error("Discovery responder failed to process a packet.", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsDiscoveryRequest(byte[] bytes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var request = JsonSerializer.Deserialize<DiscoveryRequest>(bytes, JsonOptions);
|
||||||
|
return request?.Type == DiscoveryRequestType && request.Version == 1;
|
||||||
|
}
|
||||||
|
catch (JsonException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record DiscoveryRequest(string Type, int Version);
|
||||||
|
|
||||||
|
private sealed record DiscoveryResponse(string Type, int Version, string Name, string Host, int Port);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace WirelessTextSyncer.Windows.Services;
|
||||||
|
|
||||||
|
public interface IAudioControlService
|
||||||
|
{
|
||||||
|
bool IsMuted { get; }
|
||||||
|
|
||||||
|
void SetMute(bool muted);
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ public interface IKeyboardInjectionService
|
|||||||
{
|
{
|
||||||
void InsertText(string text);
|
void InsertText(string text);
|
||||||
|
|
||||||
|
void ReplaceFocusedText(string text);
|
||||||
|
|
||||||
void Backspace();
|
void Backspace();
|
||||||
|
|
||||||
void Enter();
|
void Enter();
|
||||||
|
|||||||
@@ -1,7 +1,29 @@
|
|||||||
namespace WirelessTextSyncer.Windows.Services;
|
namespace WirelessTextSyncer.Windows.Services;
|
||||||
|
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
public enum TextInjectionMode
|
||||||
|
{
|
||||||
|
ClipboardPaste,
|
||||||
|
SendInputTyping
|
||||||
|
}
|
||||||
|
|
||||||
public sealed class KeyboardInjectionService : IKeyboardInjectionService
|
public sealed class KeyboardInjectionService : IKeyboardInjectionService
|
||||||
{
|
{
|
||||||
|
private const uint InputKeyboard = 1;
|
||||||
|
private const uint KeyEventFKeyUp = 0x0002;
|
||||||
|
private const uint KeyEventFUnicode = 0x0004;
|
||||||
|
private const uint KlfActivate = 0x00000001;
|
||||||
|
private const uint WmInputLangChangeRequest = 0x0050;
|
||||||
|
private const ushort VirtualKeyA = 0x41;
|
||||||
|
private const ushort VirtualKeyBack = 0x08;
|
||||||
|
private const ushort VirtualKeyControl = 0x11;
|
||||||
|
private const ushort VirtualKeyReturn = 0x0D;
|
||||||
|
private const ushort VirtualKeyV = 0x56;
|
||||||
|
private static readonly IntPtr EnglishKeyboardLayout = LoadKeyboardLayout("00000409", KlfActivate);
|
||||||
|
|
||||||
|
public TextInjectionMode Mode { get; set; } = TextInjectionMode.ClipboardPaste;
|
||||||
|
|
||||||
public void InsertText(string text)
|
public void InsertText(string text)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(text))
|
if (string.IsNullOrEmpty(text))
|
||||||
@@ -9,16 +31,289 @@ public sealed class KeyboardInjectionService : IKeyboardInjectionService
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
SendKeys.SendWait(text);
|
AppLogger.Info($"Inserting text length: {text.Length}. Mode: {Mode}.");
|
||||||
|
if (Mode == TextInjectionMode.SendInputTyping)
|
||||||
|
{
|
||||||
|
TypeTextWithSendInput(text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
PasteTextViaClipboard(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TypeTextWithSendInput(string text)
|
||||||
|
{
|
||||||
|
AppLogger.Info($"Falling back to SendInput text length: {text.Length}");
|
||||||
|
using var keyboardLayoutScope = KeyboardLayoutScope.SwitchForegroundWindowToEnglish();
|
||||||
|
foreach (var character in text)
|
||||||
|
{
|
||||||
|
AppLogger.Info($"Injecting char U+{(int)character:X4}: {character}");
|
||||||
|
SendUnicode(character);
|
||||||
|
Thread.Sleep(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PasteTextViaClipboard(string text)
|
||||||
|
{
|
||||||
|
Exception? failure = null;
|
||||||
|
var thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
PasteTextOnStaThread(text);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
failure = ex;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
thread.SetApartmentState(ApartmentState.STA);
|
||||||
|
thread.Start();
|
||||||
|
thread.Join();
|
||||||
|
|
||||||
|
if (failure is not null)
|
||||||
|
{
|
||||||
|
AppLogger.Error("Clipboard paste failed.", failure);
|
||||||
|
TypeTextWithSendInput(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PasteTextOnStaThread(string text)
|
||||||
|
{
|
||||||
|
var hadText = Clipboard.ContainsText(TextDataFormat.UnicodeText);
|
||||||
|
var previousText = hadText ? Clipboard.GetText(TextDataFormat.UnicodeText) : null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Clipboard.SetText(text, TextDataFormat.UnicodeText);
|
||||||
|
Thread.Sleep(30);
|
||||||
|
SendModifiedKey(VirtualKeyControl, VirtualKeyV);
|
||||||
|
Thread.Sleep(150);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
RestoreClipboardText(hadText, previousText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RestoreClipboardText(bool hadText, string? previousText)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (hadText && previousText is not null)
|
||||||
|
{
|
||||||
|
Clipboard.SetText(previousText, TextDataFormat.UnicodeText);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Clipboard.Clear();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
AppLogger.Error("Failed to restore clipboard text.", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ReplaceFocusedText(string text)
|
||||||
|
{
|
||||||
|
AppLogger.Info($"Replacing focused text length: {text.Length}");
|
||||||
|
SendModifiedKey(VirtualKeyControl, VirtualKeyA);
|
||||||
|
Backspace();
|
||||||
|
InsertText(text);
|
||||||
|
AppLogger.Info("Finished replacing focused text.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Backspace()
|
public void Backspace()
|
||||||
{
|
{
|
||||||
SendKeys.SendWait("{BACKSPACE}");
|
AppLogger.Info("Injecting backspace.");
|
||||||
|
SendVirtualKey(VirtualKeyBack);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Enter()
|
public void Enter()
|
||||||
{
|
{
|
||||||
SendKeys.SendWait("{ENTER}");
|
AppLogger.Info("Injecting enter.");
|
||||||
|
SendVirtualKey(VirtualKeyReturn);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SendUnicode(char character)
|
||||||
|
{
|
||||||
|
Send([
|
||||||
|
CreateUnicodeInput(character, 0),
|
||||||
|
CreateUnicodeInput(character, KeyEventFKeyUp)
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SendVirtualKey(ushort virtualKey)
|
||||||
|
{
|
||||||
|
Send([
|
||||||
|
CreateVirtualKeyInput(virtualKey, 0),
|
||||||
|
CreateVirtualKeyInput(virtualKey, KeyEventFKeyUp)
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SendModifiedKey(ushort modifierKey, ushort key)
|
||||||
|
{
|
||||||
|
Send([
|
||||||
|
CreateVirtualKeyInput(modifierKey, 0),
|
||||||
|
CreateVirtualKeyInput(key, 0),
|
||||||
|
CreateVirtualKeyInput(key, KeyEventFKeyUp),
|
||||||
|
CreateVirtualKeyInput(modifierKey, KeyEventFKeyUp)
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Send(INPUT[] inputs)
|
||||||
|
{
|
||||||
|
var sent = SendInput((uint)inputs.Length, inputs, Marshal.SizeOf<INPUT>());
|
||||||
|
if (sent != inputs.Length)
|
||||||
|
{
|
||||||
|
var error = Marshal.GetLastWin32Error();
|
||||||
|
AppLogger.Error(
|
||||||
|
$"Windows accepted {sent}/{inputs.Length} keyboard input events. Win32 error: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static INPUT CreateUnicodeInput(char character, uint flags)
|
||||||
|
{
|
||||||
|
return new INPUT
|
||||||
|
{
|
||||||
|
type = InputKeyboard,
|
||||||
|
U = new InputUnion
|
||||||
|
{
|
||||||
|
ki = new KEYBDINPUT
|
||||||
|
{
|
||||||
|
wScan = character,
|
||||||
|
dwFlags = KeyEventFUnicode | flags
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static INPUT CreateVirtualKeyInput(ushort virtualKey, uint flags)
|
||||||
|
{
|
||||||
|
return new INPUT
|
||||||
|
{
|
||||||
|
type = InputKeyboard,
|
||||||
|
U = new InputUnion
|
||||||
|
{
|
||||||
|
ki = new KEYBDINPUT
|
||||||
|
{
|
||||||
|
wVk = virtualKey,
|
||||||
|
dwFlags = flags
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
private static extern uint SendInput(uint numberOfInputs, INPUT[] inputs, int sizeOfInputStructure);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern IntPtr GetForegroundWindow();
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern uint GetWindowThreadProcessId(IntPtr windowHandle, out uint processId);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern IntPtr GetKeyboardLayout(uint threadId);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||||
|
private static extern IntPtr LoadKeyboardLayout(string keyboardLayoutId, uint flags);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
private static extern bool PostMessage(IntPtr windowHandle, uint message, IntPtr wParam, IntPtr lParam);
|
||||||
|
|
||||||
|
private sealed class KeyboardLayoutScope : IDisposable
|
||||||
|
{
|
||||||
|
private readonly IntPtr foregroundWindow;
|
||||||
|
private readonly IntPtr originalKeyboardLayout;
|
||||||
|
|
||||||
|
private KeyboardLayoutScope(IntPtr foregroundWindow, IntPtr originalKeyboardLayout)
|
||||||
|
{
|
||||||
|
this.foregroundWindow = foregroundWindow;
|
||||||
|
this.originalKeyboardLayout = originalKeyboardLayout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static KeyboardLayoutScope SwitchForegroundWindowToEnglish()
|
||||||
|
{
|
||||||
|
var foregroundWindow = GetForegroundWindow();
|
||||||
|
if (foregroundWindow == IntPtr.Zero)
|
||||||
|
{
|
||||||
|
AppLogger.Error("Cannot switch keyboard layout because no foreground window was found.");
|
||||||
|
return new KeyboardLayoutScope(IntPtr.Zero, IntPtr.Zero);
|
||||||
|
}
|
||||||
|
|
||||||
|
var threadId = GetWindowThreadProcessId(foregroundWindow, out _);
|
||||||
|
var originalKeyboardLayout = GetKeyboardLayout(threadId);
|
||||||
|
AppLogger.Info($"Switching foreground keyboard layout from 0x{originalKeyboardLayout.ToInt64():X} to 0x{EnglishKeyboardLayout.ToInt64():X}.");
|
||||||
|
|
||||||
|
if (EnglishKeyboardLayout != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
PostMessage(foregroundWindow, WmInputLangChangeRequest, IntPtr.Zero, EnglishKeyboardLayout);
|
||||||
|
Thread.Sleep(50);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new KeyboardLayoutScope(foregroundWindow, originalKeyboardLayout);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (foregroundWindow == IntPtr.Zero || originalKeyboardLayout == IntPtr.Zero)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppLogger.Info($"Restoring foreground keyboard layout to 0x{originalKeyboardLayout.ToInt64():X}.");
|
||||||
|
PostMessage(foregroundWindow, WmInputLangChangeRequest, IntPtr.Zero, originalKeyboardLayout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct INPUT
|
||||||
|
{
|
||||||
|
public uint type;
|
||||||
|
public InputUnion U;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Explicit)]
|
||||||
|
private struct InputUnion
|
||||||
|
{
|
||||||
|
[FieldOffset(0)]
|
||||||
|
public MOUSEINPUT mi;
|
||||||
|
|
||||||
|
[FieldOffset(0)]
|
||||||
|
public KEYBDINPUT ki;
|
||||||
|
|
||||||
|
[FieldOffset(0)]
|
||||||
|
public HARDWAREINPUT hi;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct MOUSEINPUT
|
||||||
|
{
|
||||||
|
public int dx;
|
||||||
|
public int dy;
|
||||||
|
public uint mouseData;
|
||||||
|
public uint dwFlags;
|
||||||
|
public uint time;
|
||||||
|
public UIntPtr dwExtraInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct KEYBDINPUT
|
||||||
|
{
|
||||||
|
public ushort wVk;
|
||||||
|
public ushort wScan;
|
||||||
|
public uint dwFlags;
|
||||||
|
public uint time;
|
||||||
|
public UIntPtr dwExtraInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct HARDWAREINPUT
|
||||||
|
{
|
||||||
|
public uint uMsg;
|
||||||
|
public ushort wParamL;
|
||||||
|
public ushort wParamH;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,13 @@ namespace WirelessTextSyncer.Windows.Services;
|
|||||||
public sealed class SyncMessageHandler
|
public sealed class SyncMessageHandler
|
||||||
{
|
{
|
||||||
private readonly IKeyboardInjectionService keyboard;
|
private readonly IKeyboardInjectionService keyboard;
|
||||||
|
private readonly IAudioControlService audio;
|
||||||
|
private string remoteText = string.Empty;
|
||||||
|
|
||||||
public SyncMessageHandler(IKeyboardInjectionService keyboard)
|
public SyncMessageHandler(IKeyboardInjectionService keyboard, IAudioControlService audio)
|
||||||
{
|
{
|
||||||
this.keyboard = keyboard;
|
this.keyboard = keyboard;
|
||||||
|
this.audio = audio;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Handle(SyncMessage message)
|
public void Handle(SyncMessage message)
|
||||||
@@ -16,18 +19,51 @@ public sealed class SyncMessageHandler
|
|||||||
switch (message.Action)
|
switch (message.Action)
|
||||||
{
|
{
|
||||||
case SyncAction.InsertText:
|
case SyncAction.InsertText:
|
||||||
keyboard.InsertText(message.Text ?? string.Empty);
|
var insertedText = message.Text ?? string.Empty;
|
||||||
|
keyboard.InsertText(insertedText);
|
||||||
|
remoteText += insertedText;
|
||||||
|
break;
|
||||||
|
case SyncAction.ReplaceAll:
|
||||||
|
AppendSubmittedText(message.Text ?? string.Empty);
|
||||||
break;
|
break;
|
||||||
case SyncAction.Backspace:
|
case SyncAction.Backspace:
|
||||||
keyboard.Backspace();
|
keyboard.Backspace();
|
||||||
|
if (remoteText.Length > 0)
|
||||||
|
{
|
||||||
|
remoteText = remoteText[..^1];
|
||||||
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case SyncAction.Enter:
|
case SyncAction.Enter:
|
||||||
keyboard.Enter();
|
keyboard.Enter();
|
||||||
|
remoteText += Environment.NewLine;
|
||||||
break;
|
break;
|
||||||
case SyncAction.Ping:
|
case SyncAction.Ping:
|
||||||
break;
|
break;
|
||||||
|
case SyncAction.SetMute:
|
||||||
|
HandleSetMute(message);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
throw new InvalidOperationException($"Unsupported sync action: {message.Action}");
|
throw new InvalidOperationException($"Unsupported sync action: {message.Action}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void HandleSetMute(SyncMessage message)
|
||||||
|
{
|
||||||
|
var muted = message.Muted ?? false;
|
||||||
|
AppLogger.Info($"SetMute received muted={muted}.");
|
||||||
|
audio.SetMute(muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AppendSubmittedText(string text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(text))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppLogger.Info($"Appending submitted text length: {text.Length}");
|
||||||
|
keyboard.InsertText(text);
|
||||||
|
remoteText += text;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
|
using System.Net.NetworkInformation;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Fleck;
|
using Fleck;
|
||||||
@@ -8,74 +9,240 @@ namespace WirelessTextSyncer.Windows.Services;
|
|||||||
|
|
||||||
public sealed class WebSocketServerService : IDisposable
|
public sealed class WebSocketServerService : IDisposable
|
||||||
{
|
{
|
||||||
private readonly SyncMessageHandler messageHandler;
|
private static readonly byte[] HeartbeatPayload = "wts-heartbeat"u8.ToArray();
|
||||||
private readonly List<IWebSocketConnection> clients = [];
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
||||||
private WebSocketServer? server;
|
{
|
||||||
|
PropertyNameCaseInsensitive = true
|
||||||
|
};
|
||||||
|
|
||||||
public WebSocketServerService(SyncMessageHandler messageHandler)
|
private readonly TimeSpan heartbeatInterval = TimeSpan.FromSeconds(5);
|
||||||
|
private readonly SyncMessageHandler messageHandler;
|
||||||
|
private readonly string deviceName;
|
||||||
|
private readonly List<IWebSocketConnection> clients = [];
|
||||||
|
private readonly object clientsLock = new();
|
||||||
|
private WebSocketServer? server;
|
||||||
|
private System.Threading.Timer? heartbeatTimer;
|
||||||
|
|
||||||
|
public WebSocketServerService(SyncMessageHandler messageHandler, string? deviceName = null)
|
||||||
{
|
{
|
||||||
this.messageHandler = messageHandler;
|
this.messageHandler = messageHandler;
|
||||||
|
this.deviceName = string.IsNullOrWhiteSpace(deviceName) ? Environment.MachineName : deviceName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Port { get; private set; } = 8181;
|
public int Port { get; private set; } = 8181;
|
||||||
|
|
||||||
public string LocalIpAddress { get; private set; } = "127.0.0.1";
|
public string LocalIpAddress { get; private set; } = "127.0.0.1";
|
||||||
|
|
||||||
public bool HasClient => clients.Count > 0;
|
public bool HasClient
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (clientsLock)
|
||||||
|
{
|
||||||
|
clients.RemoveAll(client => !client.IsAvailable);
|
||||||
|
return clients.Count > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public event EventHandler? StatusChanged;
|
public event EventHandler? StatusChanged;
|
||||||
|
|
||||||
|
public string BuildServiceInfoJson()
|
||||||
|
{
|
||||||
|
return JsonSerializer.Serialize(
|
||||||
|
new ServiceInfoMessage(
|
||||||
|
DiscoveryResponderService.ServiceResponseType,
|
||||||
|
1,
|
||||||
|
deviceName,
|
||||||
|
LocalIpAddress,
|
||||||
|
Port),
|
||||||
|
JsonOptions);
|
||||||
|
}
|
||||||
|
|
||||||
public void Start(int port)
|
public void Start(int port)
|
||||||
{
|
{
|
||||||
Port = port;
|
Port = port;
|
||||||
LocalIpAddress = ResolveLocalIpAddress();
|
LocalIpAddress = ResolveLocalIpAddress();
|
||||||
|
AppLogger.Info($"Starting WebSocket server on 0.0.0.0:{Port}. Local IP: {LocalIpAddress}");
|
||||||
|
|
||||||
server = new WebSocketServer($"ws://0.0.0.0:{Port}");
|
server = new WebSocketServer($"ws://0.0.0.0:{Port}");
|
||||||
server.Start(socket =>
|
server.Start(socket =>
|
||||||
{
|
{
|
||||||
socket.OnOpen = () =>
|
socket.OnOpen = () =>
|
||||||
{
|
{
|
||||||
clients.Add(socket);
|
IWebSocketConnection[] replacedClients;
|
||||||
|
lock (clientsLock)
|
||||||
|
{
|
||||||
|
replacedClients = clients
|
||||||
|
.Where(client => client.ConnectionInfo.ClientIpAddress == socket.ConnectionInfo.ClientIpAddress)
|
||||||
|
.ToArray();
|
||||||
|
clients.RemoveAll(client => !client.IsAvailable || replacedClients.Contains(client));
|
||||||
|
clients.Add(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var replacedClient in replacedClients)
|
||||||
|
{
|
||||||
|
replacedClient.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
AppLogger.Info($"Client connected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
|
||||||
|
_ = SendServiceInfoAsync(socket);
|
||||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||||
};
|
};
|
||||||
socket.OnClose = () =>
|
socket.OnClose = () =>
|
||||||
{
|
{
|
||||||
clients.Remove(socket);
|
lock (clientsLock)
|
||||||
|
{
|
||||||
|
clients.Remove(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
AppLogger.Info($"Client disconnected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
|
||||||
StatusChanged?.Invoke(this, EventArgs.Empty);
|
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||||
};
|
};
|
||||||
|
socket.OnError = exception =>
|
||||||
|
{
|
||||||
|
AppLogger.Error("WebSocket connection error.", exception);
|
||||||
|
RemoveClient(socket, "connection error");
|
||||||
|
};
|
||||||
socket.OnMessage = HandleRawMessage;
|
socket.OnMessage = HandleRawMessage;
|
||||||
});
|
});
|
||||||
|
heartbeatTimer = new System.Threading.Timer(_ => ProbeClients(), null, heartbeatInterval, heartbeatInterval);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
foreach (var client in clients.ToArray())
|
heartbeatTimer?.Dispose();
|
||||||
|
IWebSocketConnection[] currentClients;
|
||||||
|
lock (clientsLock)
|
||||||
|
{
|
||||||
|
currentClients = clients.ToArray();
|
||||||
|
clients.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var client in currentClients)
|
||||||
{
|
{
|
||||||
client.Close();
|
client.Close();
|
||||||
}
|
}
|
||||||
|
|
||||||
clients.Clear();
|
|
||||||
server?.Dispose();
|
server?.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void HandleRawMessage(string rawMessage)
|
private void ProbeClients()
|
||||||
{
|
{
|
||||||
var message = JsonSerializer.Deserialize<SyncMessage>(rawMessage);
|
IWebSocketConnection[] currentClients;
|
||||||
if (message is null)
|
var removedUnavailableClients = false;
|
||||||
|
lock (clientsLock)
|
||||||
|
{
|
||||||
|
var countBefore = clients.Count;
|
||||||
|
clients.RemoveAll(client => !client.IsAvailable);
|
||||||
|
removedUnavailableClients = clients.Count != countBefore;
|
||||||
|
currentClients = clients.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (removedUnavailableClients)
|
||||||
|
{
|
||||||
|
AppLogger.Info("Removed unavailable WebSocket clients during heartbeat.");
|
||||||
|
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var client in currentClients)
|
||||||
|
{
|
||||||
|
_ = SendHeartbeatAsync(client);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SendHeartbeatAsync(IWebSocketConnection client)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!client.IsAvailable)
|
||||||
|
{
|
||||||
|
RemoveClient(client, "heartbeat unavailable");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.SendPing(HeartbeatPayload);
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error("WebSocket heartbeat failed.", exception);
|
||||||
|
RemoveClient(client, "heartbeat failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SendServiceInfoAsync(IWebSocketConnection client)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await client.Send(BuildServiceInfoJson());
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error("Failed to send WebSocket service info.", exception);
|
||||||
|
RemoveClient(client, "service info failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RemoveClient(IWebSocketConnection client, string reason)
|
||||||
|
{
|
||||||
|
var removed = false;
|
||||||
|
lock (clientsLock)
|
||||||
|
{
|
||||||
|
removed = clients.Remove(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!removed)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
messageHandler.Handle(message);
|
AppLogger.Info($"Removed WebSocket client after {reason}: {client.ConnectionInfo.ClientIpAddress}:{client.ConnectionInfo.ClientPort}");
|
||||||
|
StatusChanged?.Invoke(this, EventArgs.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleRawMessage(string rawMessage)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
AppLogger.Info($"Received message: {rawMessage}");
|
||||||
|
var message = JsonSerializer.Deserialize<SyncMessage>(rawMessage, JsonOptions);
|
||||||
|
if (message is null)
|
||||||
|
{
|
||||||
|
AppLogger.Info("Ignored empty sync message.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
messageHandler.Handle(message);
|
||||||
|
}
|
||||||
|
catch (JsonException exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error($"Invalid sync message: {rawMessage}", exception);
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
AppLogger.Error($"Failed to handle sync message: {rawMessage}", exception);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string ResolveLocalIpAddress()
|
private static string ResolveLocalIpAddress()
|
||||||
{
|
{
|
||||||
var host = Dns.GetHostEntry(Dns.GetHostName());
|
var address = NetworkInterface.GetAllNetworkInterfaces()
|
||||||
var address = host.AddressList.FirstOrDefault(
|
.Where(networkInterface =>
|
||||||
address => address.AddressFamily == AddressFamily.InterNetwork
|
networkInterface.OperationalStatus == OperationalStatus.Up
|
||||||
&& !IPAddress.IsLoopback(address));
|
&& networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
|
||||||
|
.Select(networkInterface => networkInterface.GetIPProperties())
|
||||||
|
.Where(properties => properties.GatewayAddresses.Any(
|
||||||
|
gateway => gateway.Address.AddressFamily == AddressFamily.InterNetwork
|
||||||
|
&& !IPAddress.Any.Equals(gateway.Address)))
|
||||||
|
.SelectMany(properties => properties.UnicastAddresses)
|
||||||
|
.Select(unicast => unicast.Address)
|
||||||
|
.FirstOrDefault(address =>
|
||||||
|
address.AddressFamily == AddressFamily.InterNetwork
|
||||||
|
&& !IPAddress.IsLoopback(address)
|
||||||
|
&& !address.ToString().StartsWith("169.254.", StringComparison.Ordinal));
|
||||||
|
|
||||||
return address?.ToString() ?? "127.0.0.1";
|
return address?.ToString() ?? "127.0.0.1";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed record ServiceInfoMessage(string Type, int Version, string Name, string Host, int Port);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,20 +4,36 @@ namespace WirelessTextSyncer.Windows.Tray;
|
|||||||
|
|
||||||
public sealed class TrayApplicationContext : ApplicationContext
|
public sealed class TrayApplicationContext : ApplicationContext
|
||||||
{
|
{
|
||||||
|
private readonly KeyboardInjectionService keyboard;
|
||||||
|
private readonly AudioControlService audio;
|
||||||
private readonly WebSocketServerService server;
|
private readonly WebSocketServerService server;
|
||||||
|
private readonly DiscoveryResponderService discovery;
|
||||||
private readonly NotifyIcon notifyIcon;
|
private readonly NotifyIcon notifyIcon;
|
||||||
|
private readonly Icon connectedIcon;
|
||||||
|
private readonly Icon waitIcon;
|
||||||
|
private readonly SynchronizationContext uiContext;
|
||||||
|
private ToolStripMenuItem? clipboardPasteMenuItem;
|
||||||
|
private ToolStripMenuItem? sendInputTypingMenuItem;
|
||||||
|
private bool? lastConnectionState;
|
||||||
|
private bool disposed;
|
||||||
|
|
||||||
public TrayApplicationContext()
|
public TrayApplicationContext()
|
||||||
{
|
{
|
||||||
var keyboard = new KeyboardInjectionService();
|
AppLogger.Info("Tray application starting.");
|
||||||
var handler = new SyncMessageHandler(keyboard);
|
uiContext = SynchronizationContext.Current ?? new WindowsFormsSynchronizationContext();
|
||||||
|
keyboard = new KeyboardInjectionService();
|
||||||
|
audio = new AudioControlService();
|
||||||
|
var handler = new SyncMessageHandler(keyboard, audio);
|
||||||
|
|
||||||
server = new WebSocketServerService(handler);
|
server = new WebSocketServerService(handler);
|
||||||
server.StatusChanged += (_, _) => UpdateTrayText();
|
server.StatusChanged += (_, _) => uiContext.Post(_ => UpdateTrayStatus(), null);
|
||||||
|
discovery = new DiscoveryResponderService(() => server.LocalIpAddress, () => server.Port);
|
||||||
|
connectedIcon = TrayIconFactory.CreateConnectedIcon();
|
||||||
|
waitIcon = TrayIconFactory.CreateWaitIcon();
|
||||||
|
|
||||||
notifyIcon = new NotifyIcon
|
notifyIcon = new NotifyIcon
|
||||||
{
|
{
|
||||||
Icon = SystemIcons.Application,
|
Icon = waitIcon,
|
||||||
Text = "WirelessTextSyncer starting...",
|
Text = "WirelessTextSyncer starting...",
|
||||||
Visible = true,
|
Visible = true,
|
||||||
ContextMenuStrip = BuildMenu()
|
ContextMenuStrip = BuildMenu()
|
||||||
@@ -27,10 +43,12 @@ public sealed class TrayApplicationContext : ApplicationContext
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
server.Start(8181);
|
server.Start(8181);
|
||||||
UpdateTrayText();
|
discovery.Start();
|
||||||
|
UpdateTrayStatus();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
AppLogger.Error("Failed to start tray application.", ex);
|
||||||
notifyIcon.BalloonTipTitle = "WirelessTextSyncer";
|
notifyIcon.BalloonTipTitle = "WirelessTextSyncer";
|
||||||
notifyIcon.BalloonTipText = $"Failed to start: {ex.Message}";
|
notifyIcon.BalloonTipText = $"Failed to start: {ex.Message}";
|
||||||
notifyIcon.ShowBalloonTip(5000);
|
notifyIcon.ShowBalloonTip(5000);
|
||||||
@@ -41,7 +59,12 @@ public sealed class TrayApplicationContext : ApplicationContext
|
|||||||
{
|
{
|
||||||
if (disposing)
|
if (disposing)
|
||||||
{
|
{
|
||||||
|
disposed = true;
|
||||||
notifyIcon.Dispose();
|
notifyIcon.Dispose();
|
||||||
|
connectedIcon.Dispose();
|
||||||
|
waitIcon.Dispose();
|
||||||
|
discovery.Dispose();
|
||||||
|
audio.Dispose();
|
||||||
server.Dispose();
|
server.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,10 +75,60 @@ public sealed class TrayApplicationContext : ApplicationContext
|
|||||||
{
|
{
|
||||||
var menu = new ContextMenuStrip();
|
var menu = new ContextMenuStrip();
|
||||||
menu.Items.Add("Copy connection address", null, (_, _) => CopyConnectionAddress());
|
menu.Items.Add("Copy connection address", null, (_, _) => CopyConnectionAddress());
|
||||||
|
menu.Items.Add(BuildInputModeMenu());
|
||||||
menu.Items.Add("Exit", null, (_, _) => ExitThread());
|
menu.Items.Add("Exit", null, (_, _) => ExitThread());
|
||||||
return menu;
|
return menu;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ToolStripMenuItem BuildInputModeMenu()
|
||||||
|
{
|
||||||
|
var inputModeMenu = new ToolStripMenuItem("Input mode");
|
||||||
|
clipboardPasteMenuItem = new ToolStripMenuItem("Clipboard paste")
|
||||||
|
{
|
||||||
|
CheckOnClick = false
|
||||||
|
};
|
||||||
|
sendInputTypingMenuItem = new ToolStripMenuItem("SendInput typing")
|
||||||
|
{
|
||||||
|
CheckOnClick = false
|
||||||
|
};
|
||||||
|
|
||||||
|
clipboardPasteMenuItem.Click += (_, _) => SetInputMode(TextInjectionMode.ClipboardPaste);
|
||||||
|
sendInputTypingMenuItem.Click += (_, _) => SetInputMode(TextInjectionMode.SendInputTyping);
|
||||||
|
inputModeMenu.DropDownItems.Add(clipboardPasteMenuItem);
|
||||||
|
inputModeMenu.DropDownItems.Add(sendInputTypingMenuItem);
|
||||||
|
UpdateInputModeMenuChecks();
|
||||||
|
return inputModeMenu;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetInputMode(TextInjectionMode mode)
|
||||||
|
{
|
||||||
|
keyboard.Mode = mode;
|
||||||
|
AppLogger.Info($"Text injection mode changed to {mode}.");
|
||||||
|
UpdateInputModeMenuChecks();
|
||||||
|
|
||||||
|
notifyIcon.BalloonTipTitle = "WirelessTextSyncer";
|
||||||
|
notifyIcon.BalloonTipText = $"Input mode: {GetInputModeLabel(mode)}";
|
||||||
|
notifyIcon.ShowBalloonTip(1500);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateInputModeMenuChecks()
|
||||||
|
{
|
||||||
|
if (clipboardPasteMenuItem is not null)
|
||||||
|
{
|
||||||
|
clipboardPasteMenuItem.Checked = keyboard.Mode == TextInjectionMode.ClipboardPaste;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sendInputTypingMenuItem is not null)
|
||||||
|
{
|
||||||
|
sendInputTypingMenuItem.Checked = keyboard.Mode == TextInjectionMode.SendInputTyping;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetInputModeLabel(TextInjectionMode mode)
|
||||||
|
{
|
||||||
|
return mode == TextInjectionMode.ClipboardPaste ? "Clipboard paste" : "SendInput typing";
|
||||||
|
}
|
||||||
|
|
||||||
private void OnTrayIconClicked(object? sender, MouseEventArgs e)
|
private void OnTrayIconClicked(object? sender, MouseEventArgs e)
|
||||||
{
|
{
|
||||||
if (e.Button == MouseButtons.Left)
|
if (e.Button == MouseButtons.Left)
|
||||||
@@ -72,9 +145,34 @@ public sealed class TrayApplicationContext : ApplicationContext
|
|||||||
notifyIcon.ShowBalloonTip(1500);
|
notifyIcon.ShowBalloonTip(1500);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void UpdateTrayText()
|
private void UpdateTrayStatus()
|
||||||
{
|
{
|
||||||
var status = server.HasClient ? "connected" : "waiting";
|
if (disposed)
|
||||||
notifyIcon.Text = $"WirelessTextSyncer {server.LocalIpAddress}:{server.Port} ({status})";
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var connected = server.HasClient;
|
||||||
|
var status = connected ? "connected" : "waiting";
|
||||||
|
var text = $"WirelessTextSyncer {server.LocalIpAddress}:{server.Port} ({status})";
|
||||||
|
notifyIcon.Icon = connected ? connectedIcon : waitIcon;
|
||||||
|
notifyIcon.Text = text.Length > 63 ? text[..63] : text;
|
||||||
|
|
||||||
|
if (lastConnectionState is not null && lastConnectionState != connected)
|
||||||
|
{
|
||||||
|
ShowConnectionToast(connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
lastConnectionState = connected;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ShowConnectionToast(bool connected)
|
||||||
|
{
|
||||||
|
notifyIcon.BalloonTipTitle = "WirelessTextSyncer";
|
||||||
|
notifyIcon.BalloonTipText = connected
|
||||||
|
? $"Device connected to {server.LocalIpAddress}:{server.Port}."
|
||||||
|
: "Device disconnected. Waiting for connection.";
|
||||||
|
notifyIcon.BalloonTipIcon = connected ? ToolTipIcon.Info : ToolTipIcon.Warning;
|
||||||
|
notifyIcon.ShowBalloonTip(3000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
50
WirelessTextSyncer.Windows/Tray/TrayIconFactory.cs
Normal file
50
WirelessTextSyncer.Windows/Tray/TrayIconFactory.cs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
using System.Drawing.Imaging;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace WirelessTextSyncer.Windows.Tray;
|
||||||
|
|
||||||
|
internal static class TrayIconFactory
|
||||||
|
{
|
||||||
|
private const string ConnectedResourceName = "WirelessTextSyncer.TrayConnected.png";
|
||||||
|
private const string WaitResourceName = "WirelessTextSyncer.TrayWait.png";
|
||||||
|
|
||||||
|
public static Icon CreateConnectedIcon()
|
||||||
|
{
|
||||||
|
return CreateIconFromResource(ConnectedResourceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Icon CreateWaitIcon()
|
||||||
|
{
|
||||||
|
return CreateIconFromResource(WaitResourceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Icon CreateIconFromResource(string resourceName)
|
||||||
|
{
|
||||||
|
var assembly = Assembly.GetExecutingAssembly();
|
||||||
|
using var stream = assembly.GetManifestResourceStream(resourceName)
|
||||||
|
?? throw new InvalidOperationException($"Tray icon resource not found: {resourceName}");
|
||||||
|
using var source = new Bitmap(stream);
|
||||||
|
using var bitmap = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb);
|
||||||
|
using (var graphics = Graphics.FromImage(bitmap))
|
||||||
|
{
|
||||||
|
graphics.Clear(Color.Transparent);
|
||||||
|
graphics.DrawImage(source, 0, 0, source.Width, source.Height);
|
||||||
|
}
|
||||||
|
|
||||||
|
var handle = bitmap.GetHicon();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var icon = Icon.FromHandle(handle);
|
||||||
|
return (Icon)icon.Clone();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DestroyIcon(handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool DestroyIcon(IntPtr handle);
|
||||||
|
}
|
||||||
@@ -6,12 +6,18 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<UseWindowsForms>true</UseWindowsForms>
|
<UseWindowsForms>true</UseWindowsForms>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<ApplicationIcon>Resources\Icons\app.ico</ApplicationIcon>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Fleck" Version="1.2.0" />
|
<PackageReference Include="Fleck" Version="1.2.0" />
|
||||||
<PackageReference Include="InputSimulatorPlus" Version="1.0.7" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.8" />
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.8" />
|
||||||
|
<PackageReference Include="NAudio" Version="2.2.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="Resources\Icons\tray-connected.png" LogicalName="WirelessTextSyncer.TrayConnected.png" />
|
||||||
|
<EmbeddedResource Include="Resources\Icons\tray-wait.png" LogicalName="WirelessTextSyncer.TrayWait.png" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
|
|||||||
Reference in New Issue
Block a user