C# WinForms 在运行时动态创建图片框不起作用



我正在尝试使用c#winforms在运行时动态创建PictureBox。 我的项目:我想编写一个程序,它有一个节点 GUI(具有各种类型的节点、某种盒子的GUI,它们连接在一起并处理图像、音频流或其他任何东西(。

因此,我想在运行时动态创建和删除图片框,但我的测试不起作用,表单为空。

这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AudioNodeGUI
{
public partial class AudioNodeWindow : Form
{
public AudioNodeWindow()
{
InitializeComponent();
}
private void AudioNodeWindow_Load(object sender, EventArgs e)
{
}
private void AudioNodeWindow_Paint(object sender, PaintEventArgs e)
{
PictureBox start_picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(19, 32),
Location = new Point(100, 100),
Visible = true,
Image = Bitmap.FromFile(@"C:UsersBenjamin.MBENJAMINPicturesStart.png"),
};
start_picture.Show();
}
}
}

请帮忙!

您需要将创建的控件添加到窗体控件中。

在 Show(( 图片框之前,请尝试添加以下行:

Controls.Add(start_picture);

其次,你不想在Paint((上这样做!

我会说你需要把它移动到 Load(( 方法,这样它将在表单加载时完成,而不是每次重新绘制时!

更改:

start_picture.Show();

自:

this.Controls.Add(start_picture);
start_picture.Show();

Controls.Add 告知表单,PictureBox此特定表单的一部分。

此外,您不希望在Paint事件处理程序中执行此操作。把它留在那里会导致比你想象的更多的图片框......

我已将您的代码更改为:

PictureBox start_picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(19, 32),
Location = new Point(100, 100),
Visible = true,
Image = Bitmap.FromFile(@"D:testlearn.png"),
};
//start_picture.Show();
Controls.Add(start_picture);

最新更新