[英]Create a picturebox_clicked event for each picturebox created
private Form1 form1 { get; set; }
readonly HttpClient httpClient = new();
public static string FolderPath = @".\Storage";
public static int picNum = 0;
public static List<string> outofScopeURL = new List<string>();
private async void Detailed_View_Load_1(object sender, EventArgs e)
{
DirectoryInfo directory = new(FolderPath);
FileInfo[] files = directory.GetFiles();
string[] FileFormats = { ".png", ".jpg", ".jpeg", ".txt" };
for (int pictureCreator = 0; pictureCreator < files.Length; pictureCreator++)
{
FileInfo file = files[pictureCreator];
if (file.FullName.EndsWith(FileFormats[3]))
{
string url = File.ReadAllText(file.FullName);
if (url != null)
{
try
{
Image gif = Image.FromStream(await httpClient.GetStreamAsync(url));
PictureBox picture = new PictureBox
{
Name = url,
Size = new(38, 38),
Image = gif,
Location = new((gif.Width * pictureCreator), 0),
SizeMode = PictureBoxSizeMode.Zoom
};
this.Controls.Add(picture);
MessageBox.Show(picture.Name);
outofScopeURL.Add(url);
picture.Click += Picture_Click;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
picNum++;
}
}
}
我想要实现的目标:我试图在特定目录中查找文本文件,然后我想读取这些文件并提取其中存在的 URL。 在我获得文件夹中所有文本文件的所有 URL 后,我将它们添加到列表中,这样我就可以将它们与它们各自的图片框一起使用
例如,当 URL1 有 picture1,URL2 有 picture2 时,我想在单击应用了 picture1 的 picturebox1 时将剪贴板的文本设置为 URL1。
我尝试了什么:我尝试在 pictureCreator for 循环中创建一个新的 picturebox_Clicked 事件,但问题是该事件始终应用于最后创建的图片框。
任何帮助深表感谢。
您的问题是关于为每个创建的图片框创建一个 picturebox_clicked 事件。
您发布的代码似乎是这样做的,但正如评论中所提到的,转换sender
参数将是使事件有用的关键。 考虑一个类似于此实现的点击处理程序:
private void onAnyPictureBoxClick(object? sender, EventArgs e)
{
if(sender is PictureBox pictureBox)
{
var builder = new List<string>();
builder.Add($"Name: {pictureBox.Name}");
builder.Add($"Tag: {pictureBox.Tag}");
builder.Add($"Image Location: {pictureBox.ImageLocation}");
MessageBox.Show(string.Join(Environment.NewLine, builder));
}
}
现在对其进行测试(模拟已经从本地商店收集 URL 的部分)。
public partial class MainForm : Form
{
public MainForm() =>InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
int id = 0;
// Here we have "already read" the URLs from the local store.
foreach (var url in new string[]
{
"https://i.stack.imgur.com/eSiWr.png",
"https://i.stack.imgur.com/o5dmA.png",
"https://i.stack.imgur.com/aqAuN.png",
})
{
var dynamicPB = new PictureBox
{
Width = flowLayoutPanel.Width - SystemInformation.VerticalScrollBarWidth,
Height = 200,
SizeMode = PictureBoxSizeMode.Zoom,
BackColor = Color.Azure,
// In this case, the url is already stored here...
ImageLocation = url,
// ...but here are a couple of other ID options.
Name = $"pictureBox{++id}",
Tag = $"Tag Identifier {id}",
Padding = new Padding(10),
};
dynamicPB.Click += onAnyPictureBoxClick;
flowLayoutPanel.Controls.Add(dynamicPB);
}
}
.
.
.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.