Repository navigation
Expand file tree
/
Copy pathLightStart.cs
More file actions
146 lines (145 loc) · 12.7 KB
/
Copy pathLightStart.cs
File metadata and controls
146 lines (145 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Security.Principal;
using System.Windows.Forms;
namespace LightStart {
public sealed class Rule {
public string Id, File, Time;
public bool Daily;
public string When { get { return Daily ? "每天 " + Time + " 重启" : "登录时打开"; } }
}
public class Rules {
static string Prefix { get { return "LightStart-" + WindowsIdentity.GetCurrent().User.Value + "-"; } }
readonly dynamic service, folder;
public Rules() {
service = Activator.CreateInstance(Type.GetTypeFromProgID("Schedule.Service", true));
service.Connect(); folder = service.GetFolder(@"\");
}
public List<Rule> Read() {
var result = new List<Rule>();
foreach (dynamic task in folder.GetTasks(0)) {
string id = task.Name;
if (!id.StartsWith(Prefix, StringComparison.Ordinal)) continue;
dynamic def = task.Definition, tr = def.Triggers.Item(1);
bool daily = (int)tr.Type == 2;
result.Add(new Rule { Id=id, File=(string)def.RegistrationInfo.Description, Daily=daily,
Time=daily ? ((string)tr.StartBoundary).Substring(11,5) : "09:00" });
}
result.Sort(delegate(Rule a, Rule b) {return String.Compare(a.File,b.File,StringComparison.CurrentCultureIgnoreCase);});
return result;
}
public void Save(Rule r) {
dynamic def = service.NewTask(0);
string user = WindowsIdentity.GetCurrent().Name;
def.Principal.UserId = user; def.Principal.LogonType = 3; // Interactive token, no password.
def.RegistrationInfo.Description = r.File;
def.Settings.DisallowStartIfOnBatteries = false; def.Settings.StopIfGoingOnBatteries = false;
dynamic tr = def.Triggers.Create(r.Daily ? 2 : 9);
if (r.Daily) {
tr.DaysInterval = 1; tr.StartBoundary = DateTime.Today.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) + "T" + r.Time + ":00";
} else tr.UserId = user;
dynamic action = def.Actions.Create(0);
action.Path = Application.ExecutablePath;
action.Arguments = (r.Daily ? "--restart " : "--open ") + "\"" + r.File + "\"";
string id = r.Id ?? Prefix + Guid.NewGuid().ToString("N");
folder.RegisterTaskDefinition(id, def, 6, user, null, 3, null); r.Id = id;
}
public void Remove(Rule r) {folder.DeleteTask(r.Id, 0);}
}
static class Program {
[STAThread] static void Main(string[] args) {
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
try {
if (args.Length==2 && (args[0]=="--open" || args[0]=="--restart")) { Launch(args[1],args[0]=="--restart"); return; }
Application.Run(new Home(args.Length==1 ? args[0] : null));
} catch(Exception e) { Error(e); Environment.ExitCode=1; }
}
internal static void Error(Exception e) {MessageBox.Show(e.Message,"轻启 · 操作未完成",MessageBoxButtons.OK,MessageBoxIcon.Warning);}
internal static bool IsExe(string p) {return String.Equals(Path.GetExtension(p),".exe",StringComparison.OrdinalIgnoreCase);}
internal static void Launch(string file,bool restart) {
if(!File.Exists(file)) throw new FileNotFoundException("找不到文件,请检查它是否已移动:\n"+file);
if(restart) {
if(!IsExe(file) || String.Equals(file,Application.ExecutablePath,StringComparison.OrdinalIgnoreCase)) throw new Exception("请选择其他 EXE 程序作为重启目标。");
var matches = new List<Process>(); int session=Process.GetCurrentProcess().SessionId;
Process[] candidates=Process.GetProcessesByName(Path.GetFileNameWithoutExtension(file));
try {
foreach(Process p in candidates) {
try { if(p.SessionId==session && String.Equals(p.MainModule.FileName,file,StringComparison.OrdinalIgnoreCase)) matches.Add(p); }
catch(InvalidOperationException) { /* Already exited. */ }
}
if(matches.Count>0) {
// Close only a single identifiable main window, never kill background workers.
Process main=null;
foreach(Process p in matches) if(!p.HasExited && p.MainWindowHandle!=IntPtr.Zero) {
if(main!=null) throw new Exception("程序有多个主窗口,本次未重启:\n"+file); main=p;
}
if(main==null || !main.CloseMainWindow() || !main.WaitForExit(15000)) throw new Exception("程序未正常退出,本次未重启。若有未保存的工作,请先处理:\n"+file);
}
} finally {foreach(Process p in candidates) p.Dispose();}
}
Process.Start(new ProcessStartInfo(file){UseShellExecute=true,WorkingDirectory=Path.GetDirectoryName(file)});
}
}
class Home : Form {
readonly ListView list=new ListView(); readonly Label status=new Label(); readonly Button edit=new Button(), remove=new Button();
Rules rules; readonly string initial;
static readonly Color Ink=Color.FromArgb(29,47,55), Accent=Color.FromArgb(20,102,88);
internal static void StyleButton(Button b,string text,bool primary) {
b.Text=text; b.AutoSize=true; b.Padding=new Padding(8,3,8,3); b.FlatStyle=FlatStyle.Flat;
b.BackColor=primary?Accent:Color.White; b.ForeColor=primary?Color.White:Ink; b.FlatAppearance.BorderColor=primary?Accent:Color.Silver;
}
static Label TextLine(string s,float size,bool bold) {return new Label {Text=s,Dock=DockStyle.Fill,TextAlign=ContentAlignment.MiddleLeft,Font=new Font("Microsoft YaHei UI",size,bold?FontStyle.Bold:FontStyle.Regular),ForeColor=Ink};}
public Home(string first) {
initial=first; Text="轻启 · 自启与定时重启"; StartPosition=FormStartPosition.CenterScreen; AutoScaleMode=AutoScaleMode.Dpi;
Font=new Font("Microsoft YaHei UI",10); BackColor=Color.White; ClientSize=new Size(770,490); MinimumSize=new Size(625,430);
var grid=new TableLayoutPanel {Dock=DockStyle.Fill,Padding=new Padding(24,16,24,12),ColumnCount=1,RowCount=6}; Controls.Add(grid);
foreach(int h in new int[]{48,78,50,-1,48,29}) grid.RowStyles.Add(h<0?new RowStyle(SizeType.Percent,100):new RowStyle(SizeType.Absolute,h));
grid.Controls.Add(TextLine("轻启 / 启动规则",19,true),0,0);
var drop=new Panel{Dock=DockStyle.Fill,BackColor=Color.FromArgb(235,245,241),Padding=new Padding(15,10,12,10)};
var pick=new Button{Dock=DockStyle.Right}; StyleButton(pick,"选择文件…",true); pick.Click+=delegate { Pick(); };
var prompt=TextLine("将文件拖到这里,添加一条规则",11,false); drop.Controls.Add(prompt); drop.Controls.Add(pick); grid.Controls.Add(drop,0,1);
grid.Controls.Add(TextLine("我的规则",12,true),0,2);
list.Dock=DockStyle.Fill; list.View=View.Details; list.FullRowSelect=true; list.MultiSelect=false; list.HideSelection=false;
list.Columns.Add("文件",160); list.Columns.Add("执行时间",150); list.Columns.Add("位置",370); list.SizeChanged+=delegate{list.Columns[2].Width=Math.Max(160,list.ClientSize.Width-335);}; grid.Controls.Add(list,0,3);
var bar=new FlowLayoutPanel{Dock=DockStyle.Fill,Padding=new Padding(0,4,0,0)}; StyleButton(edit,"编辑规则",false); StyleButton(remove,"移除规则",false); bar.Controls.AddRange(new Control[]{edit,remove});grid.Controls.Add(bar,0,4);
edit.Click+=delegate {EditSelected();}; list.DoubleClick+=delegate{EditSelected();}; remove.Click+=delegate {var r=Selected(); if(r!=null) Guard(delegate {rules.Remove(r);RefreshList();});};
list.SelectedIndexChanged+=delegate{edit.Enabled=remove.Enabled=Selected()!=null;}; edit.Enabled=remove.Enabled=false;
status.Dock=DockStyle.Fill;status.TextAlign=ContentAlignment.MiddleLeft; status.ForeColor=Color.DimGray;grid.Controls.Add(status,0,5);
AllowDrop=true; DragEnter+=delegate(object s,DragEventArgs e){if(e.Data.GetDataPresent(DataFormats.FileDrop))e.Effect=DragDropEffects.Copy;};
DragDrop+=delegate(object s,DragEventArgs e){string[] files=(string[])e.Data.GetData(DataFormats.FileDrop); if(files!=null && files.Length==1) Configure(files[0],null); else status.Text="请一次拖入一个文件。";};
Shown+=delegate{Guard(delegate{rules=new Rules();RefreshList();if(initial!=null) Configure(initial,null);});};
}
void Guard(Action action){try{action();}catch(Exception e){Program.Error(e);}}
Rule Selected(){return list.SelectedItems.Count==0?null:(Rule)list.SelectedItems[0].Tag;}
void RefreshList(){var rows=rules.Read();list.Items.Clear();foreach(Rule r in rows){var row=new ListViewItem(new[]{Path.GetFileName(r.File),r.When,r.File});row.Tag=r;list.Items.Add(row);} status.Text=rows.Count==0?"还没有规则。先选择或拖入一个文件。":"共 "+rows.Count+" 条规则 · 关闭轻启后仍会生效";}
void Pick(){using(var d=new OpenFileDialog{Title="选择要打开或重启的文件",Filter="所有文件|*.*",DereferenceLinks=false}) if(d.ShowDialog(this)==DialogResult.OK)Configure(d.FileName,null);}
void EditSelected(){var r=Selected();if(r!=null) Configure(r.File,r);}
void Configure(string file,Rule old){Guard(delegate{
if(!File.Exists(file)) throw new Exception("请选择一个存在的文件,而不是文件夹。");
file=Path.GetFullPath(file);
using(var d=new Editor(file,old)){if(d.ShowDialog(this)!=DialogResult.OK)return;
var r=new Rule{Id=old==null?null:old.Id,File=file,Daily=d.Daily,Time=d.Clock};
if(rules==null)rules=new Rules();
foreach(var x in rules.Read()) if(x.Id!=r.Id && x.Daily==r.Daily && String.Equals(x.File,r.File,StringComparison.OrdinalIgnoreCase)) throw new Exception("这个文件已有相同类型的规则,请直接编辑已有规则。");
rules.Save(r);RefreshList();status.Text="已保存:"+Path.GetFileName(file)+" · "+r.When;
}
});}
}
class Editor:Form {
readonly RadioButton daily=new RadioButton(),login=new RadioButton();readonly DateTimePicker clock=new DateTimePicker();
public bool Daily{get{return daily.Checked;}}public string Clock{get{return clock.Value.ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture);}}
public Editor(string file,Rule old){Text=old==null?"添加规则":"编辑规则";Font=new Font("Microsoft YaHei UI",10);AutoScaleMode=AutoScaleMode.Dpi;StartPosition=FormStartPosition.CenterParent;FormBorderStyle=FormBorderStyle.FixedDialog;MaximizeBox=MinimizeBox=false;ClientSize=new Size(490,270);BackColor=Color.White;
var name=new Label{Text=Path.GetFileName(file),Font=new Font(Font,FontStyle.Bold),AutoEllipsis=true};name.SetBounds(20,15,450,25);
var path=new Label{Text=file,AutoEllipsis=true,ForeColor=Color.DimGray};path.SetBounds(20,42,450,25);
login.Text="登录 Windows 时打开";login.SetBounds(20,80,360,28);daily.Text="每天定时重启这个程序";daily.SetBounds(20,114,245,30);daily.Enabled=Program.IsExe(file)&&!String.Equals(file,Application.ExecutablePath,StringComparison.OrdinalIgnoreCase);
clock.Format=DateTimePickerFormat.Custom;clock.CustomFormat="HH:mm";clock.ShowUpDown=true;clock.SetBounds(275,116,95,28);
clock.Value=DateTime.Today.Add(TimeSpan.Parse(old==null?"09:00":old.Time));daily.CheckedChanged+=delegate{clock.Enabled=daily.Checked;};daily.Checked=old!=null&&old.Daily;login.Checked=!daily.Checked;clock.Enabled=daily.Checked;
var tip=new Label{Text=daily.Enabled?"定时重启仅在已登录时执行。程序没运行就打开;正在运行则先请求正常关闭,不强制结束。":"文档和快捷方式可以在登录时打开;定时重启请选择程序本身(.exe)。",ForeColor=Color.DimGray};tip.SetBounds(22,156,445,51);
var save=new Button{DialogResult=DialogResult.OK};Home.StyleButton(save,"保存规则",true);save.SetBounds(371,219,96,36);var cancel=new Button{DialogResult=DialogResult.Cancel};Home.StyleButton(cancel,"取消",false);cancel.SetBounds(277,219,82,36);AcceptButton=save;CancelButton=cancel;
Controls.AddRange(new Control[]{name,path,login,daily,clock,tip,cancel,save});
}
}
}