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

如何将修改后的Bitmap从子窗体Form2传回主窗体Form1?

WinForms窗体间Bitmap回传解决方案

核心思路

  • 在Form2中定义类级别的Bitmap字段保存修改后的图像
  • 给Form2添加公共属性供Form1读取修改后的Bitmap
  • 利用ShowDialog()的返回值区分用户确认/取消操作,仅在确认时读取返回图像

修改后的Form2代码

// 类级别字段,保存修改后的Bitmap
private Bitmap _modifiedBitmap;

// 公共属性,供Form1获取修改后的图像
public Bitmap ModifiedBitmap => _modifiedBitmap;

int integer_f2;
internal void ReceiveData(int integer)
{
    integer_f2 = integer;
}

public void Linear(Bitmap bmp)
{
    // 创建修改后的Bitmap实例
    _modifiedBitmap = new Bitmap(bmp.Width, bmp.Height);

    for (int x = 0; x < bmp.Width; x++)
    {
        for (int y = 0; y < bmp.Height; y++)
        {
            Color clr = Color.FromArgb(255, integer_f2, integer_f2, integer_f2);
            _modifiedBitmap.SetPixel(x, y, clr);
        }
    }

    // 可选:在Form2中显示修改后的图像(需先在Form2添加PictureBox控件,命名为pictureBox1)
    pictureBox1.Image = _modifiedBitmap;
}

private void Button_Cancel_2_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.Cancel;
    Close();
}

private void Button_OK_2_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.OK;
    Close();
}

修改后的Form1代码

private void Button1_Click(object sender, EventArgs e)
{
    using (Form2 f2 = new Form2())
    {
        f2.ReceiveData(integer);
        f2.Linear(bmp);
        DialogResult result = f2.ShowDialog();
        
        if (result == DialogResult.OK)
        {
            // 获取修改后的Bitmap并处理
            Bitmap modifiedBmp = f2.ModifiedBitmap;
            // 示例:显示在Form1的PictureBox中
            // pictureBox1.Image = modifiedBmp;
        }
    }
}

注意事项

  • Bitmap属于非托管资源,使用完毕后需调用Dispose()释放内存,使用using语句包裹Form2实例可确保资源自动释放
  • 若直接修改传入的Bitmap实例,会直接改变原对象状态,创建新实例的方式更安全,避免影响原图像
  • Form2中若要预览修改后的图像,需添加PictureBox控件并将_modifiedBitmap赋值给其Image属性

内容的提问来源于stack exchange,提问作者Gaunter O'Dimm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:36:16