2025-10-11 18:25:59 +08:00

105 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace XiaoZhiSharp.Utils
{
public class CapsLockChecker
{
public static bool IsCapsLockOn()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return IsCapsLockOnWindows();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return IsCapsLockOnLinux();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return IsCapsLockOnMacOS();
}
else
{
throw new PlatformNotSupportedException("Unsupported operating system");
}
}
// Windows 实现
private static bool IsCapsLockOnWindows()
{
return Console.CapsLock;
}
// Linux 实现
private static bool IsCapsLockOnLinux()
{
try
{
// 使用 xset 命令查询键盘状态
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "xset",
Arguments = "q",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// 解析输出,查找 Caps Lock 状态
return output.Contains("Caps Lock: on");
}
catch
{
// 如果 xset 不可用,尝试其他方法
return false;
}
}
// macOS 实现
private static bool IsCapsLockOnMacOS()
{
try
{
// 使用 defaults 命令读取键盘设置
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "defaults",
Arguments = "read -g AppleKeyboardUIMode",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// 如果返回值为 1 或 3表示 Caps Lock 已启用
if (int.TryParse(output.Trim(), out int result))
{
return result == 1 || result == 3;
}
return false;
}
catch
{
return false;
}
}
}
}