using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace XPUtilitiesPro.Core
{
public static class SynchronizeInvoke
{
public static void CustomInvoke<T>(this T @control, Action<T> toPerform) where T : ISynchronizeInvoke
{
if (@control.InvokeRequired)
@control.Invoke(toPerform, new object[] { @control });
else
toPerform(@control);
}
}
}
And when creating PictureBoxes at runtime and adding them to a Panel I use it like so
private void LoadWallpapers(Panel p, string folder)
{
progressBar1.CustomInvoke(p1 => p1.Visible = true);
progressBar1.CustomInvoke(p1 => p1.Enabled = true);
p.Controls.Clear();
int position = 0;
int count = 10;
string[] validExtensions = new string[] { ".jpg", ".bmp", ".gif", ".png" };
DirectoryInfo info = new DirectoryInfo(folder);
foreach (FileInfo f in info.GetFiles())
{
for (int i = 0; i < validExtensions.Length; i++)
{
if (f.Extension.ToString().ToLower() == validExtensions[i].ToLower())
{
PictureBox pb = new PictureBox();
pb.CustomInvoke(pic => pic.Name = "WallpaperPB" + count);
pb.CustomInvoke(pic => pic.Cursor = Cursors.Hand);
pb.CustomInvoke(pic => pic.Parent = p);
pb.CustomInvoke(pic => pic.Size = new Size(130, 98));
pb.CustomInvoke(pic => pic.SizeMode = PictureBoxSizeMode.StretchImage);
pb.CustomInvoke(pic => pic.Location = new Point(position + 10, 20));
pb.CustomInvoke(pic => pic.Image = Image.FromFile(f.FullName));
pb.CustomInvoke(pic => pic.Image.Tag = f.FullName);
pb.CustomInvoke(pic => pic.MouseHover += new EventHandler(pb_MouseHover));
pb.CustomInvoke(pic => pic.MouseLeave += new EventHandler(pb_MouseLeave));
pb.CustomInvoke(pic => pic.Click += new EventHandler(pb_Click));
position += 135;
count += 1;
}
}
}
label1.CustomInvoke(l=> l.Text = string.Format("Current Directory: {0}", folder));
progressBar1.CustomInvoke(p1 => p1.Visible = false);
progressBar1.CustomInvoke(p1 => p1.Enabled = false);
}
The invoke extension I use works because I use it on about 20 custom Panel controls in this application. The line that's giving the error is here
pb.CustomInvoke(pic => pic.Parent = p);
Anyone have any ideas on how I can execute this line without getting the cross-thread error?

New Topic/Question
Reply



MultiQuote



|