For some reason we are getting "InvalidOperationException: Object is currently in use elsewhere."
during our custom OnPaint, below (that's actually almost a line for line copy of the code... there's that little there).
We have logging in the exception handler below to detect if we're somehow calling OnPaint from a non-UI thread... and that isn't getting tripped, but we are getting that error logged (see stack trace below).
On machines where we're getting these errors, we're also seeing the dreaded Red X of doom from other controls (which presumably don't have a try/catch around their OnPaints).
They're probably related, but I can't figure out what could be causing that error if this code is only called from the UI thread.
Any ideas?
This is the stack trace:
System.InvalidOperationException: Object is currently in use elsewhere.
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawRectangle(Pen pen, Int32 x, Int32 y, Int32 width, Int32 height)
at System.Windows.Forms.ControlPaint.DrawBorderSimple(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style)
at System.Windows.Forms.ControlPaint.DrawBorder(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style)
at MyUserControl.OnPaint(PaintEventArgs e)
This is the class:
public class MyUserControl : UserControl
{
// Override this to set your custom border color
protected Color mBorderColor = SystemColors.ControlDarkDark;
public MyeUserControl()
: base()
{
this.BorderStyle = BorderStyle.None;
this.Padding = new Padding(1);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
try
{
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, mBorderColor, ButtonBorderStyle.Solid);
}
catch (Exception ex)
{
// check if we're not on the UI thread, and if not, log it
// log exception
}
}
}