<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<Button Content="獲取電池狀態信息" Click="Button_Click" />
<TextBlock x:Name="tbInfo" FontSize="25" />
</StackPanel>
</Grid>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp14.Resources;
using Windows.Phone.Devices.Power;
namespace PhoneApp14
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// 獲取當前手機默認電池的Battery實例
var myBattery = Battery.GetDefault();
// 獲取剩余電量
int pc = myBattery.RemainingChargePercent;
// 獲取剩余續航時間
TimeSpan tsp = myBattery.RemainingDischargeTime;
string msg = string.Format("當前可用電量:{0}%\n 估計剩余時間:{1}天{2}小時{3}分{4}秒", pc, tsp.Days, tsp.Hours, tsp.Minutes, tsp.Seconds);
this.tbInfo.Text = msg;
}
}
}