无需Windows App SDK,在F#/.NET中从HWND获取WindowId
在F#/.NET中从HWND获取WindowId
直接通过P/Invoke实现
Windows系统原生提供了GetWindowIdFromWindow函数,你可以在F#中通过P/Invoke直接调用它,完全避开Windows App SDK的WinUI兼容性问题。
以下是完整的实现代码:
open System open System.Runtime.InteropServices // 对应ABI层面的Windows.UI.WindowId结构体 [<Struct>] type AbiWindowId = val Value: uint64 // 声明P/Invoke调用签名 [<DllImport("user32.dll", SetLastError = true)>] extern int GetWindowIdFromWindow(IntPtr hwnd, [<Out>] AbiWindowId& windowId) // 封装为返回WinRT WindowId的易用函数 let getWindowIdFromWindow (hwnd: IntPtr) = let mutable abiWindowId = AbiWindowId() let hresult = GetWindowIdFromWindow(hwnd, &abiWindowId) if hresult <> 0 then failwithf "调用GetWindowIdFromWindow失败,错误码: %d" (Marshal.GetLastWin32Error()) // 转换为WinRT的WindowId实例 Windows.UI.WindowId(abiWindowId.Value)
替代方案
如果需要结合Windows App SDK的其他能力使用,可选择以下两种方案:
- 调整项目配置兼容Windows App SDK:修改F#项目文件,移除WinUI相关依赖,仅引用Windows App SDK的核心包(如
Microsoft.Windows.SDK.NET),从而直接使用Win32Interop.GetWindowIdFromWindow。 - 通过C#中间层转发:创建独立的C#类库项目,引用Windows App SDK并封装
Win32Interop.GetWindowIdFromWindow函数,将类库资产标记为私有后,在F#项目中引用该类库间接获取WindowId。
内容的提问来源于stack exchange,提问作者Nick Darvey
相关产品推荐
相关产品推荐

