-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowInfo.cs
More file actions
80 lines (69 loc) · 2.18 KB
/
WindowInfo.cs
File metadata and controls
80 lines (69 loc) · 2.18 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
using System.Text.Json;
namespace MonitorWindowsRestore;
public class WindowInfo
{
public string ProcessName { get; set; } = "";
public string WindowTitle { get; set; } = "";
public string Id { get; set; } = "";
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public bool IsMaximized { get; set; }
public int ZOrder { get; set; }
public static string GenerateId(string processName, string windowTitle)
{
var hash = windowTitle.GetHashCode();
return $"{processName}_{hash:X8}";
}
}
public class WindowState
{
public Dictionary<string, WindowInfo> Windows { get; set; } = [];
public DateTime LastUpdated { get; set; } = DateTime.Now;
[System.Text.Json.Serialization.JsonIgnore]
private readonly object _lock = new();
private static readonly string StatePath = Path.Combine(
AppContext.BaseDirectory, "window-state.json");
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true
};
public static WindowState Load()
{
if (!File.Exists(StatePath))
return new WindowState();
try
{
var json = File.ReadAllText(StatePath);
return JsonSerializer.Deserialize<WindowState>(json, JsonOptions) ?? new WindowState();
}
catch
{
return new WindowState();
}
}
public void Save()
{
lock (_lock)
{
LastUpdated = DateTime.Now;
// Take a snapshot of the dictionary for serialization to avoid concurrent modification
var snapshot = new WindowState
{
Windows = new Dictionary<string, WindowInfo>(Windows),
LastUpdated = LastUpdated
};
var json = JsonSerializer.Serialize(snapshot, JsonOptions);
File.WriteAllText(StatePath, json);
}
}
public void RemoveWindow(string id)
{
lock (_lock)
{
Windows.Remove(id);
}
Save();
}
}