开发者

How to record button clicks on Windows Phone and play back the sequence

I'm working on an app 开发者_高级运维for the Windows Phone 7 that plays sounds when certain buttons are clicked. I would like to be able to 'record' the sequence of buttons that are clicked so that it will appear to play back what they 'composed'. I'm assuming that some sort of timer would be used to keep track of the clicks and then you could replicate the clicks later on. I just can't seem to get going in the right direction. I appreciate any suggestions or examples.


I would hook up all your button to the same ICommand or Click event handler. Then in that handler add a record of the click to a Queue before doing something with it.

public class RecordedEvent
{
    public Button Button { get; set; } 
    public TimeSpan DelayTime { get; set; }
}

private Queue<RecordedEvent> _clickQueue = new Queue<RecordedEvent>();

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    var clickTime = DateTime.Now;

    //record the click by adding it to the queue
    _clickQueue.Enqueue(new RecordedEvent()
         { 
             Button = button,
             DelayTime = _lastClickTime - clickTime;
          };
    _lastClickTime = clickTime;

    DoAction(button); //do what ever needs to be done when the button it clicked
}

Then to play back it's a matter of pulling items back out of the queue.

public void PlayBack()
{
   var recordedClick = _clickQueue.Dequeue();
   while (recordedClick != null)
   {
       Thread.Sleep(recordedClick.DelayTime);
       DoAction(recordedClick.Button);
       recordedClick = _clickQueue.Dequeue();
   }
}

Now that isn't a perfect solution by any stretch (you need to make sure _lastClickTime is set correctly first time round, etc). But this is along the lines of how I would implement it.

The other problem is that Thread.Sleep() is going to block your UI which is bad, so you could possibly use a timer as you suggest. Depending on the resolution you need this may or may not be viable. Another option would be to have a background thread read the Queue and then use the Dispatcher to call DoAction() (calling Thread.Sleep() is fine on a background thread), but bear in mind that Queue is not thread safe so you would need to add synchronization logic yourself.

Anyway that should get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜