using System; using System.Drawing; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; internal sealed class MainForm : Form { private const string AppName = "每日文件同步"; private readonly TextBox source = new TextBox { AccessibleName = "源目录" }; private readonly TextBox destination = new TextBox { AccessibleName = "目标目录" }; private readonly DateTimePicker time = new DateTimePicker { AccessibleName = "每日同步时间", Format = DateTimePickerFormat.Custom, CustomFormat = "HH:mm", ShowUpDown = true, Width = 95 }; private readonly CheckBox launchAtLogin = new CheckBox { Text = "开机自动启动", AutoSize = true, Anchor = AnchorStyles.Left }; private readonly Label nextRun = new Label { AutoSize = true, Margin = new Padding(3, 10, 3, 10) }; private readonly TextBox status = new TextBox { AccessibleName = "同步状态", Multiline = true, ReadOnly = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical }; private readonly Button selectSource = new Button { Text = "浏览…", AutoSize = true }; private readonly Button selectDestination = new Button { Text = "浏览…", AutoSize = true }; private readonly Button save = new Button { Text = "保存设置", AutoSize = true }; private readonly Button sync = new Button { Text = "立即同步", AutoSize = true }; private readonly ContextMenuStrip trayMenu = new ContextMenuStrip(); private readonly NotifyIcon tray; private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer { Interval = 1000 }; private SyncSettings settings; private CancellationTokenSource activeSync; private bool exiting; private bool allowClose; private bool trayHintShown; public MainForm() { Text = AppName; Icon = SystemIcons.Application; StartPosition = FormStartPosition.CenterScreen; AutoScaleMode = AutoScaleMode.Dpi; ClientSize = new Size(610, 370); MinimumSize = new Size(490, 365); BuildLayout(); selectSource.Click += (sender, args) => Browse(source, "选择源目录"); selectDestination.Click += (sender, args) => Browse(destination, "选择目标目录"); save.Click += (sender, args) => { if (SaveSettings()) { status.Text = "设置已保存。"; CheckSchedule(); } }; sync.Click += (sender, args) => { if (SaveSettings()) StartSync(null); }; ToolStripItem open = trayMenu.Items.Add("打开窗口", null, (sender, args) => OpenWindow()); open.Font = new Font(open.Font, FontStyle.Bold); trayMenu.Items.Add(new ToolStripSeparator()); trayMenu.Items.Add("退出程序", null, (sender, args) => ExitProgram()); tray = new NotifyIcon { Text = AppName, Icon = Icon, ContextMenuStrip = trayMenu, Visible = true }; tray.DoubleClick += (sender, args) => OpenWindow(); FormClosing += HideOrClose; timer.Tick += (sender, args) => CheckSchedule(); LoadSettings(); try { launchAtLogin.Checked = StartupRegistration.IsEnabled(); } catch (Exception error) { status.AppendText("\r\n无法读取开机自动启动设置。\r\n" + error.Message); } launchAtLogin.Click += (sender, args) => ChangeStartupSetting(); } public void Start(bool startInTray) { if (startInTray) CreateHandle(); // Keep the form hidden while allowing Close to raise FormClosed. else Show(); timer.Start(); } private void ChangeStartupSetting() { bool enabled = launchAtLogin.Checked; try { StartupRegistration.SetEnabled(enabled); } catch (Exception error) { launchAtLogin.Checked = !enabled; MessageBox.Show(this, error.Message, "无法更新开机自动启动设置", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void BuildLayout() { TableLayoutPanel panel = new TableLayoutPanel { Dock = DockStyle.Fill, Padding = new Padding(14), ColumnCount = 3, RowCount = 7 }; panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); for (int row = 0; row < 6; row++) panel.RowStyles.Add(new RowStyle(SizeType.AutoSize)); panel.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); AddField(panel, 0, "源目录", source, selectSource); AddField(panel, 1, "目标目录", destination, selectDestination); panel.Controls.Add(FieldLabel("每日同步时间"), 0, 2); time.Anchor = AnchorStyles.Left; panel.Controls.Add(time, 1, 2); panel.Controls.Add(launchAtLogin, 0, 3); panel.SetColumnSpan(launchAtLogin, 3); FlowLayoutPanel actions = new FlowLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, WrapContents = false, FlowDirection = FlowDirection.RightToLeft, Margin = new Padding(0, 8, 0, 0) }; actions.Controls.Add(sync); actions.Controls.Add(save); panel.Controls.Add(actions, 0, 4); panel.SetColumnSpan(actions, 3); panel.Controls.Add(nextRun, 0, 5); panel.SetColumnSpan(nextRun, 3); panel.Controls.Add(status, 0, 6); panel.SetColumnSpan(status, 3); Controls.Add(panel); } private static Label FieldLabel(string label) { return new Label { Text = label, AutoSize = true, Anchor = AnchorStyles.Left }; } private static void AddField(TableLayoutPanel panel, int row, string label, TextBox input, Button browse) { panel.Controls.Add(FieldLabel(label), 0, row); input.Anchor = AnchorStyles.Left | AnchorStyles.Right; panel.Controls.Add(input, 1, row); panel.Controls.Add(browse, 2, row); } private void Browse(TextBox input, string description) { using (FolderBrowserDialog dialog = new FolderBrowserDialog()) { dialog.Description = description; if (Directory.Exists(input.Text)) dialog.SelectedPath = input.Text; if (dialog.ShowDialog(this) == DialogResult.OK) input.Text = dialog.SelectedPath; } } private void LoadSettings() { try { settings = SyncSettings.Load(); status.Text = settings.IsConfigured ? "等待同步。" : "选择源目录和目标目录,设置每日同步时间后保存。"; } catch (Exception error) { settings = new SyncSettings(); status.Text = "无法读取设置。请重新填写并保存。" + Environment.NewLine + error.Message; } source.Text = settings.Source; destination.Text = settings.Destination; time.Value = DateTime.Today.AddMinutes(settings.ScheduledMinute); UpdateNextRun(DateTime.Now); } private bool SaveSettings() { try { string sourcePath = source.Text; string targetPath = destination.Text; SyncEngine.ValidatePaths(ref sourcePath, ref targetPath); bool sameFolders = String.Equals(settings.Source, sourcePath, StringComparison.OrdinalIgnoreCase) && String.Equals(settings.Destination, targetPath, StringComparison.OrdinalIgnoreCase); SyncSettings updated = new SyncSettings { Source = sourcePath, Destination = targetPath, ScheduledMinute = time.Value.Hour * 60 + time.Value.Minute, LastScheduledDate = sameFolders ? settings.LastScheduledDate : DateTime.MinValue }; updated.Save(); settings = updated; source.Text = sourcePath; destination.Text = targetPath; UpdateNextRun(DateTime.Now); return true; } catch (Exception error) { MessageBox.Show(this, error.Message, "无法保存设置", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } } private void UpdateNextRun(DateTime now) { if (!settings.IsConfigured) { nextRun.Text = "尚未设置每日同步"; return; } DateTime day = settings.LastScheduledDate.Date >= now.Date ? settings.LastScheduledDate.Date.AddDays(1) : now.Date; DateTime scheduled = day.AddMinutes(settings.ScheduledMinute); nextRun.Text = scheduled <= now ? "下次定时同步:等待开始" : "下次定时同步:" + scheduled.ToString("yyyy-MM-dd HH:mm"); } private void CheckSchedule() { if (activeSync != null || exiting) return; DateTime now = DateTime.Now; if (settings.IsDue(now)) StartSync(now.Date); else UpdateNextRun(now); } private async void StartSync(DateTime? scheduledDay) { if (activeSync != null || exiting) return; CancellationTokenSource cancellation = new CancellationTokenSource(); activeSync = cancellation; SetInputsEnabled(false); string mode = scheduledDay.HasValue ? "定时同步" : "手动同步"; status.Text = mode + "进行中…"; string sourcePath = settings.Source; string targetPath = settings.Destination; try { SyncResult result = await Task.Run(() => SyncEngine.Run(sourcePath, targetPath, cancellation.Token)); status.Text = String.Format("{0:yyyy-MM-dd HH:mm:ss} {1}{2}\r\n已复制 {3} 个文件,未变化 {4} 个,跳过链接 {5} 个,失败 {6} 项。", DateTime.Now, mode, result.Failed == 0 ? "完成" : "完成,存在失败项", result.Copied, result.Unchanged, result.SkippedLinks, result.Failed); if (result.Errors.Count > 0) status.AppendText("\r\n\r\n" + String.Join("\r\n\r\n", result.Errors)); if (result.Failed > result.Errors.Count) status.AppendText("\r\n\r\n另有 " + (result.Failed - result.Errors.Count) + " 项失败。"); } catch (OperationCanceledException) { status.Text = mode + "已取消。"; scheduledDay = null; } catch (Exception error) { status.Text = mode + "失败。" + Environment.NewLine + error.Message; } finally { if (scheduledDay.HasValue) { settings.LastScheduledDate = scheduledDay.Value; try { settings.Save(); } catch (Exception error) { status.AppendText("\r\n无法保存本次定时同步记录。\r\n" + error.Message); } } activeSync = null; cancellation.Dispose(); if (exiting) FinishExit(); else { SetInputsEnabled(true); UpdateNextRun(DateTime.Now); } } } private void SetInputsEnabled(bool enabled) { source.Enabled = destination.Enabled = time.Enabled = enabled; selectSource.Enabled = selectDestination.Enabled = save.Enabled = sync.Enabled = enabled; } private void HideOrClose(object sender, FormClosingEventArgs args) { if (allowClose || args.CloseReason == CloseReason.WindowsShutDown || args.CloseReason == CloseReason.TaskManagerClosing) return; args.Cancel = true; Hide(); if (trayHintShown) return; trayHintShown = true; tray.ShowBalloonTip(2500, AppName, "程序仍在通知区域运行。右键图标可打开窗口或退出。", ToolTipIcon.Info); } private void OpenWindow() { if (exiting) return; Show(); if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; Activate(); } private void ExitProgram() { if (exiting) return; exiting = true; timer.Stop(); if (activeSync == null) FinishExit(); else { status.Text = "正在取消同步并退出…"; activeSync.Cancel(); } } private void FinishExit() { allowClose = true; tray.Visible = false; Close(); } protected override void Dispose(bool disposing) { if (disposing) { timer.Dispose(); tray.Dispose(); trayMenu.Dispose(); } base.Dispose(disposing); } }