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

使用Win32 API获取桌面工作区:如何让SystemParametersInfoA返回System.Drawing.Rectangle?

解决方法

你不需要用IntPtr接收工作区矩形,直接通过结构体映射或直接使用System.Drawing.Rectangle即可实现需求,具体方案如下:

方案一:通过自定义RECT结构体转换

  1. 定义与Windows API兼容的RECT结构体,并添加转换为System.Drawing.Rectangle的方法:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;

    public Rectangle ToRectangle()
    {
        return new Rectangle(Left, Top, Right - Left, Bottom - Top);
    }
}
  1. 修正SystemParametersInfo的DllImport声明,将参数类型改为out RECT:
[DllImport("user32.dll", SetLastError = true)]
static extern bool SystemParametersInfo(uint uiAction, uint uiParam, out RECT pvParam, uint fWinIni);
const uint SPI_GETWORKAREA = 0x0030;
  1. 修改GetRect方法,获取矩形后完成转换:
void GetRect()
{
    RECT workAreaRect;
    if (SystemParametersInfo(SPI_GETWORKAREA, 0, out workAreaRect, 0))
    {
        Rectangle drawingRect = workAreaRect.ToRectangle();
        // 在此处使用drawingRect即可
    }
    else
    {
        // 调用失败时,可通过Marshal.GetLastWin32Error()获取错误码排查问题
    }
}

方案二:直接使用System.Drawing.Rectangle

由于System.Drawing.Rectangle的内存布局与Windows API的RECT完全一致,可直接将其作为参数传入,省去转换步骤:

[DllImport("user32.dll", SetLastError = true)]
static extern bool SystemParametersInfo(uint uiAction, uint uiParam, out Rectangle pvParam, uint fWinIni);
const uint SPI_GETWORKAREA = 0x0030;

void GetRect()
{
    Rectangle workAreaRect;
    if (SystemParametersInfo(SPI_GETWORKAREA, 0, out workAreaRect, 0))
    {
        // 直接使用workAreaRect即可
    }
}

注意:.NET Core/.NET 5+项目需要手动安装NuGet包System.Drawing.Common,.NET Framework项目默认已引用System.Drawing程序集。

内容的提问来源于stack exchange,提问作者Nairel Prandini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:15:38