XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.ComponentModel;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using NAudio.CoreAudioApi;

namespace XFEToolBox.QuickTools;

public sealed record AudioEndpoint(string Id, string Name, bool Default) { public override string ToString() => (Default ? "● " : "") + Name; }
public static class SystemActions
{
    public static AudioEndpoint[] OutputDevices()
    {
        using var enumerator = new MMDeviceEnumerator(); string? current = null;
        try { using var d = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console); current = d.ID; } catch (COMException) { }
        var result = new List<AudioEndpoint>(); foreach (var d in enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)) { using (d) result.Add(new(d.ID, d.FriendlyName, d.ID == current)); }
        return result.ToArray();
    }
    public static bool MicrophoneMuted()
    { using var enumerator = new MMDeviceEnumerator(); using var d = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications); return d.AudioEndpointVolume.Mute; }
    public static void SetMicrophoneMute(bool mute)
    { using var enumerator = new MMDeviceEnumerator(); using var d = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Communications); d.AudioEndpointVolume.Mute = mute; }
    public static void SetOutput(string id)
    {
        using var enumerator = new MMDeviceEnumerator(); using (var device = enumerator.GetDevice(id)) if (device.State != DeviceState.Active || device.DataFlow != DataFlow.Render) throw new InvalidOperationException("所选播放设备不可用,请刷新列表。");
        var prior = new List<(Role Role, string Id)>(); foreach (var role in new[] { Role.Console, Role.Multimedia, Role.Communications }) { using var d = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, role); prior.Add((role, d.ID)); }
        object policy = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("870AF99C-171D-4F9E-AF0D-E63DF40C2BC9"), true)!)!;
        try { var config = (IPolicyConfig)policy; foreach (var item in prior) { int hr = config.SetDefaultEndpoint(id, (int)item.Role); if (hr < 0) { var failures = new List<int>(); foreach (var old in prior) { int undo = config.SetDefaultEndpoint(old.Id, (int)old.Role); if (undo < 0) failures.Add(undo); } throw new InvalidOperationException($"切换音频失败 0x{hr:X8}。" + (failures.Count == 0 ? "已恢复原设备。" : "部分恢复失败,请在 Windows 声音设置中检查默认设备。")); } } }
        finally { Marshal.ReleaseComObject(policy); }
    }
    public static string LocalAddresses() => string.Join(Environment.NewLine, NetworkInterface.GetAllNetworkInterfaces().Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback).SelectMany(n => n.GetIPProperties().UnicastAddresses.Select(a => $"{n.Name}  {a.Address}")));
    public static nint ForegroundWindow() => GetForegroundWindow();
    public static bool IsTopmost(nint hwnd) => (GetWindowLongPtr(hwnd, -20).ToInt64() & 8) != 0;
    public static void SetTopmost(nint hwnd, bool enabled)
    { if (hwnd == 0 || !IsWindow(hwnd)) throw new InvalidOperationException("目标窗口已不存在,请先切换到目标窗口,再用快捷键打开工具箱。"); if (!SetWindowPos(hwnd, enabled ? new nint(-1) : new nint(-2), 0, 0, 0, 0, 0x13)) throw new Win32Exception(Marshal.GetLastWin32Error()); }
    public static void PasteTo(nint hwnd)
    {
        if (hwnd == 0 || !IsWindow(hwnd)) throw new InvalidOperationException("没有有效的先前窗口;内容已复制,可手动 Ctrl+V。");
        SetForegroundWindow(hwnd);
        if (GetForegroundWindow() != hwnd) throw new InvalidOperationException("系统阻止切回目标窗口;内容已复制,可手动 Ctrl+V。");
        // Emit only after explicit click and verifying the intended foreground HWND.
        var input = new[] { Key(0x11, false), Key(0x56, false), Key(0x56, true), Key(0x11, true) };
        if (SendInput((uint)input.Length, input, Marshal.SizeOf<INPUT>()) != input.Length) { SendInput(2, [Key(0x56, true), Key(0x11, true)], Marshal.SizeOf<INPUT>()); throw new Win32Exception(Marshal.GetLastWin32Error(), "无法粘贴到该权限级别的窗口,请手动粘贴。"); }
    }
    private static INPUT Key(ushort key, bool up) => new() { Type = 1, Data = new INPUTDATA { Keyboard = new KEYBDINPUT { VirtualKey = key, Flags = up ? 2u : 0 } } };
    [StructLayout(LayoutKind.Sequential)] private struct INPUT { public uint Type; public INPUTDATA Data; }
    [StructLayout(LayoutKind.Explicit)] private struct INPUTDATA { [FieldOffset(0)] public KEYBDINPUT Keyboard; [FieldOffset(0)] public MOUSEINPUT Mouse; }
    [StructLayout(LayoutKind.Sequential)] private struct KEYBDINPUT { public ushort VirtualKey, Scan; public uint Flags, Time; public nuint Extra; }
    [StructLayout(LayoutKind.Sequential)] private struct MOUSEINPUT { public int X, Y; public uint Data, Flags, Time; public nuint Extra; }
    [DllImport("user32.dll")] private static extern nint GetForegroundWindow();
    [DllImport("user32.dll")] private static extern bool IsWindow(nint hwnd);
    [DllImport("user32.dll")] private static extern nint GetWindowLongPtr(nint hwnd, int index);
    [DllImport("user32.dll", SetLastError = true)] private static extern bool SetWindowPos(nint hwnd, nint after, int x, int y, int w, int h, uint flags);
    [DllImport("user32.dll")] private static extern bool SetForegroundWindow(nint hwnd);
    [DllImport("user32.dll", SetLastError = true)] private static extern uint SendInput(uint count, INPUT[] inputs, int size);
    [ComImport, Guid("F8679F50-850A-41CF-9C72-430F290290C8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    private interface IPolicyConfig
    {
        [PreserveSig] int GetMixFormat(); [PreserveSig] int GetDeviceFormat(); [PreserveSig] int ResetDeviceFormat(); [PreserveSig] int SetDeviceFormat(); [PreserveSig] int GetProcessingPeriod(); [PreserveSig] int SetProcessingPeriod(); [PreserveSig] int GetShareMode(); [PreserveSig] int SetShareMode(); [PreserveSig] int GetPropertyValue(); [PreserveSig] int SetPropertyValue();
        [PreserveSig] int SetDefaultEndpoint([MarshalAs(UnmanagedType.LPWStr)] string id, int role); [PreserveSig] int SetEndpointVisibility();
    }
}
public sealed class AwakeLease : IDisposable
{
    public static AwakeLease Shared { get; } = new();
    public DateTimeOffset? Until { get; private set; }
    private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(1) };
    public AwakeLease() { timer.Tick += (_, _) => { if (DateTimeOffset.Now >= Until) Stop(); }; }
    public void Start(int minutes)
    { if (minutes is < 1 or > 240) throw new ArgumentException("防休眠时长为 1–240 分钟。"); if (SetThreadExecutionState(0x80000003) == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); Until = DateTimeOffset.Now.AddMinutes(minutes); timer.Start(); }
    public void Stop() { timer.Stop(); if (Until.HasValue) SetThreadExecutionState(0x80000000); Until = null; }
    public void Dispose() => Stop();
    [DllImport("kernel32.dll", SetLastError = true)] private static extern uint SetThreadExecutionState(uint flags);
}