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

在.NET中不导入Win32 API,是否有GetUpdateRect()的替代方案?

在C#自定义控件中获取Update Rect的方案

原生.NET组件实现(推荐)

在自定义控件的OnPaint方法中,.NET提供的PaintEventArgs已经封装了需要更新的区域,直接通过ClipRectangle属性就能获取,完全无需依赖Win32 API:

protected override void OnPaint(PaintEventArgs e)
{
    // 获取当前需要更新的区域(即Update Rect)
    Rectangle updateRect = e.ClipRectangle;

    // 示例:用红色边框标记更新区域
    using (Pen redPen = new Pen(Color.Red, 1))
    {
        e.Graphics.DrawRectangle(redPen, updateRect);
    }

    // 执行控件原有绘制逻辑
    base.OnPaint(e);
}

当控件触发重绘时,.NET会自动计算出需要更新的局部区域并传入PaintEventArgs,ClipRectangle就是这个区域的矩形范围,这是最贴合.NET原生开发模式的方案。

Win32 API实现(可选)

如果需要在OnPaint以外的时机获取更新区域,可以通过GetUpdateRect Win32 API实现:

首先声明API导入:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool GetUpdateRect(IntPtr hWnd, out Rectangle lpRect, bool bErase);

然后在自定义控件的方法中调用:

public Rectangle GetCurrentUpdateRect()
{
    Rectangle updateRect = Rectangle.Empty;
    // bErase设为false,避免自动擦除更新区域的背景
    GetUpdateRect(this.Handle, out updateRect, false);
    return updateRect;
}

注意:GetUpdateRect获取的是尚未处理的更新区域,一旦调用Invalidate或完成重绘,该区域会被重置为Empty。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:28:14