Change notify system, refactoring

This commit is contained in:
SlothDpal
2024-05-22 10:33:04 +03:00
parent 54ded84224
commit 15b185f6f5
3 changed files with 85 additions and 69 deletions

View File

@@ -33,6 +33,7 @@
this.chbxDiscordEnabled = new System.Windows.Forms.CheckBox(); this.chbxDiscordEnabled = new System.Windows.Forms.CheckBox();
this.textDwhURL = new System.Windows.Forms.TextBox(); this.textDwhURL = new System.Windows.Forms.TextBox();
this.lblDwhURL = new System.Windows.Forms.Label(); this.lblDwhURL = new System.Windows.Forms.Label();
this.btnClearUrlField = new System.Windows.Forms.Button();
this.SuspendLayout(); this.SuspendLayout();
// //
// btnOk // btnOk
@@ -43,7 +44,7 @@
this.btnOk.TabIndex = 0; this.btnOk.TabIndex = 0;
this.btnOk.Text = "Сохранить"; this.btnOk.Text = "Сохранить";
this.btnOk.UseVisualStyleBackColor = true; this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click); this.btnOk.Click += new System.EventHandler(this.BtnOk_Click);
// //
// btnCancel // btnCancel
// //
@@ -54,13 +55,13 @@
this.btnCancel.TabIndex = 1; this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Отменить"; this.btnCancel.Text = "Отменить";
this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); this.btnCancel.Click += new System.EventHandler(this.BtnCancel_Click);
// //
// chbxDiscordEnabled // chbxDiscordEnabled
// //
this.chbxDiscordEnabled.AutoSize = true; this.chbxDiscordEnabled.AutoSize = true;
this.chbxDiscordEnabled.Checked = true; this.chbxDiscordEnabled.Checked = global::RelaunchProcess.Properties.Settings.Default.dwhEnabled;
this.chbxDiscordEnabled.CheckState = System.Windows.Forms.CheckState.Checked; this.chbxDiscordEnabled.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::RelaunchProcess.Properties.Settings.Default, "dwhEnabled", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.chbxDiscordEnabled.Location = new System.Drawing.Point(12, 63); this.chbxDiscordEnabled.Location = new System.Drawing.Point(12, 63);
this.chbxDiscordEnabled.Name = "chbxDiscordEnabled"; this.chbxDiscordEnabled.Name = "chbxDiscordEnabled";
this.chbxDiscordEnabled.Size = new System.Drawing.Size(232, 17); this.chbxDiscordEnabled.Size = new System.Drawing.Size(232, 17);
@@ -70,10 +71,12 @@
// //
// textDwhURL // textDwhURL
// //
this.textDwhURL.DataBindings.Add(new System.Windows.Forms.Binding("Text", global::RelaunchProcess.Properties.Settings.Default, "dwhURL", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.textDwhURL.Location = new System.Drawing.Point(12, 37); this.textDwhURL.Location = new System.Drawing.Point(12, 37);
this.textDwhURL.Name = "textDwhURL"; this.textDwhURL.Name = "textDwhURL";
this.textDwhURL.Size = new System.Drawing.Size(337, 20); this.textDwhURL.Size = new System.Drawing.Size(337, 20);
this.textDwhURL.TabIndex = 3; this.textDwhURL.TabIndex = 3;
this.textDwhURL.Text = global::RelaunchProcess.Properties.Settings.Default.dwhURL;
// //
// lblDwhURL // lblDwhURL
// //
@@ -84,14 +87,26 @@
this.lblDwhURL.TabIndex = 4; this.lblDwhURL.TabIndex = 4;
this.lblDwhURL.Text = "URL-адрес Discord веб-хука"; this.lblDwhURL.Text = "URL-адрес Discord веб-хука";
// //
// btnClearUrlField
//
this.btnClearUrlField.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.btnClearUrlField.Location = new System.Drawing.Point(351, 38);
this.btnClearUrlField.Name = "btnClearUrlField";
this.btnClearUrlField.Size = new System.Drawing.Size(19, 19);
this.btnClearUrlField.TabIndex = 5;
this.btnClearUrlField.Text = "X";
this.btnClearUrlField.UseVisualStyleBackColor = true;
this.btnClearUrlField.Click += new System.EventHandler(this.BtnClearUrlField_Click);
//
// DiscordSettings // DiscordSettings
// //
this.AcceptButton = this.btnOk; this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel; this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(361, 128); this.ClientSize = new System.Drawing.Size(375, 128);
this.ControlBox = false; this.ControlBox = false;
this.Controls.Add(this.btnClearUrlField);
this.Controls.Add(this.lblDwhURL); this.Controls.Add(this.lblDwhURL);
this.Controls.Add(this.textDwhURL); this.Controls.Add(this.textDwhURL);
this.Controls.Add(this.chbxDiscordEnabled); this.Controls.Add(this.chbxDiscordEnabled);
@@ -104,7 +119,6 @@
this.ShowIcon = false; this.ShowIcon = false;
this.ShowInTaskbar = false; this.ShowInTaskbar = false;
this.Text = "Настройки Discord webhook"; this.Text = "Настройки Discord webhook";
this.Load += new System.EventHandler(this.DiscordSettings_Load);
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
@@ -117,5 +131,6 @@
private System.Windows.Forms.CheckBox chbxDiscordEnabled; private System.Windows.Forms.CheckBox chbxDiscordEnabled;
private System.Windows.Forms.TextBox textDwhURL; private System.Windows.Forms.TextBox textDwhURL;
private System.Windows.Forms.Label lblDwhURL; private System.Windows.Forms.Label lblDwhURL;
private System.Windows.Forms.Button btnClearUrlField;
} }
} }

View File

@@ -19,23 +19,19 @@ namespace RelaunchProcess
InitializeComponent(); InitializeComponent();
} }
private void DiscordSettings_Load(object sender, EventArgs e) private void BtnCancel_Click(object sender, EventArgs e)
{
chbxDiscordEnabled.Checked=Settings.Default.dwhEnabled;
textDwhURL.Text=Settings.Default.dwhURL;
}
private void btnCancel_Click(object sender, EventArgs e)
{ {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
} }
private void btnOk_Click(object sender, EventArgs e) private void BtnOk_Click(object sender, EventArgs e)
{ {
if (Uri.IsWellFormedUriString(textDwhURL.Text, UriKind.Absolute)) if (Uri.IsWellFormedUriString(textDwhURL.Text, UriKind.Absolute)||textDwhURL.Text=="")
{ {
Settings.Default.dwhEnabled = chbxDiscordEnabled.Checked; if (textDwhURL.Text=="")
Settings.Default.dwhURL = textDwhURL.Text; {
chbxDiscordEnabled.Checked = false;
}
Settings.Default.Save(); Settings.Default.Save();
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
@@ -43,9 +39,13 @@ namespace RelaunchProcess
else else
{ {
//TODO обработать ситуацию с неверным УРЛом //TODO обработать ситуацию с неверным УРЛом
MessageBox.Show("Неверный формат URL.", "URL", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
}
private void BtnClearUrlField_Click(object sender, EventArgs e)
{
textDwhURL.Text = "";
} }
} }
} }

103
Form1.cs
View File

@@ -18,17 +18,26 @@ namespace Process_Auto_Relaunch
{ {
public partial class Form1 : Form public partial class Form1 : Form
{ {
private delegate void UpdateLogDelegate(string text, bool add_history = false); [Flags]
private UpdateLogDelegate updateLogDelegate; public enum NotifyLevel
{
logNone = 0,
logAlways = 1, // ïèñàòü âåçäå
logUpdateStatus = 2, // ïèñàòü â ñòðîêå ñîñòîÿíèÿ
logHistory = 4, // ïèñàòü â îêíå èñòîðèè ïåðåçàïóñêîâ
logDiscord = 8 // ïèñàòü â Äèñêîðä
}
private delegate void UpdateLogDelegate(string text, NotifyLevel level = NotifyLevel.logUpdateStatus);
private readonly UpdateLogDelegate updateLogDelegate;
private DiscordWebhook dwhHook; private DiscordWebhook dwhHook;
private DiscordMessage dwhMessage; private DiscordMessage dwhMessage;
private DiscordSettings discordSettings;
public Form1() public Form1()
{ {
InitializeComponent(); InitializeComponent();
this.updateLogDelegate = this.UpdateStatus; this.updateLogDelegate = this.UpdateStatus;
this.updateLogDelegate += this.SendDiscordMessage; this.updateLogDelegate += this.SendDiscordMessage;
this.updateLogDelegate += this.HistoryLog;
myBackgroundWorker.WorkerSupportsCancellation = true; myBackgroundWorker.WorkerSupportsCancellation = true;
dwhHook = new DiscordWebhook(); dwhHook = new DiscordWebhook();
if ( Uri.IsWellFormedUriString(Settings.Default.dwhURL,UriKind.Absolute) && Settings.Default.dwhEnabled && Settings.Default.dwhURL!="") if ( Uri.IsWellFormedUriString(Settings.Default.dwhURL,UriKind.Absolute) && Settings.Default.dwhEnabled && Settings.Default.dwhURL!="")
@@ -87,7 +96,7 @@ namespace Process_Auto_Relaunch
if (myBackgroundWorker.WorkerSupportsCancellation && myBackgroundWorker.IsBusy) if (myBackgroundWorker.WorkerSupportsCancellation && myBackgroundWorker.IsBusy)
{ {
myBackgroundWorker.CancelAsync(); myBackgroundWorker.CancelAsync();
UpdateStatus("Îòìåíÿåì..."); UpdateStatus("Îòìåíÿåì...",NotifyLevel.logUpdateStatus);
} }
} }
@@ -136,24 +145,43 @@ namespace Process_Auto_Relaunch
/// </summary> /// </summary>
/// <param name="text">Òåêñò äëÿ îòîáðàæåíèÿ</param> /// <param name="text">Òåêñò äëÿ îòîáðàæåíèÿ</param>
/// <param name="add_history">Ñîõðàíåíèå òåêñòà â îêíî èñòîðèè</param> /// <param name="add_history">Ñîõðàíåíèå òåêñòà â îêíî èñòîðèè</param>
public void UpdateStatus(string text, bool add_history = false) public void UpdateStatus( string text, NotifyLevel level )
{ {
if (!level.HasFlag(NotifyLevel.logAlways) && !level.HasFlag(NotifyLevel.logUpdateStatus)) return;
labelStatus.Text = text; labelStatus.Text = text;
if (add_history)
{
HistoryLog(text);
}
} }
private void HistoryLog(string text) private void HistoryLog( string text, NotifyLevel level = NotifyLevel.logUpdateStatus )
{ {
if (!level.HasFlag(NotifyLevel.logAlways) && !level.HasFlag(NotifyLevel.logHistory)) return;
richTextBoxHistory.Text += DateTime.Now.ToString() + ": " + text + "\n"; richTextBoxHistory.Text += DateTime.Now.ToString() + ": " + text + "\n";
} }
public void Status(string text, bool add_history = false) public void SendDiscordMessage( string message, NotifyLevel level )
{ {
Invoke(updateLogDelegate, text, add_history); if (!level.HasFlag(NotifyLevel.logAlways) && !level.HasFlag(NotifyLevel.logDiscord)) return;
if (Settings.Default.dwhEnabled)
{
dwhHook.Url = Settings.Default.dwhURL;
dwhMessage.Username = "Relaunch process";
dwhMessage.Content = ":arrows_counterclockwise: " + message;
try
{
dwhHook.Send(dwhMessage);
}
catch (Exception ex)
{
HistoryLog($"Discord messaging error: {ex.Message}");
Debug.WriteLine($"Discord messaging error: {ex.Message}");
Settings.Default.dwhEnabled = false;
Settings.Default.Save();
}
}
}
public void Status(string text, NotifyLevel level)
{
updateLogDelegate.Invoke(text, level);
} }
private void CheckProgramState() private void CheckProgramState()
@@ -164,7 +192,7 @@ namespace Process_Auto_Relaunch
groupBoxProcessName.Enabled = !watching; groupBoxProcessName.Enabled = !watching;
groupBoxProgramStart.Enabled = !watching; groupBoxProgramStart.Enabled = !watching;
groupBoxActions.Enabled = !watching; groupBoxActions.Enabled = !watching;
btnShowDiscordSettings.Enabled = !watching; btnShowDiscordSettings.Enabled = !watching; //îòêëþ÷àåì êíîïêó íàñòðîåê äèñêîðäà
Settings.Default.enableWatching = watching; Settings.Default.enableWatching = watching;
@@ -192,7 +220,6 @@ namespace Process_Auto_Relaunch
textBoxProcessName.Text = textBoxProcessName.Text.Remove(textBoxProcessName.Text.Length-4); textBoxProcessName.Text = textBoxProcessName.Text.Remove(textBoxProcessName.Text.Length-4);
Settings.Default.startProgramPath = openFile.FileName; Settings.Default.startProgramPath = openFile.FileName;
Settings.Default.Save(); Settings.Default.Save();
openFile.Dispose(); openFile.Dispose();
} }
@@ -231,7 +258,7 @@ namespace Process_Auto_Relaunch
} }
} }
Status("Ïðîöåññ áûë çàïóùåí.", true); Status("Ïðîöåññ áûë çàïóùåí.", NotifyLevel.logUpdateStatus);
Process.Start(path, args); Process.Start(path, args);
} }
@@ -244,24 +271,23 @@ namespace Process_Auto_Relaunch
{ {
if (ProcessByNameIsRuning(textBoxProcessName.Text)) if (ProcessByNameIsRuning(textBoxProcessName.Text))
{ {
Status($"Ïðîöåññ {textBoxProcessName.Text} óæå çàïóùåí"); Status($"Ïðîöåññ óæå çàïóùåí",NotifyLevel.logUpdateStatus);
if (i < (int)numericUpDown1.Value) SendDiscordMessage($"Ïðîöåññ {textBoxProcessName.Text} çàïóùåí.",true); if (i < (int)numericUpDown1.Value) SendDiscordMessage($"Ïðîöåññ {textBoxProcessName.Text} çàïóùåí.",NotifyLevel.logDiscord);
i = (int)numericUpDown1.Value; i = (int)numericUpDown1.Value;
} }
else else
{ {
if (radioButtonRestartTimer.Checked) if (radioButtonRestartTimer.Checked)
{ {
if (i==(int)numericUpDown1.Value) SendDiscordMessage($"Ïðîöåññ {textBoxProcessName.Text} íå íàéäåí. Çàïóñê ÷åðåç {i}",true); if (i==(int)numericUpDown1.Value) Status($"Ïðîöåññ {textBoxProcessName.Text} íå íàéäåí. Çàïóñê ÷åðåç {i} ñåê",NotifyLevel.logDiscord);
i--; i--;
Status($"Ïðîöåññ {textBoxProcessName.Text} íå íàéäåí. Çàïóñê ÷åðåç {i}"); Status($"Ïðîöåññ {textBoxProcessName.Text} íå íàéäåí. Çàïóñê ÷åðåç {i}", NotifyLevel.logUpdateStatus);
} }
if (i <= 0 || radioButtonRestartNow.Checked) if (i <= 0 || radioButtonRestartNow.Checked)
{ {
i = (int)numericUpDown1.Value; i = (int)numericUpDown1.Value;
Status("Çàïóñêàåì..."); Status($"Çàïóñêàåì {textBoxProcessName.Text}", NotifyLevel.logUpdateStatus|NotifyLevel.logDiscord);
SendDiscordMessage($"Çàïóñêàåì {textBoxProcessName.Text}",true);
ProcessStart(Settings.Default.startProgramPath, textBoxArguments.Text); ProcessStart(Settings.Default.startProgramPath, textBoxArguments.Text);
} }
} }
@@ -279,48 +305,23 @@ namespace Process_Auto_Relaunch
{ {
if (e.Cancelled) if (e.Cancelled)
{ {
Status("Íàáëþäåíèå îòìåíåíî."); Status("Íàáëþäåíèå îòìåíåíî.",NotifyLevel.logUpdateStatus);
} }
else if (e.Error != null) else if (e.Error != null)
{ {
MessageBox.Show("Error: " + e.Error.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Stop); MessageBox.Show("Error: " + e.Error.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Status("Ïðîèçîøëà îøèáêà! Íàáëþäåíèå îñòàíîâëåíî.", true); Status("Ïðîèçîøëà îøèáêà! Íàáëþäåíèå îñòàíîâëåíî.", NotifyLevel.logUpdateStatus|NotifyLevel.logDiscord);
radioButtonDisableWathing.Checked = true; radioButtonDisableWathing.Checked = true;
} }
else else
{ {
Status("Íàáëþäåíèå îñòàíîâëåíî."); Status("Íàáëþäåíèå îñòàíîâëåíî.", NotifyLevel.logUpdateStatus|NotifyLevel.logDiscord);
} }
} }
/// <summary>
/// Îòïðàâêà ñîîáùåíèÿ â Äèñêîðä
/// </summary>
/// <param name="text">Òåêñò äëÿ îòïðàâêè</param>
public void SendDiscordMessage(string message, bool addToHistory = false)
{
if (Settings.Default.dwhEnabled && addToHistory)
{
dwhHook.Url = Settings.Default.dwhURL;
dwhMessage.Username = "Relaunch process";
dwhMessage.Content = ":arrows_counterclockwise: " + message;
try
{
dwhHook.Send(dwhMessage);
}
catch (Exception ex)
{
HistoryLog($"Discord messaging error: {ex.Message}");
Debug.WriteLine($"Discord messaging error: {ex.Message}");
Settings.Default.dwhEnabled = false;
Settings.Default.Save();
}
}
}
private void btnShowDiscordSettings_Click(object sender, EventArgs e) private void btnShowDiscordSettings_Click(object sender, EventArgs e)
{ {
DiscordSettings discordSettings;
discordSettings = new DiscordSettings(); discordSettings = new DiscordSettings();
discordSettings.ShowDialog(this); discordSettings.ShowDialog(this);
discordSettings.Dispose(); discordSettings.Dispose();