从线程以外的线程访问的 C# WPF 线程
本文关键字:线程 WPF 访问 | 更新日期: 2023-09-27 18:37:28
我正在尝试创建一个 WPF 应用程序,该应用程序在播放时每秒拍摄视频并截取一次屏幕截图。
法典
public Form2(string url)
{
InitializeComponent();
axWindowsMediaPlayer1.URL = url;
new Thread(delegate(){
CheckFrame();
}).Start();
}
private void CheckFrame()
{
for (int i = 0; i < 100; i++)
{
Bitmap screenshot = new Bitmap(axWindowsMediaPlayer1.Bounds.Width, axWindowsMediaPlayer1.Bounds.Height);
Graphics g = Graphics.FromImage(screenshot);
g.CopyFromScreen(axWindowsMediaPlayer1.PointToScreen(
new System.Drawing.Point()).X,
axWindowsMediaPlayer1.PointToScreen(
new System.Drawing.Point()).Y, 0, 0, axWindowsMediaPlayer1.Bounds.Size);
pictureBox1.BackgroundImage = screenshot;
System.Threading.Thread.Sleep(1000);
}
}
使用媒体播放器本身的 x y 值时,出现错误
Additional information: Cross-thread operation not valid: Control 'axWindowsMediaPlayer1'
accessed from a thread other than the thread it was created on.
当使用 0 作为 X/Y 值时,从形式的角度来看只有 0px 和 0px,它运行良好
在这种情况下,
您可以使用计时器:
Timer tm = new Timer();
public Form2(string url)
{
InitializeComponent();
axWindowsMediaPlayer1.URL = url;
tm.Interval = 1000;
tm.Tick += tm_Tick;
tm.Start();
}
int i = -1;
void tm_Tick(object sender, EventArgs e)
{
if (++i < 100)
{
Bitmap screenshot = new Bitmap(axWindowsMediaPlayer1.Bounds.Width, axWindowsMediaPlayer1.Bounds.Height);
Graphics g = Graphics.FromImage(screenshot);
g.CopyFromScreen(axWindowsMediaPlayer1.PointToScreen(
new System.Drawing.Point()).X,
axWindowsMediaPlayer1.PointToScreen(
new System.Drawing.Point()).Y, 0, 0, axWindowsMediaPlayer1.Bounds.Size);
pictureBox1.BackgroundImage = screenshot;
}
else
{
i = -1;
tm.Stop();
}
}
备注:要使用您的方法截屏,axWindowsMediaPlayer1
必须在屏幕上可见。