In Windows 10 the light sensor is a type of environmental sensor that allow apps to respond to changes in the user's environment.
An ambient light sensor is used to extend battery life and enables easy-to-view display that is optimized to the environment in portable devices such as tablets, smartphones, and laptops.
It is very helpful to conserve battery life for mobile phones.
Let’s see the steps:
- Create a new Windows 10 universal app.
- Design the UI according to your wish; here I have created one button to start the light sensor reading.
- Now go to the coding part and write the following code. Firstly, add the following namespace to access the Light sensor API.
- using Windows.Devices.Sensors;
- Create one object for the LightSensor,
- LightSensor mylightSensor;
- Now get the default properties and reading using GetDefault method.
- mylightSensor = LightSensor.GetDefault();
- Then set interval to read the value from certain interval.
- mylightSensor.ReportInterval = 15;
Now create one event light sensor reading changes to handle the readings and assign it to your light sensor.
- mylightSensor.ReadingChanged += MylightSensor_ReadingChanged;
Now start the application and get the values from the light sensor.
To read the light sensor value use
LightSensorReadingclass or formatted string.
Full code looks like the following code.
- LightSensor mylightSensor;
- publicasyncvoid StartLightSensor() {
- mylightSensor = LightSensor.GetDefault();
- mylightSensor.ReportInterval = 15;
- mylightSensor.ReadingChanged += MylightSensor_ReadingChanged;
- }
-
- privatevoid MylightSensor_ReadingChanged(LightSensor sender, LightSensorReadingChangedEventArgs args) {
- LightSensorReading read = args.Reading;
- string values = String.Format("Light Sensor Reading:\t{0}\t{1}", args.Reading.Timestamp.ToString(), args.Reading.IlluminanceInLux.ToString());
- }
Read more articles on
Windows 10: