-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogWindow.cs
75 lines (72 loc) · 2.1 KB
/
LogWindow.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KeyInputMacro
{
public partial class LogWindow : Form
{
public LogWindow()
{
InitializeComponent();
}
private void LogWindow_Shown(object sender, EventArgs e)
{
foreach (string log in Logger.logs)
{
LogList.Items.Add(log);
Application.DoEvents();
}
Logger.LogUpdateToUI += LogUpdateToUI;
LogListAutoScroll();
}
void LogUpdateToUI(string newLog)
{
this.Invoke(new Action(() =>
{
LogList.Items.Add(newLog);
LogListAutoScroll();
}));
}
void LogListAutoScroll()
{
LogList.SelectedIndex = LogList.Items.Count - 1;
}
private void LogWindow_FormClosing(object sender, FormClosingEventArgs e)
{
Logger.LogUpdateToUI -= LogUpdateToUI;
}
}
public struct Logger
{
public delegate void AddNewLog(string newLog);
/// <summary>
/// 将更新的日志数据同步至UI
/// </summary>
public static event AddNewLog? LogUpdateToUI;
#pragma warning disable CA2211
public static List<string> logs = [];
#pragma warning restore CA2211
/// <summary>
/// 添加日志
/// </summary>
/// <param name="message">日志内容</param>
public static void LogAdd(string message)
{
Thread t = new(() =>
{
logs.Add(GetTime() + message);
LogUpdateToUI?.Invoke(logs[^1]);//如果委托不为null,则调用。参数为数组的最后一位
});t.Start();//日志编写另起线程进行
}
static string GetTime()
{
return DateTime.Now.ToString("[yyyy/MM/dd HH:mm:ss.fff] ");
}
}
}