csharp 对 win32api 的调用和封装到底设计成怎样比较好

首先分情况,现在肯定都是用 cswin32 来投影源生成

如果只是个测试项目,那直接用随便怎样都好。

如果是个正式项目,那就需要把对 win32 的调用封装在一个类或文件中,并且不对外暴露 HWND 等 cswin32 相关命名空间。

 一、约定成熟的调用方案

如 MessageBox.Show(),这是 wpf 里自带的调用。

namespace YourNamespace.Interop;

class MessageBox
{
  public static Task ShowAsync(string text, string caption = Constants.DisplayName) =>
    Task.FromResult(PInvoke.MessageBox(HWND.Null, text, caption, MESSAGEBOX_STYLE.MB_OK));
}

可以自定义这个 ShowAsync 或者多个函数签名重载。

二、封装调用

public static partial class Win32
{
    public static void SetFocus(nint hwnd) => PInvoke.SetFocus(new(hwnd));

    public static void ActivateWindow(nint hwnd)
    {
        PInvoke.ShowWindow(new(hwnd), SHOW_WINDOW_CMD.SW_RESTORE);
        PInvoke.SetForegroundWindow(new(hwnd));
    }

    public static bool HideWindow(IntPtr hWnd) => PInvoke.ShowWindow(new(hWnd), SHOW_WINDOW_CMD.SW_HIDE);

    public static Task<bool> SetParentWindowAsync(nint child, nint parent) =>
        Task.Run(() => PInvoke.SetParent(new(child), new(parent)) != HWND.Null);
}

可以按需拆分为多个 Win32 文件,Win32.cs,Win32.Window.cs。

不需要 Extension 不要不伦不类的。

感觉可以分为三个等阶级

1 名字和调用完全一致没有任何改变的封装。

2 如果有任何不同,理应重新命名,名字带 Async 异步化,如修改了返回值从 HWND 变为 bool 等。

3 完全自定义复杂的逻辑如 Win32.SendAltEnter()。

 

常用的关键词 Interop,NativeMethods,Win32,PInvoke

NativeMethods.txt 这个名称被 cswin32 用过,PInvoke 也是 cswin32 生成的类名。

posted @ 2025-04-08 15:22  凌枫玖  阅读(25)  评论(0)    收藏  举报