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

C#中如何使用PaintEventArgs e参数初始化Gallow类?

解决方法

核心思路是不要让Gallow的构造依赖PaintEventArgs——这个参数只有在Paint事件触发时才会生成,提前初始化对象根本拿不到它。我们可以把Graphics的传递或绘制逻辑移到单独方法里,先初始化Gallow对象,等Paint事件触发时再传入所需的Graphics。

方案1:分离构造与Graphics赋值

修改Gallow类,去掉构造函数对PaintEventArgs的依赖,添加方法来设置Graphics并执行绘制:

internal class Gallow : Hangman
{
    private Graphics _g;

    // 无参构造,提前初始化时直接调用
    public Gallow() { }

    // 在Paint事件中调用此方法传入Graphics
    public void SetGraphics(Graphics graphics)
    {
        _g = graphics;
        // 这里可以直接调用绘制逻辑
        DrawGallow();
    }

    // 单独的绞架绘制方法
    private void DrawGallow()
    {
        if (_g == null) return;
        // 写你的绘制逻辑,比如:
        _g.DrawLine(Pens.Black, 10, 10, 10, 100);
        // 其他绘制代码...
    }
}

使用示例:

// 提前初始化Gallow,不需要PaintEventArgs
Gallow gallow = new Gallow();

// 在控件的Paint事件处理方法中:
private void YourControl_Paint(object sender, PaintEventArgs e)
{
    // 传入当前上下文的Graphics并执行绘制
    gallow.SetGraphics(e.Graphics);
}

方案2:直接在Paint事件中传入Graphics绘制

如果不需要长期保存Graphics对象,也可以把绘制逻辑做成接收Graphics参数的方法,构造函数保持无参:

internal class Gallow : Hangman
{
    public Gallow() { }

    // 绘制方法直接接收Graphics参数,在Paint事件里调用
    public void Draw(Graphics graphics)
    {
        if (graphics == null) return;
        // 绞架绘制逻辑
        graphics.DrawLine(Pens.Black, 10, 10, 10, 100);
        // 其他绘制代码...
    }
}

使用示例:

// 提前初始化Gallow
Gallow gallow = new Gallow();

// Paint事件中调用绘制方法
private void YourControl_Paint(object sender, PaintEventArgs e)
{
    gallow.Draw(e.Graphics);
}

补充说明

Graphics对象和当前绘制上下文绑定,长期保存容易引发绘制异常。每次Paint事件传入最新的Graphics,才是更安全的做法——毕竟WinForms会在需要重绘时自动触发Paint事件,确保绘制逻辑始终用的是有效上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:15:42