使用C#以编程方式切换Windows专注模式

缘起 最近需要以编程方式调用windows api实现windows10专注模式的切换,但是Google一圈,没有现成代码。找到的相关帖子要么是cpp的要么是rust的,而且是undocument的Windows api。 Csharp调用 以下是完整代码 public static class FocusAssistToogle { private const string NtdllDlDll = "ntdll.dll"; private const uint DataBufferSize = 4; private static readonly byte[] DisableDataBuf = { 0x00, 0x00, 0x00, 0x00 }; // 01仅优先通知 02 仅限闹钟 private static readonly byte[] EnableDataBuf = { 0x02, 0x00, 0x00, 0x00 }; [DllImport(NtdllDlDll, SetLastError = true)] private static extern int ZwUpdateWnfStateData( ref WnfSWnfStateName sWnfStateName, byte[] buffer, uint bufferSize, IntPtr previousStateData, IntPtr currentStateData, uint previousStateDataSize, uint currentStateDataSize); [StructLayout(LayoutKind.Sequential)] private struct WnfSWnfStateName { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public uint[] Data; } private static WnfSWnfStateName _wnfSWnfShelQuietMomentShellModeChanged = new WnfSWnfStateName { Data = new uint[] { 0xa3bf5075, 0xd83063e } }; public static bool EnableFocusMode() { int result = ZwUpdateWnfStateData(ref _wnfSWnfShelQuietMomentShellModeChanged, EnableDataBuf, DataBufferSize, IntPtr.Zero, IntPtr.Zero, 0, 0); return result == 0; } public static bool DisableFocusMode() { int result = ZwUpdateWnfStateData(ref _wnfSWnfShelQuietMomentShellModeChanged, DisableDataBuf, DataBufferSize, IntPtr.Zero, IntPtr.Zero, 0, 0); return result == 0; } } 调用时,最好先调用DisableFoucusMode方法,再调用EnableFocusMode,参考StackOverflow上的说明 ...

2023-07-24 · 2 分钟 · czyt

C# dllimport 备忘录

dllImport的入口点问题 通过Dependencies 查询Dll对应方法的EntryPoint 然后在dllimport的attribute中显式申明EntryPoint [DllImport("demo.dll", SetLastError = true,EntryPoint ="??0DemoManager@EcgParser@Gfeit@@AEAA@XZ")] public static extern IntPtr DemoManager(); 导入类方法的问题 最好的方式还是使用C++构造wrapper,然后通过windowsApi的方式调用Pinvoke 参考链接 swig nuget swig C++/C# interoperability Working with C++ Interface Classes from C# Call function in unmanaged DLL from C# and pass custom data types [Marshal] SWIG and C# Example for SWIG to wrap C++ library in .Net 6

2022-10-09 · 1 分钟 · czyt