时间:2016-03-05 19:50:52

标签: c# wpf

我正在尝试创建一个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,它运行良好

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用Timer:

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