PDA

View Full Version : حرفه ای: مشکل Cross-thread operation not valid



apkgames
چهارشنبه 27 دی 1402, 15:43 عصر
با سلام خدمت اساتید
من یدونه فرم طراحی کردم که یک picturebox داره و تصویر رو از وبکم میگیرم و در اون نمایش میدم
بعد با استفاده از رویداد mousewheel اون رو zoom و unzoom می کنم.
وقتی که چندین بار عمل zoom و unzoom رو می کنم به یکباره برنامه قطع میشه و پیام خطای زیر نمایش داده میشه.

'Cross-thread operation not valid: Control 'pictureBox1' accessed from a thread other than the thread it was created on.'

namespace Taradod{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
pictureBox1.MouseWheel += new MouseEventHandler(pictureBox1_MouseWheel);
}
private void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
if (e.Delta > 0)
{
pictureBox1.Width += Convert.ToInt32(pictureBox1.Width * 120 / 1000);
pictureBox1.Height += Convert.ToInt32(pictureBox1.Height * 120 / 1000);
}
else
{
pictureBox1.Width -= Convert.ToInt32(pictureBox1.Width * 120 / 1000);
pictureBox1.Height -= Convert.ToInt32(pictureBox1.Height * 120 / 1000);


}
}


private FilterInfoCollection webcam;
private VideoCaptureDevice finalframe;







private void Form2_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevi ce);
foreach (FilterInfo vcd in webcam)
{
comboBox1.Items.Add(vcd.Name);
}
comboBox1.SelectedIndex = 3;
finalframe = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
finalframe.NewFrame += new NewFrameEventHandler(Finalframe_NewFrame);

finalframe.Start();
varibel.finalframestatus = "start";
}


private void Finalframe_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
//خطای رخ داده مربوط به خط پایین است
pictureBox1.Image= (Bitmap)eventArgs.Frame.Clone();
}


private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (varibel.finalframestatus =="start")
{
varibel.finalframestatus = "";
finalframe.Stop();

}
}


private void pictureBox1_MouseHover(object sender, EventArgs e)
{
pictureBox1.Focus();
}

}
}

پرستو پارسایی
چهارشنبه 27 دی 1402, 19:22 عصر
مشکل شما به دلیل دسترسی به کنترل pictureBox1 از یک نخ دیگر هست که در آن ایجاد نشده. برای رفع این مشکل، باید از روشهای مناسب برای دسترسی به کنترلها در نخهای متفاوت استفاده کنید.





private void Finalframe_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (pictureBox1.InvokeRequired)
{
pictureBox1.Invoke(new MethodInvoker(delegate
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}));
}
else
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
}

apkgames
چهارشنبه 27 دی 1402, 21:09 عصر
ممنونم از شما ، با راهنمایتان حل شد.