Stopping Kinect when pressing Stop Button in Visual Studio UI?-Collection of common programming errors

I’m using Kinect in a WPF app and Dan Fernández taught us in his quickstart video series how to stop the sensor when calling the event “Window_Closing” (which being new into C#, I guess it’s a delegate, or event handler). The thing is that if I press the Stop button in the Visual Studio UI to stop running, my Kinect doesn’t stop and then I have to run the app again and close it clicking on the X button.

Is there a more general way to stop the Kinect with some event for the app Shutdown inside my code?

Thank you.

    void StopKinect(KinectSensor sensor) {
        if (sensor != null) {
            sensor.Stop();

            if (sensor.AudioSource != null)
            {
                sensor.AudioSource.Stop();
            }
        }
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        StopKinect(kinectSensorChooser1.Kinect); 
    }
  1. When you click the Stop button on VS you interrupt the process. So the Windows_Closing event is never called. And the Kinect don’t stop.

  2. How are you defining whether the Kinect sensor has stopped?

    I reccomend adding exception handling around the method you are using to stop Kinect.

    try
    {
       StopKinect(kinectSensorChooser1.Kinect); 
    }
    catch(Exception ex)
    {
       //Log Exception
    }
    

    If the application was throwing an unhandled exception when attempting to stop the Kinect sensor this will give you a method of identifying it.

    Can you confirm whether the Window_Closing event fires? Add a breakpoint within the function and if this is not hit then you’ll know the problem. An alternative may be to clean up the Kinect Sensor with a different event as @Bob suggested. It’s possible that when VS stops debugging the process is killed and so the event you’ve included the cleanup code for is not invoked.