feat: 添加暂停和恢复功能以优化工作计时管理
This commit is contained in:
@@ -17,6 +17,10 @@ namespace TimerApp
|
||||
private TimeSpan _accumulatedWorkTime;
|
||||
private DateTime _restStartTime;
|
||||
private int _restElapsedSeconds; // 休息已过秒数(用于避免时间计算导致的跳变)
|
||||
private bool _isPaused = false; // 暂停状态
|
||||
private DateTime _pauseStartTime; // 暂停开始时间
|
||||
private TimeSpan _pauseDuration = TimeSpan.Zero; // 累计暂停时间(用于工作计时)
|
||||
private int _restPauseStartSeconds = 0; // 休息暂停时的已过秒数
|
||||
|
||||
// 配置 (默认值)
|
||||
public TimeSpan WorkDuration { get; set; } = TimeSpan.FromMinutes(20);
|
||||
@@ -24,6 +28,7 @@ namespace TimerApp
|
||||
public TimeSpan IdleThreshold { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
public MonitorState CurrentState { get; private set; } = MonitorState.Idle;
|
||||
public bool IsPaused { get; private set; } = false;
|
||||
|
||||
// 事件
|
||||
public event EventHandler<TimeSpan> WorkProgressChanged; // 剩余工作时间
|
||||
@@ -68,6 +73,12 @@ namespace TimerApp
|
||||
|
||||
private void Timer_Tick(object sender, EventArgs e)
|
||||
{
|
||||
// 如果处于暂停状态,不处理计时逻辑
|
||||
if (_isPaused)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
long idleMs = NativeMethods.GetIdleTime();
|
||||
TimeSpan idleTime = TimeSpan.FromMilliseconds(idleMs);
|
||||
|
||||
@@ -188,6 +199,9 @@ namespace TimerApp
|
||||
{
|
||||
_accumulatedWorkTime = TimeSpan.Zero;
|
||||
_lastWorkStartTime = DateTime.Now;
|
||||
_isPaused = false;
|
||||
IsPaused = false;
|
||||
_pauseDuration = TimeSpan.Zero;
|
||||
|
||||
// Ensure timer is running
|
||||
if (!_timer.Enabled) _timer.Start();
|
||||
@@ -198,5 +212,51 @@ namespace TimerApp
|
||||
// Immediately refresh UI to show full duration
|
||||
RefreshStatus();
|
||||
}
|
||||
|
||||
public void Pause()
|
||||
{
|
||||
if (!_isPaused && CurrentState != MonitorState.Idle)
|
||||
{
|
||||
_isPaused = true;
|
||||
IsPaused = true;
|
||||
_pauseStartTime = DateTime.Now;
|
||||
|
||||
// 如果正在休息,记录当前已过秒数
|
||||
if (CurrentState == MonitorState.Resting)
|
||||
{
|
||||
_restPauseStartSeconds = _restElapsedSeconds;
|
||||
}
|
||||
|
||||
StateChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
public void Resume()
|
||||
{
|
||||
if (_isPaused)
|
||||
{
|
||||
_isPaused = false;
|
||||
IsPaused = false;
|
||||
|
||||
// 计算暂停时长
|
||||
TimeSpan pauseTime = DateTime.Now - _pauseStartTime;
|
||||
|
||||
// 如果正在工作,将暂停时间累加到暂停总时长中
|
||||
// 这样工作时间就不会因为暂停而减少
|
||||
if (CurrentState == MonitorState.Working)
|
||||
{
|
||||
_pauseDuration += pauseTime;
|
||||
}
|
||||
// 如果正在休息,调整已过秒数,使剩余时间保持不变
|
||||
else if (CurrentState == MonitorState.Resting)
|
||||
{
|
||||
// 保持已过秒数不变,这样恢复后剩余时间不会变化
|
||||
// _restElapsedSeconds 保持不变
|
||||
}
|
||||
|
||||
StateChanged?.Invoke(this, EventArgs.Empty);
|
||||
RefreshStatus();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user