使用Win32 API获取桌面工作区:如何让SystemParametersInfoA返回System.Drawing.Rectangle?
解决方法
你不需要用IntPtr接收工作区矩形,直接通过结构体映射或直接使用System.Drawing.Rectangle即可实现需求,具体方案如下:
方案一:通过自定义RECT结构体转换
- 定义与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); } }
- 修正
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;
- 修改
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
相关产品推荐
相关产品推荐

