I'm trying to add custom controls on a secondary thread, but when I close the window while the thread is still running i get this exception:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
I don't know if the reason for getting this exception is because of a missused thread or becuse I'm closing the window while the thread is still running.
this is the code that i get the exception for:
panelWall.Invoke(new Action(() =>
{
postControl = new FBPostUserControl(m_LoggedInUser.Name, m_LoggedInUser.ImageNormal, post.CreatedTime);
postControl.PostBody = post.Message;
postControl.Image = postImage;
postControl.Dock = DockStyle.Top;
postControl.BringToFront();
}));
this is the code of my custom control:
public partial class FBPostUserControl : UserControl
{
private readonly string m_UserName = string.Empty;
private readonly Image m_UserProfileImage = null;
private readonly DateTime? m_DatePosted = null;
private Image m_Image = null;
private string m_PostBody = string.Empty;
public string UserName
{
get { return m_UserName; }
}
public DateTime? DatePosted
{
get { return m_DatePosted; }
}
public Image Image
{
get { return m_Image; }
set
{
if (value == null)
{
pictureBoxImage.Visible = false;
}
else
{
pictureBoxImage.Visible = true;
pictureBoxImage.Image = value;
updateImageSize();
}
}
}
private void updateImageSize()
{
if (pictureBoxImage.Image != null)
{
double ratio = pictureBoxImage.Image.Width / pictureBoxImage.Image.Height;
pictureBoxImage.Height = (int)(pictureBoxImage.Width / ratio);
pictureBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
}
}
public string PostBody
{
get { return m_PostBody; }
set
{
if (string.IsNullOrWhiteSpace(value) == false)
{
labelPostBody.Visible = true;
labelPostBody.Text = value;
}
else
{
labelPostBody.Visible = false;
}
}
}
public Image UserProfileImage
{
get { return m_UserProfileImage; }
}
public FBPostUserControl(string i_Name, Image i_ProfileImage, DateTime? i_PostDate)
{
InitializeComponent();
m_UserName = i_Name;
m_UserProfileImage = i_ProfileImage;
m_DatePosted = i_PostDate;
refreshHeader();
}
private void refreshHeader()
{
pictureBoxUserImage.Image = m_UserProfileImage;
labelName.Text = m_UserName;
if (labelDate != null)
{
labelDate.Text = m_DatePosted.ToString();
}
else
{
labelDate.Visible = false;
}
}
}