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.textDwhURL = new System.Windows.Forms.TextBox();
this.lblDwhURL = new System.Windows.Forms.Label();
this.btnClearUrlField = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnOk
@@ -43,7 +44,7 @@
this.btnOk.TabIndex = 0;
this.btnOk.Text = "Сохранить";
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
this.btnOk.Click += new System.EventHandler(this.BtnOk_Click);
//
// btnCancel
//
@@ -54,13 +55,13 @@
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Отменить";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
this.btnCancel.Click += new System.EventHandler(this.BtnCancel_Click);
//
// chbxDiscordEnabled
//
this.chbxDiscordEnabled.AutoSize = true;
this.chbxDiscordEnabled.Checked = true;
this.chbxDiscordEnabled.CheckState = System.Windows.Forms.CheckState.Checked;
this.chbxDiscordEnabled.Checked = global::RelaunchProcess.Properties.Settings.Default.dwhEnabled;
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.Name = "chbxDiscordEnabled";
this.chbxDiscordEnabled.Size = new System.Drawing.Size(232, 17);
@@ -70,10 +71,12 @@
//
// 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.Name = "textDwhURL";
this.textDwhURL.Size = new System.Drawing.Size(337, 20);
this.textDwhURL.TabIndex = 3;
this.textDwhURL.Text = global::RelaunchProcess.Properties.Settings.Default.dwhURL;
//
// lblDwhURL
//
@@ -84,14 +87,26 @@
this.lblDwhURL.TabIndex = 4;
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
//
this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(361, 128);
this.ClientSize = new System.Drawing.Size(375, 128);
this.ControlBox = false;
this.Controls.Add(this.btnClearUrlField);
this.Controls.Add(this.lblDwhURL);
this.Controls.Add(this.textDwhURL);
this.Controls.Add(this.chbxDiscordEnabled);
@@ -104,7 +119,6 @@
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "Настройки Discord webhook";
this.Load += new System.EventHandler(this.DiscordSettings_Load);
this.ResumeLayout(false);
this.PerformLayout();
@@ -117,5 +131,6 @@
private System.Windows.Forms.CheckBox chbxDiscordEnabled;
private System.Windows.Forms.TextBox textDwhURL;
private System.Windows.Forms.Label lblDwhURL;
private System.Windows.Forms.Button btnClearUrlField;
}
}

View File

@@ -19,23 +19,19 @@ namespace RelaunchProcess
InitializeComponent();
}
private void DiscordSettings_Load(object sender, EventArgs e)
{
chbxDiscordEnabled.Checked=Settings.Default.dwhEnabled;
textDwhURL.Text=Settings.Default.dwhURL;
}
private void btnCancel_Click(object sender, EventArgs e)
private void BtnCancel_Click(object sender, EventArgs e)
{
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;
Settings.Default.dwhURL = textDwhURL.Text;
if (textDwhURL.Text=="")
{
chbxDiscordEnabled.Checked = false;
}
Settings.Default.Save();
DialogResult = DialogResult.OK;
Close();
@@ -43,9 +39,13 @@ namespace RelaunchProcess
else
{
//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
{
private delegate void UpdateLogDelegate(string text, bool add_history = false);
private UpdateLogDelegate updateLogDelegate;
[Flags]
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 DiscordMessage dwhMessage;
private DiscordSettings discordSettings;
public Form1()
{
InitializeComponent();
this.updateLogDelegate = this.UpdateStatus;
this.updateLogDelegate += this.SendDiscordMessage;
this.updateLogDelegate += this.HistoryLog;
myBackgroundWorker.WorkerSupportsCancellation = true;
dwhHook = new DiscordWebhook();
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)
{
myBackgroundWorker.CancelAsync();
UpdateStatus("Îòìåíÿåì...");
UpdateStatus("Îòìåíÿåì...",NotifyLevel.logUpdateStatus);
}
}
@@ -136,24 +145,43 @@ namespace Process_Auto_Relaunch
/// </summary>
/// <param name="text">Òåêñò äëÿ îòîáðàæåíèÿ</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;
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";
}
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()
@@ -164,7 +192,7 @@ namespace Process_Auto_Relaunch
groupBoxProcessName.Enabled = !watching;
groupBoxProgramStart.Enabled = !watching;
groupBoxActions.Enabled = !watching;
btnShowDiscordSettings.Enabled = !watching;
btnShowDiscordSettings.Enabled = !watching; //îòêëþ÷àåì êíîïêó íàñòðîåê äèñêîðäà
Settings.Default.enableWatching = watching;
@@ -192,7 +220,6 @@ namespace Process_Auto_Relaunch
textBoxProcessName.Text = textBoxProcessName.Text.Remove(textBoxProcessName.Text.Length-4);
Settings.Default.startProgramPath = openFile.FileName;
Settings.Default.Save();
openFile.Dispose();
}
@@ -231,7 +258,7 @@ namespace Process_Auto_Relaunch
}
}
Status("Ïðîöåññ áûë çàïóùåí.", true);
Status("Ïðîöåññ áûë çàïóùåí.", NotifyLevel.logUpdateStatus);
Process.Start(path, args);
}
@@ -244,24 +271,23 @@ namespace Process_Auto_Relaunch
{
if (ProcessByNameIsRuning(textBoxProcessName.Text))
{
Status($"Ïðîöåññ {textBoxProcessName.Text} óæå çàïóùåí");
if (i < (int)numericUpDown1.Value) SendDiscordMessage($"Ïðîöåññ {textBoxProcessName.Text} çàïóùåí.",true);
Status($"Ïðîöåññ óæå çàïóùåí",NotifyLevel.logUpdateStatus);
if (i < (int)numericUpDown1.Value) SendDiscordMessage($"Ïðîöåññ {textBoxProcessName.Text} çàïóùåí.",NotifyLevel.logDiscord);
i = (int)numericUpDown1.Value;
}
else
{
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--;
Status($"Ïðîöåññ {textBoxProcessName.Text} íå íàéäåí. Çàïóñê ÷åðåç {i}");
Status($"Ïðîöåññ {textBoxProcessName.Text} íå íàéäåí. Çàïóñê ÷åðåç {i}", NotifyLevel.logUpdateStatus);
}
if (i <= 0 || radioButtonRestartNow.Checked)
{
i = (int)numericUpDown1.Value;
Status("Çàïóñêàåì...");
SendDiscordMessage($"Çàïóñêàåì {textBoxProcessName.Text}",true);
Status($"Çàïóñêàåì {textBoxProcessName.Text}", NotifyLevel.logUpdateStatus|NotifyLevel.logDiscord);
ProcessStart(Settings.Default.startProgramPath, textBoxArguments.Text);
}
}
@@ -279,48 +305,23 @@ namespace Process_Auto_Relaunch
{
if (e.Cancelled)
{
Status("Íàáëþäåíèå îòìåíåíî.");
Status("Íàáëþäåíèå îòìåíåíî.",NotifyLevel.logUpdateStatus);
}
else if (e.Error != null)
{
MessageBox.Show("Error: " + e.Error.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Status("Ïðîèçîøëà îøèáêà! Íàáëþäåíèå îñòàíîâëåíî.", true);
Status("Ïðîèçîøëà îøèáêà! Íàáëþäåíèå îñòàíîâëåíî.", NotifyLevel.logUpdateStatus|NotifyLevel.logDiscord);
radioButtonDisableWathing.Checked = true;
}
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)
{
DiscordSettings discordSettings;
discordSettings = new DiscordSettings();
discordSettings.ShowDialog(this);
discordSettings.Dispose();