在Dispather计时器中访问Draw Context会产生异常

时间:2012-11-01 11:33:51

标签: c# wpf kinect drawingcontext

我想要做的是首先找到肩关节的角度,直到现在我已经设法做到了。我现在想要做的是当角度在70到90之间时,一个时间从3开始秒和每秒应检查角度是否仍然在范围内,如果它然后显示在屏幕上,否则重新启动计时器显示消息后你没有完成时间限制 请非常感谢C#和kinect对这方面的任何帮助都会有所帮助 面向问题的图像的链接是: http://i46.tinypic.com/2nu4ygw.jpg

请帮助!!

       System.Windows.Point shoul_l = this.point_toScreen(sh_left.Position, sen);
        draw.DrawText(new FormattedText(angle.ToString("0"), new 
        System.Globalization.CultureInfo("en-us"),
          System.Windows.FlowDirection.LeftToRight,
         new Typeface("Verdana"), 16,System.Windows.Media.Brushes.OrangeRed),
         new System.Windows.Point(shoul_l.X+10, shoul_l.Y +20));

        if (timer_start == false)
        {
        if (angle > 70 && angle < 90)
        {
                timer_start = true;
                timer.Interval = 2000;
                timer.Start();
                timer.Elapsed += new ElapsedEventHandler((sender, e) =>   \    
                on_time_event(sender, e, draw,shoul_l));

        }
        }


}   
void on_time_event(object sender, ElapsedEventArgs e, DrawingContext dcrt, 

 System.Windows.Point Shoudery_lefty)
 {
     --index;
     if (index != 0)
     {
         dcrt.DrawText(new FormattedText(index.ToString(), new   
      System.Globalization.CultureInfo("en-us"),
           System.Windows.FlowDirection.LeftToRight,
          new Typeface("Verdana"), 16, System.Windows.Media.Brushes.OrangeRed),
          new System.Windows.Point(Shoudery_lefty.X+50,Shoudery_lefty.Y+50));
      //  MessageBox.Show(index.ToString());
     }
     else
     {
         timer.Stop();
     }
   }

我在代码的这一部分得到了一个例外

      dcrt.DrawText(new FormattedText(index.ToString(), new   
      System.Globalization.CultureInfo("en-us"),
      System.Windows.FlowDirection.LeftToRight,
      new Typeface("Verdana"), 16, System.Windows.Media.Brushes.OrangeRed),
      new System.Windows.Point(Shoudery_lefty.X+50,Shoudery_lefty.Y+50));

1 个答案:

答案 0 :(得分:2)

您正在尝试从Timer主题更新UI元素。这是不允许的。
您必须使用Dispatcher封送UI更新调用UI线程,如下所示:

dcrt.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => 
    {
        dcrt.DrawText(new FormattedText(index.ToString(), new System.Globalization.CultureInfo("en-us"),
       System.Windows.FlowDirection.LeftToRight,
      new Typeface("Verdana"), 16, System.Windows.Media.Brushes.OrangeRed),
      new System.Windows.Point(Shoudery_lefty.X+50,Shoudery_lefty.Y+50));
    }));