You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 19:31:00