基本界面
主要功能
在指定的时间之后执行 关机|休眠|重启 的操作, 支持取消.
实现思路
使用了 Prism
来辅助实现mvvm模式, 主要用到了其中的 BindableBase
和 DelegateCommand
这两个类.
关机|睡眠|重启 使用 Shutdown.exe
实现. 代码里提取了 IPowerManager
这个接口, 然后 WinPowerManager
这个类实现功能.
namespace WinPowerHelper.Core.Interfaces
{
using System;
public interface IPowerManager
{
/// <summary>
/// 立刻关机
/// </summary>
void Shutdown();
/// <summary>
/// 等待<param name="interval"></param>时间后关机
/// </summary>
/// <param name="interval"></param>
void Shutdown(TimeSpan interval);
/// <summary>
/// 让电脑立即休眠
/// </summary>
void Sleep();
/// <summary>
/// 在等待<param name="interval"></param>时间后, 立即休眠
/// </summary>
/// <param name="interval"></param>
void Sleep(TimeSpan interval);
/// <summary>
/// 立即重启
/// </summary>
void Restart();
/// <summary>
/// 在等待<param name="interval"></param>时间后, 立即重启
/// </summary>
/// <param name="interval"></param>
void Restart(TimeSpan interval);
}
}
namespace WinPowerHelper.Core.Services
{
using System;
using System.Diagnostics;
using WinPowerHelper.Core.Interfaces;
public class WinPowerManager: IPowerManager
{
private const string ShutdownCmd = "shutdown.exe";
private WinPowerManager() { }
private static readonly object _lock = new object();
private static WinPowerManager _instance;
public static WinPowerManager Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
_instance = new WinPowerManager();
}
}
return _instance;
}
}
public void Shutdown()
{
Process.Start(ShutdownCmd, "-s");
}
public void Shutdown(TimeSpan interval)
{
Process.Start(ShutdownCmd, $"-s -t {interval.TotalSeconds}");
}
public void Sleep()
{
Process.Start(ShutdownCmd, "-h");
}
public void Sleep(TimeSpan interval)
{
Process.Start(ShutdownCmd, $"-h -t {interval.TotalSeconds}");
}
public void Restart()
{
Process.Start(ShutdownCmd, "-r");
}
public void Restart(TimeSpan interval)
{
Process.Start(ShutdownCmd, $"-r -t {interval.TotalSeconds}");
}
}
}
一些问题
- 数据绑定时, 如果用到值转换器(IValueConverter), 需要传递
ConverterParameter
时, 如何传递字符串?
xaml中绑定代码如下:
"{Binding ElementName=timer, Path=IsTiming, Converter={StaticResource BoolToStringConverter}, ConverterParameter='取消;开始'}"
C#值转换器代码如下:
namespace WinPowerHelper.Wpf.Extensions
{
using System;
using System.Globalization;
using System.Windows.Data;
public class BoolToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(bool)) return new InvalidCastException();
var splitText = (parameter as string).Split(';');
if (splitText == null || splitText.Length != 2)
return value; // 转换失败
return ((bool) value) ? splitText[0] : splitText[1];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}