From 7f0c887a85169e2b02524c697b529bd9d85b4587 Mon Sep 17 00:00:00 2001 From: arthurits Date: Sun, 3 Apr 2022 12:17:29 +0200 Subject: [PATCH] Code clean-up and auto-properties --- Simon says.sln | 4 +- Simon says/ExtensionMethods.cs | 6 +- Simon says/InitializationRoutines.cs | 16 +- Simon says/JsonSettings.cs | 4 +- Simon says/MainForm.Designer.cs | 16 +- Simon says/MainForm.cs | 43 +- Simon says/Program.cs | 2 +- Simon says/Simon says.csproj | 4 +- Simon says/SimonGame.cs | 150 +++---- Simon says/UserInteractionGUI.cs | 6 +- Simon says/clsApplicationSettings.cs | 68 ---- Simon says/clsSettings.cs | 2 +- Simon says/controls/ColorPickerColumn.cs | 483 +++++++++++------------ Simon says/frmAbout.Designer.cs | 2 +- Simon says/frmAbout.cs | 14 +- Simon says/frmSettings.Designer.cs | 4 +- Simon says/frmSettings.cs | 99 +---- 17 files changed, 378 insertions(+), 545 deletions(-) delete mode 100644 Simon says/clsApplicationSettings.cs diff --git a/Simon says.sln b/Simon says.sln index 10e8f14..70a6fbc 100644 --- a/Simon says.sln +++ b/Simon says.sln @@ -19,8 +19,8 @@ Global {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Debug|x64.Build.0 = Debug|Any CPU {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Release|Any CPU.ActiveCfg = Release|Any CPU {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Release|Any CPU.Build.0 = Release|Any CPU - {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Release|x64.ActiveCfg = Release|x64 - {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Release|x64.Build.0 = Release|x64 + {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Release|x64.ActiveCfg = Release|Any CPU + {5C30595C-50CF-4F2E-8752-AED30F3ADD0C}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Simon says/ExtensionMethods.cs b/Simon says/ExtensionMethods.cs index 4aaec4e..e1072f5 100644 --- a/Simon says/ExtensionMethods.cs +++ b/Simon says/ExtensionMethods.cs @@ -12,13 +12,11 @@ public static class ExtensionMethods /// Key we are looking for /// Default value to return when the TKey is not found in the dictionary /// - public static TValue GetOrDefault(this System.Collections.Generic.Dictionary dictionary, TKey key, TValue defaultValue = default(TValue)) + public static TValue GetOrDefault(this System.Collections.Generic.Dictionary dictionary, TKey key, TValue defaultValue = default) { - if(dictionary.TryGetValue(key, out var value)) - { return value; - } + return defaultValue; /* if (dictionary != null && dictionary.ContainsKey(key)) diff --git a/Simon says/InitializationRoutines.cs b/Simon says/InitializationRoutines.cs index da137be..44a63f2 100644 --- a/Simon says/InitializationRoutines.cs +++ b/Simon says/InitializationRoutines.cs @@ -1,6 +1,6 @@ namespace SimonSays; -partial class frmSimon +partial class FrmSimon { /// /// Initialize the ToolStripPanel component: add the child components to it @@ -27,13 +27,13 @@ private void InitializeToolStrip() toolStripMain.Renderer = new customRenderer(Brushes.SteelBlue, Brushes.LightSkyBlue); - if (File.Exists(_path + @"\images\exit.ico")) this.toolStripMain_Exit.Image = new Icon(_path + @"\images\exit.ico", 48, 48).ToBitmap(); - if (File.Exists(_path + @"\images\start.ico")) this.toolStripMain_Start.Image = new Icon(_path + @"\images\start.ico", 48, 48).ToBitmap(); - if (File.Exists(_path + @"\images\stop.ico")) this.toolStripMain_Stop.Image = new Icon(_path + @"\images\stop.ico", 48, 48).ToBitmap(); - if (File.Exists(_path + @"\images\soundoff.ico")) this.toolStripMain_Sound.Image = new Icon(_path + @"\images\soundoff.ico", 48, 48).ToBitmap(); - if (File.Exists(_path + @"\images\graph.ico")) this.toolStripMain_Stats.Image = new Icon(_path + @"\images\graph.ico", 48, 48).ToBitmap(); - if (File.Exists(_path + @"\images\settings.ico")) this.toolStripMain_Settings.Image = new Icon(_path + @"\images\settings.ico", 48, 48).ToBitmap(); - if (File.Exists(_path + @"\images\about.ico")) this.toolStripMain_About.Image = new Icon(_path + @"\images\about.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\exit.ico")) this.toolStripMain_Exit.Image = new Icon(_settings.AppPath + @"\images\exit.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\start.ico")) this.toolStripMain_Start.Image = new Icon(_settings.AppPath + @"\images\start.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\stop.ico")) this.toolStripMain_Stop.Image = new Icon(_settings.AppPath + @"\images\stop.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\soundoff.ico")) this.toolStripMain_Sound.Image = new Icon(_settings.AppPath + @"\images\soundoff.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\graph.ico")) this.toolStripMain_Stats.Image = new Icon(_settings.AppPath + @"\images\graph.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\settings.ico")) this.toolStripMain_Settings.Image = new Icon(_settings.AppPath + @"\images\settings.ico", 48, 48).ToBitmap(); + if (File.Exists(_settings.AppPath + @"\images\about.ico")) this.toolStripMain_About.Image = new Icon(_settings.AppPath + @"\images\about.ico", 48, 48).ToBitmap(); } diff --git a/Simon says/JsonSettings.cs b/Simon says/JsonSettings.cs index d6428b9..5d144f5 100644 --- a/Simon says/JsonSettings.cs +++ b/Simon says/JsonSettings.cs @@ -7,7 +7,7 @@ namespace SimonSays; -partial class frmSimon +partial class FrmSimon { /// /// Loads all settings from file _sett.FileName into class instance _settings @@ -19,8 +19,6 @@ private void LoadProgramSettingsJSON() { var jsonString = File.ReadAllText(_settings.FileName); _settings = JsonSerializer.Deserialize(jsonString) ?? _settings; - - ApplySettingsJSON(_settings.WindowPosition); } catch (FileNotFoundException) { diff --git a/Simon says/MainForm.Designer.cs b/Simon says/MainForm.Designer.cs index 44e7971..4de3367 100644 --- a/Simon says/MainForm.Designer.cs +++ b/Simon says/MainForm.Designer.cs @@ -3,7 +3,7 @@ namespace SimonSays { - partial class frmSimon + partial class FrmSimon { /// /// Required designer variable. @@ -31,7 +31,7 @@ protected override void Dispose(bool disposing) /// private void InitializeComponent() { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmSimon)); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmSimon)); this.tspTop = new System.Windows.Forms.ToolStripPanel(); this.tspBottom = new System.Windows.Forms.ToolStripPanel(); this.toolStripMain = new System.Windows.Forms.ToolStrip(); @@ -242,12 +242,12 @@ private void InitializeComponent() this.Name = "frmSimon"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Simon Says — Memory Game"; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmSimon_FormClosing); - this.Load += new System.EventHandler(this.frmSimon_Load); - this.Shown += new System.EventHandler(this.frmSimon_Shown); - this.ResizeBegin += new System.EventHandler(this.frmSimon_ResizeBegin); - this.ResizeEnd += new System.EventHandler(this.frmSimon_ResizeEnd); - this.Resize += new System.EventHandler(this.frmSimon_Resize); + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmSimon_FormClosing); + this.Load += new System.EventHandler(this.FrmSimon_Load); + this.Shown += new System.EventHandler(this.FrmSimon_Shown); + this.ResizeBegin += new System.EventHandler(this.FrmSimon_ResizeBegin); + this.ResizeEnd += new System.EventHandler(this.FrmSimon_ResizeEnd); + this.Resize += new System.EventHandler(this.FrmSimon_Resize); this.toolStripMain.ResumeLayout(false); this.toolStripMain.PerformLayout(); this.ResumeLayout(false); diff --git a/Simon says/MainForm.cs b/Simon says/MainForm.cs index be67ef9..7c8bfa9 100644 --- a/Simon says/MainForm.cs +++ b/Simon says/MainForm.cs @@ -5,14 +5,14 @@ namespace SimonSays; -public partial class frmSimon : Form +public partial class FrmSimon : Form { - private SimonGame _Game = new(); + private readonly SimonGame _Game = new(); private ClassSettings _settings = new(); - private readonly System.Resources.ResourceManager StringsRM = new("SimonSays.localization.strings", typeof(frmSimon).Assembly); + private readonly System.Resources.ResourceManager StringsRM = new("SimonSays.localization.strings", typeof(FrmSimon).Assembly); - public frmSimon() + public FrmSimon() { // Set form icon if (System.IO.File.Exists(_settings.AppPath + @"\images\simon.ico")) this.Icon = new Icon(_settings.AppPath + @"\images\simon.ico"); @@ -33,10 +33,9 @@ public frmSimon() // Load and apply the program settings LoadProgramSettingsJSON(); - + ApplySettingsJSON(_settings.WindowPosition); } - #region Events subscription /// /// Consumes the Tick event of the Game class /// @@ -79,11 +78,9 @@ private void OnCorrectSequence(object sender, CorrectEventArgs e) //MessageBox.Show("Well done!\nTotal score: " + e.Score.ToString()); this.simonBoard.ScoreTotal = _Game.ScoreTotal; this.simonBoard.ScoreHighest = _Game.ScoreHighest; - - if ((this._Game.GameMode & SimonGame.PlayMode.SimonBounce)==SimonGame.PlayMode.SimonBounce) - { + + if ((this._Game.GameMode & SimonGame.PlayMode.SimonBounce) == SimonGame.PlayMode.SimonBounce) this.simonBoard.RandomizeButtons(); - } /* foreach (ColorButton.SimonButton button in simonBoard.Controls.OfType()) @@ -95,20 +92,19 @@ private void OnCorrectSequence(object sender, CorrectEventArgs e) private void OnGameOver(object sender, OverEventArgs e) { - MessageBox.Show("Your total score is: " + e.Score.ToString(),"Game over"); + using (new CenterWinDialog(this)) + { + MessageBox.Show(this, "Your total score is: " + e.Score.ToString(), "Game over"); + } this.simonBoard.ScoreTotal = 0; } - #endregion Events subscription - - #region Form events - - private void frmSimon_Load(object sender, EventArgs e) + private void FrmSimon_Load(object sender, EventArgs e) { Win32.Win32API.AnimateWindow(this.Handle, 500, Win32.Win32API.AnimateWindowFlags.AW_BLEND); } - private void frmSimon_FormClosing(object sender, FormClosingEventArgs e) + private void FrmSimon_FormClosing(object sender, FormClosingEventArgs e) { using (new CenterWinDialog(this)) { @@ -130,14 +126,14 @@ private void frmSimon_FormClosing(object sender, FormClosingEventArgs e) SaveProgramSettingsJSON(); } - private void frmSimon_Shown(object sender, EventArgs e) + private void FrmSimon_Shown(object sender, EventArgs e) { // Send Close event to the splash screen using var closeSplashEvent = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, "CloseSplashScreenEvent"); closeSplashEvent.Set(); } - private void frmSimon_Resize(object sender, EventArgs e) + private void FrmSimon_Resize(object sender, EventArgs e) { // Force the client area to be painted again //Invalidate(); @@ -147,16 +143,13 @@ private void frmSimon_Resize(object sender, EventArgs e) //this.btnGreen.Width = 400; } - private void frmSimon_ResizeBegin(object sender, EventArgs e) + private void FrmSimon_ResizeBegin(object sender, EventArgs e) { this.SuspendLayout(); } - private void frmSimon_ResizeEnd(object sender, EventArgs e) + private void FrmSimon_ResizeEnd(object sender, EventArgs e) { this.ResumeLayout(); } - - #endregion Form events - -} +} \ No newline at end of file diff --git a/Simon says/Program.cs b/Simon says/Program.cs index 855b700..c8e08a6 100644 --- a/Simon says/Program.cs +++ b/Simon says/Program.cs @@ -16,7 +16,7 @@ static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new frmSimon()); + Application.Run(new FrmSimon()); } } } diff --git a/Simon says/Simon says.csproj b/Simon says/Simon says.csproj index 8233b6e..fa886b0 100644 --- a/Simon says/Simon says.csproj +++ b/Simon says/Simon says.csproj @@ -35,7 +35,9 @@ PreserveNewest - + + PreserveNewest + PreserveNewest diff --git a/Simon says/SimonGame.cs b/Simon says/SimonGame.cs index 6a68549..f007968 100644 --- a/Simon says/SimonGame.cs +++ b/Simon says/SimonGame.cs @@ -5,17 +5,10 @@ class SimonGame private const int MAX_SEQUENCE = 100000; #region Variable definitions - private PlayMode _playMode; // The current play mode private Int32 _nNumButts = 0; private Int32[] _sequence; - private Int32 _nScore; - private Int32 _nCounter; - private Int32 _nHighest; - private bool _nPlaySimon; - private bool _nFlashLight; + private Int32 _nCounter = 0; private readonly int[,] _arrayTimeSeq; - private Int32 _msBetween; - private Int32 _msFlashlight; private readonly System.Timers.Timer _timer; [Flags] @@ -37,10 +30,6 @@ public enum PlayMode public event EventHandler CorrectSequence; public event EventHandler GameOver; - #endregion Variable definitions - - #region Public interface - /// /// Number of buttons to generate the random sequence /// @@ -48,92 +37,80 @@ public Int32 NumberOfButtons { get => _nNumButts; set { _nNumButts = value < 0 ? 0 : value;} - } - - public Int32 ScoreTotal - { - //set { _nScore = value; } - get => _nScore; - } - public Int32 ScoreHighest - { - //set { _nCounter = value; } - get => _nHighest; - } - public Int32 DurationFlash - { - get => _msFlashlight; - } - public Int32 DurationBetween - { - get => _msBetween; - set => _msBetween = value; } + /// + /// The partial score while the user is still reproducing the sequence + /// + public Int32 ScoreTotal { get; private set; } = 0; + + /// + /// The highest score during the whole time the user is playing the game + /// + public Int32 ScoreHighest { get; private set; } = 0; + + /// + /// Milliseconds for the button flashing and sound + /// + public Int32 DurationFlash { get; private set; } = 420; + + /// + /// Milliseconds between each button flashing + /// + public Int32 DurationBetween { get; set; } = 50; + /// /// True if Simon is playing a sequence, flase otherwise /// - public bool Play - { - get => _nPlaySimon; - set => _nPlaySimon = value; - } - public bool Flash - { - get => _nFlashLight; - set => _nFlashLight = value; - } + public bool Play { get; set; } = true; + + /// + /// True if the button is flashing + /// + public bool Flash { get; set; } = true; /// /// The actual play-mode selected by the user (time and sequence mode). /// - public PlayMode GameMode { get => _playMode; set => _playMode = value; } + public PlayMode GameMode { get; set; } - #endregion Public interface + #endregion Variable definitions public SimonGame() { _timer = new(); _timer.Elapsed += TimerTick; - _nPlaySimon = true; - _nFlashLight = true; - _nScore = 0; - _nCounter = 0; - _nHighest = 0; _arrayTimeSeq = new int[3, 2] { { 5, 420 }, { 13, 320 }, { 31, 220 } }; - _msBetween = 50; } public void Start() { GetNewSequence(); - _nScore = 0; + ScoreTotal = 0; _nCounter = 0; - _nPlaySimon = true; // Sets Simon to start reproducing a sequence - _nFlashLight = true; - _msFlashlight = FindTime(); - _timer.Interval = _msFlashlight; + Play = true; // Sets Simon to start reproducing a sequence + Flash = true; + DurationFlash = FindTime(); + _timer.Interval = DurationFlash; _timer.Enabled = true; } public void Restart() { _nCounter = 0; - _nPlaySimon = true; // Sets Simon to start reproducing a sequence + Play = true; // Sets Simon to start reproducing a sequence // Wait 0.5 seconds before the next sequence is played by Simon Task.Run(async () => { - await Task.Delay(_msFlashlight); - _timer.Interval = _msFlashlight; + await Task.Delay(DurationFlash); + _timer.Interval = DurationFlash; _timer.Enabled = true; }); - if ((_playMode & PlayMode.SimonRandom) == PlayMode.SimonRandom) - { - GetNewSequence(_nScore + 1); - } + if ((GameMode & PlayMode.SimonRandom) == PlayMode.SimonRandom) + GetNewSequence(ScoreTotal + 1); //_timer.Interval = 200; //_timer.Enabled = true; @@ -143,7 +120,7 @@ public void Restart() public void Stop() { _timer.Enabled = false; // Stops the internal timer - _nPlaySimon = false; // Stops Simon reproducing a sequence + Play = false; // Stops Simon reproducing a sequence _nCounter = 0; // Resets the counter to 0 } @@ -153,28 +130,28 @@ public void Stop() /// The internal value of the button pressed by the user public void OnPress(Int32 buttonValue) { - if (_nPlaySimon == true) return; // If Simon is playing then exit the function + if (Play == true) return; // If Simon is playing then exit the function Int32 length = _sequence.Length; Int32 sequence = _sequence[_nCounter]; - if ((_playMode & PlayMode.SimonRewind) == PlayMode.SimonRewind) + if ((GameMode & PlayMode.SimonRewind) == PlayMode.SimonRewind) { - sequence = _sequence[_nScore - _nCounter]; + sequence = _sequence[ScoreTotal - _nCounter]; } if (buttonValue == sequence) { - if (_nCounter < _nScore) _nCounter++; + if (_nCounter < ScoreTotal) _nCounter++; else { // Update the total score and find the time for the next sequence - _nScore++; - _nHighest = (_nScore > _nHighest) ? _nScore : _nHighest; - _msFlashlight = FindTime(); + ScoreTotal++; + ScoreHighest = (ScoreTotal > ScoreHighest) ? ScoreTotal : ScoreHighest; + DurationFlash = FindTime(); // Fire the event - if (CorrectSequence != null) OnCorrectSequence(new CorrectEventArgs(_nScore)); + if (CorrectSequence != null) OnCorrectSequence(new CorrectEventArgs(ScoreTotal)); // _nPlaySimon = true; // Quit control from player and pass it to Simon Restart(); // Pass the control to Simon and restart the sequence reproduction } @@ -182,8 +159,8 @@ public void OnPress(Int32 buttonValue) else // If the button pressed is incorrect { // Fire the event to finish the game - if (GameOver != null) OnGameOver(new OverEventArgs(_nScore)); - _nPlaySimon = true; // Quit control from player and pass it to Simon + if (GameOver != null) OnGameOver(new OverEventArgs(ScoreTotal)); + Play = true; // Quit control from player and pass it to Simon } } @@ -196,18 +173,18 @@ private void TimerTick(object sender, EventArgs e) { //Console.WriteLine("Time: {0}, ms: {1}, pause: {2}, interval: {3}", DateTime.Now.ToString("hh:mm:sss"), DateTime.Now.Millisecond.ToString(), Pause.ToString(), _timer.Interval.ToString()); // Fire the event - if (Tick != null) OnTick(new TickEventArgs(_nFlashLight, _sequence[_nCounter])); + if (Tick != null) OnTick(new TickEventArgs(Flash, _sequence[_nCounter])); // The counter only increases after the light has been switched off. So does the finishing - if (_nFlashLight == false) + if (Flash == false) { _nCounter++; - if (_nCounter > _nScore) Stop(); + if (_nCounter > ScoreTotal) Stop(); } // Change the status of the flash light and the corresponding timer interval - _nFlashLight = !_nFlashLight; - _timer.Interval = (_nFlashLight == false) ? _msFlashlight : _msBetween; // 420 miliseconds flashlight and 50 miliseconds between flashes/beeps + Flash = !Flash; + _timer.Interval = (Flash == false) ? DurationFlash : DurationBetween; // 420 miliseconds flashlight and 50 miliseconds between flashes/beeps } /// @@ -217,7 +194,7 @@ private void GetNewSequence(int optionalLength = MAX_SEQUENCE) { _sequence = new int[optionalLength]; - Random rnd = new Random(); + Random rnd = new(); for (Int32 i = 0; i < optionalLength; i++) { _sequence[i] = rnd.Next(0, _nNumButts); } // Random numbers between 0 and 3 } @@ -228,7 +205,7 @@ private void GetNewSequence(int optionalLength = MAX_SEQUENCE) /// The time that corresponds to the actual score private int FindTime() { - if ((_playMode & PlayMode.TimeIncremental) != PlayMode.TimeIncremental) + if ((GameMode & PlayMode.TimeIncremental) != PlayMode.TimeIncremental) { return _arrayTimeSeq[0, 1]; } @@ -236,7 +213,7 @@ private int FindTime() uint i; for (i = 0; i < _arrayTimeSeq.GetLength(0); i++) { - if (_nScore < _arrayTimeSeq[i, 0]) break; + if (ScoreTotal < _arrayTimeSeq[i, 0]) break; } return _arrayTimeSeq[i, 1]; } @@ -244,19 +221,19 @@ private int FindTime() // Events protected virtual void OnTick(TickEventArgs e) { - if (Tick != null) Tick(this, e); + Tick?.Invoke(this, e); } protected virtual void OnWrongSequence(WrongEventArgs e) { - if (WrongSequence != null) WrongSequence(this, e); + WrongSequence?.Invoke(this, e); } protected virtual void OnCorrectSequence(CorrectEventArgs e) { - if (CorrectSequence != null) CorrectSequence(this, e); + CorrectSequence?.Invoke(this, e); } protected virtual void OnGameOver(OverEventArgs e) { - if (GameOver != null) GameOver(this, e); + GameOver?.Invoke(this, e); } } @@ -289,5 +266,4 @@ public class OverEventArgs : EventArgs { public readonly Int32 Score; public OverEventArgs(Int32 value) { Score = value; } -} - +} \ No newline at end of file diff --git a/Simon says/UserInteractionGUI.cs b/Simon says/UserInteractionGUI.cs index 9b8fea6..92ed73b 100644 --- a/Simon says/UserInteractionGUI.cs +++ b/Simon says/UserInteractionGUI.cs @@ -1,6 +1,6 @@ namespace SimonSays; -partial class frmSimon +partial class FrmSimon { private void OnButtonClick(object sender, CustomBoard.ButtonClickEventArgs e) { @@ -28,7 +28,7 @@ private void Stop_Click(object sender, EventArgs e) private void Settings_Click(object sender, EventArgs e) { - frmSettings frmSettings = new(_settings); + FrmSettings frmSettings = new(_settings); frmSettings.ShowDialog(this); if (frmSettings.DialogResult == DialogResult.OK) { @@ -39,7 +39,7 @@ private void Settings_Click(object sender, EventArgs e) private void About_Click(object sender, EventArgs e) { - frmAbout form = new(); + FrmAbout form = new(); form.ShowDialog(this); } } diff --git a/Simon says/clsApplicationSettings.cs b/Simon says/clsApplicationSettings.cs deleted file mode 100644 index 5f67e71..0000000 --- a/Simon says/clsApplicationSettings.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Drawing; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - - -namespace System -{ - // https://dzone.com/articles/how-to-serializedeserialize-a-dictionary-object-in-1 - [XmlRoot("Program_SimonSays")] - public class ProgramSettings : System.Collections.Generic.Dictionary, IXmlSerializable - { - public XmlSchema GetSchema() { return null; } - - public void ReadXml(XmlReader reader) - { - if (reader.IsEmptyElement) { return; } - - reader.Read(); - - while (reader.NodeType != XmlNodeType.EndElement) - { - object key = reader.GetAttribute("Property"); - object value = reader.GetAttribute("Value"); - this.Add((TKey)key, (TValue)value); - reader.Read(); - } - } - - public void WriteXml(XmlWriter writer) - { - foreach (var pair in this) - { - writer.WriteStartElement("Settings"); - writer.WriteAttributeString("Property", pair.Key.ToString()); - writer.WriteAttributeString("Value", pair.Value.ToString()); - writer.WriteEndElement(); - } - } - } - - // https://stackoverflow.com/questions/453161/how-can-i-save-application-settings-in-a-windows-forms-application - // https://github.com/Nucs/JsonSettings - public class AppSettings where T : new() - { - private const string DEFAULT_FILENAME = "settings.json"; - - public void Save(string fileName = DEFAULT_FILENAME) - { - //System.IO.File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(this)); - } - - public static void Save(T pSettings, string fileName = DEFAULT_FILENAME) - { - //System.IO.File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(pSettings)); - } - /* - public static T Load(string fileName = DEFAULT_FILENAME) - { - T t = new T(); - if (System.IO.File.Exists(fileName)) - t = (new JavaScriptSerializer()).Deserialize(System.IO.File.ReadAllText(fileName)); - return t; - } - */ - } -} diff --git a/Simon says/clsSettings.cs b/Simon says/clsSettings.cs index 4f3fa8b..9bb6b46 100644 --- a/Simon says/clsSettings.cs +++ b/Simon says/clsSettings.cs @@ -14,7 +14,7 @@ public class ClassSettings /// Remember window position on start up /// [JsonPropertyName("Window position")] - public bool WindowPosition { get; set; } = true; // Remember window position + public bool WindowPosition { get; set; } = false; /// /// Window top-left x coordinate diff --git a/Simon says/controls/ColorPickerColumn.cs b/Simon says/controls/ColorPickerColumn.cs index 3ad7b2d..83db581 100644 --- a/Simon says/controls/ColorPickerColumn.cs +++ b/Simon says/controls/ColorPickerColumn.cs @@ -1,304 +1,297 @@ -using System; -using System.Collections.Generic; -using System.Text; -//using LaMarvin.Windows.Forms; -using System.Windows.Forms; -using System.Drawing; -using System.Threading; +//using LaMarvin.Windows.Forms; -namespace System.Windows.Forms +namespace System.Windows.Forms; + +// https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells +// https://social.msdn.microsoft.com/Forums/windows/en-US/f501e688-e8ef-42e5-aaa4-71ec2b6a1176/datagridview-color-picker?forum=winformsdatacontrols +public class ColorPickerColumn : DataGridViewColumn { - // https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells - // https://social.msdn.microsoft.com/Forums/windows/en-US/f501e688-e8ef-42e5-aaa4-71ec2b6a1176/datagridview-color-picker?forum=winformsdatacontrols - public class ColorPickerColumn : DataGridViewColumn + public ColorPickerColumn():base(new ColorPickerCell()) + { + + } + + public override DataGridViewCell CellTemplate { - public ColorPickerColumn():base(new ColorPickerCell()) + get { - + return base.CellTemplate; } - - public override DataGridViewCell CellTemplate + set { - get + // Ensure that the cell used for the template is a CalendarCell. + if (value != null && + !value.GetType().IsAssignableFrom(typeof(ColorPickerCell))) { - return base.CellTemplate; - } - set - { - // Ensure that the cell used for the template is a CalendarCell. - if (value != null && - !value.GetType().IsAssignableFrom(typeof(ColorPickerCell))) - { - throw new InvalidCastException("Must be a ColorPicker"); - } - base.CellTemplate = value; + throw new InvalidCastException("Must be a ColorPicker"); } + base.CellTemplate = value; } } +} - public class ColorPickerCell : DataGridViewTextBoxCell +public class ColorPickerCell : DataGridViewTextBoxCell +{ + ColorPickerControl _ColorPicker; + public ColorPickerCell() + : base() { - ColorPickerControl _ColorPicker; - public ColorPickerCell() - : base() + + } + + public override void InitializeEditingControl(int rowIndex, object + initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) + { + // Set the value of the editing control to the current cell value. + base.InitializeEditingControl(rowIndex, initialFormattedValue, + dataGridViewCellStyle); + ColorPickerControl ctl = DataGridView.EditingControl as ColorPickerControl; + _ColorPicker = ctl; + + + if (this.Value !=null && (this.Value.GetType() == typeof(Color))) { - + ctl.BackColor = (Color)this.Value; + ctl._color = (Color)this.Value; } - - public override void InitializeEditingControl(int rowIndex, object - initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) + else if (this.Value != null && this.Value.GetType() == typeof(string)) { - // Set the value of the editing control to the current cell value. - base.InitializeEditingControl(rowIndex, initialFormattedValue, - dataGridViewCellStyle); - ColorPickerControl ctl = DataGridView.EditingControl as ColorPickerControl; - _ColorPicker = ctl; + ctl.BackColor = Color.FromArgb(int.Parse(this.Value.ToString(), Globalization.NumberStyles.HexNumber)); + ctl._color = Color.FromArgb(int.Parse(this.Value.ToString(), Globalization.NumberStyles.HexNumber)); + } - - if (this.Value !=null && (this.Value.GetType() == typeof(Color))) - { - ctl.BackColor = (Color)this.Value; - ctl._color = (Color)this.Value; - } - else if (this.Value != null && this.Value.GetType() == typeof(string)) - { - ctl.BackColor = Color.FromArgb(int.Parse(this.Value.ToString(), Globalization.NumberStyles.HexNumber)); - ctl._color = Color.FromArgb(int.Parse(this.Value.ToString(), Globalization.NumberStyles.HexNumber)); - } + } - } + public override Type EditType + { + //Return the type of the editing contol that CalendarCell uses. + get => typeof(ColorPickerControl); + } - public override Type EditType - { - //Return the type of the editing contol that CalendarCell uses. - get => typeof(ColorPickerControl); - } + public override Type ValueType + { + // Return the type of the value that CalendarCell contains. + get => typeof(Color); + } - public override Type ValueType - { - // Return the type of the value that CalendarCell contains. - get => typeof(Color); - } + public override object DefaultNewRowValue + { + // Use the current date and time as the default value. + get => Color.White; + } + + protected override void Paint(Graphics graphics, + Rectangle clipBounds, Rectangle cellBounds, int rowIndex, + DataGridViewElementStates elementState, object value, + object formattedValue, string errorText, + DataGridViewCellStyle cellStyle, + DataGridViewAdvancedBorderStyle advancedBorderStyle, + DataGridViewPaintParts paintParts) + { + formattedValue = null; - public override object DefaultNewRowValue - { - // Use the current date and time as the default value. - get => Color.White; - } - - protected override void Paint(Graphics graphics, - Rectangle clipBounds, Rectangle cellBounds, int rowIndex, - DataGridViewElementStates elementState, object value, - object formattedValue, string errorText, - DataGridViewCellStyle cellStyle, - DataGridViewAdvancedBorderStyle advancedBorderStyle, - DataGridViewPaintParts paintParts) - { - formattedValue = null; - - base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, - errorText, cellStyle, advancedBorderStyle, paintParts); + base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, + errorText, cellStyle, advancedBorderStyle, paintParts); - - Rectangle ColorBoxRect = new Rectangle(); - RectangleF TextBoxRect = new RectangleF(); - GetDisplayLayout(cellBounds, ref ColorBoxRect, ref TextBoxRect); + + Rectangle ColorBoxRect = new Rectangle(); + RectangleF TextBoxRect = new RectangleF(); + GetDisplayLayout(cellBounds, ref ColorBoxRect, ref TextBoxRect); - if (value.GetType() == typeof(string)) - value = Color.FromArgb(int.Parse(value.ToString(), Globalization.NumberStyles.HexNumber)); + if (value.GetType() == typeof(string)) + value = Color.FromArgb(int.Parse(value.ToString(), Globalization.NumberStyles.HexNumber)); - //// Draw the cell background, if specified. - if ((paintParts & DataGridViewPaintParts.Background) == - DataGridViewPaintParts.Background) + //// Draw the cell background, if specified. + if ((paintParts & DataGridViewPaintParts.Background) == + DataGridViewPaintParts.Background) + { + SolidBrush cellBackground; + if (value != null && value.GetType() == typeof(Color)) { - SolidBrush cellBackground; - if (value != null && value.GetType() == typeof(Color)) - { - cellBackground = new SolidBrush((Color)value); - } - else - { - cellBackground = new SolidBrush(cellStyle.BackColor); - } - graphics.FillRectangle(cellBackground, ColorBoxRect); - graphics.DrawRectangle(Pens.Black, ColorBoxRect); - Color lclcolor=(Color)value; - graphics.DrawString(lclcolor.Name.ToString(), cellStyle.Font, System.Drawing.Brushes.Black, TextBoxRect); - - cellBackground.Dispose(); + cellBackground = new SolidBrush((Color)value); } - - } - - public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.ComponentModel.TypeConverter valueTypeConverter) - { - int result; - //string number = "0x" + formattedValue.ToString(); - if (int.TryParse(formattedValue.ToString(), System.Globalization.NumberStyles.HexNumber, null, out result)) - //Hex number - //return base.ParseFormattedValue("0x" + formattedValue.ToString(), cellStyle, formattedValueTypeConverter, valueTypeConverter); - return base.ParseFormattedValue(formattedValue.ToString().ToUpper(), cellStyle, formattedValueTypeConverter, valueTypeConverter); else - return base.ParseFormattedValue(formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); + { + cellBackground = new SolidBrush(cellStyle.BackColor); + } + graphics.FillRectangle(cellBackground, ColorBoxRect); + graphics.DrawRectangle(Pens.Black, ColorBoxRect); + Color lclcolor=(Color)value; + graphics.DrawString(lclcolor.Name.ToString(), cellStyle.Font, System.Drawing.Brushes.Black, TextBoxRect); + + cellBackground.Dispose(); } + + } - protected virtual void GetDisplayLayout(Rectangle CellRect,ref Rectangle colorBoxRect, ref RectangleF textBoxRect) - { - const int DistanceFromEdge = 2; - - colorBoxRect.X = CellRect.X+DistanceFromEdge ; - colorBoxRect.Y = CellRect.Y +1 ; - colorBoxRect.Size = new Size((int)(1.5 * 17), CellRect.Height - (2*DistanceFromEdge)); - - // The text occupies the middle portion. - textBoxRect = RectangleF.FromLTRB(colorBoxRect.X + colorBoxRect.Width + 5, colorBoxRect.Y+2, CellRect.X+CellRect.Width-DistanceFromEdge , colorBoxRect.Y + colorBoxRect.Height ); - } + public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.ComponentModel.TypeConverter valueTypeConverter) + { + int result; + //string number = "0x" + formattedValue.ToString(); + if (int.TryParse(formattedValue.ToString(), System.Globalization.NumberStyles.HexNumber, null, out result)) + //Hex number + //return base.ParseFormattedValue("0x" + formattedValue.ToString(), cellStyle, formattedValueTypeConverter, valueTypeConverter); + return base.ParseFormattedValue(formattedValue.ToString().ToUpper(), cellStyle, formattedValueTypeConverter, valueTypeConverter); + else + return base.ParseFormattedValue(formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); } - class ColorPickerControl : Button , IDataGridViewEditingControl + protected virtual void GetDisplayLayout(Rectangle CellRect,ref Rectangle colorBoxRect, ref RectangleF textBoxRect) { - DataGridView dataGridView; - private bool valueChanged = false; - int rowIndex; - public Color _color; + const int DistanceFromEdge = 2; + + colorBoxRect.X = CellRect.X+DistanceFromEdge ; + colorBoxRect.Y = CellRect.Y +1 ; + colorBoxRect.Size = new Size((int)(1.5 * 17), CellRect.Height - (2*DistanceFromEdge)); - public ColorPickerControl() - { - this.Click += new EventHandler(ColorEditingControl_Click); - } + // The text occupies the middle portion. + textBoxRect = RectangleF.FromLTRB(colorBoxRect.X + colorBoxRect.Width + 5, colorBoxRect.Y+2, CellRect.X+CellRect.Width-DistanceFromEdge , colorBoxRect.Y + colorBoxRect.Height ); + } +} - public void ColorEditingControl_Click(object sender, EventArgs e) - { - ColorDialog ColorDlg = new ColorDialog(); - ColorDlg.AllowFullOpen = true; - ColorDlg.AnyColor = true; - ColorDlg.FullOpen = true; - ColorDlg.SolidColorOnly = false; - ColorDlg.ShowHelp = true; - ColorDlg.Color = this._color; +class ColorPickerControl : Button , IDataGridViewEditingControl +{ + DataGridView dataGridView; + private bool valueChanged = false; + int rowIndex; + public Color _color; - if (ColorDlg.ShowDialog() == DialogResult.OK) - { - if (this._color != ColorDlg.Color) - { - this._color = ColorDlg.Color; - valueChanged = true; - this.EditingControlDataGridView.NotifyCurrentCellDirty(true); - } - } + public ColorPickerControl() + { + this.Click += new EventHandler(ColorEditingControl_Click); + } - this.EditingControlDataGridView.NotifyCurrentCellDirty(true); - } + public void ColorEditingControl_Click(object sender, EventArgs e) + { + ColorDialog ColorDlg = new ColorDialog(); + ColorDlg.AllowFullOpen = true; + ColorDlg.AnyColor = true; + ColorDlg.FullOpen = true; + ColorDlg.SolidColorOnly = false; + ColorDlg.ShowHelp = true; + ColorDlg.Color = this._color; - // Implements the IDataGridViewEditingControl.EditingControlFormattedValue - // property. - public object EditingControlFormattedValue + if (ColorDlg.ShowDialog() == DialogResult.OK) { - get => this._color.ToArgb().ToString("X"); - set + if (this._color != ColorDlg.Color) { - if (value != null) - this._color = Color.FromArgb(int.Parse(value.ToString(), System.Globalization.NumberStyles.HexNumber)); + this._color = ColorDlg.Color; + valueChanged = true; + this.EditingControlDataGridView.NotifyCurrentCellDirty(true); } } - // Implements the - // IDataGridViewEditingControl.GetEditingControlFormattedValue method. - public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) - { - return EditingControlFormattedValue; - } + this.EditingControlDataGridView.NotifyCurrentCellDirty(true); + } - // Implements the - // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. - public void ApplyCellStyleToEditingControl( - DataGridViewCellStyle dataGridViewCellStyle) + // Implements the IDataGridViewEditingControl.EditingControlFormattedValue + // property. + public object EditingControlFormattedValue + { + get => this._color.ToArgb().ToString("X"); + set { - this.Font = dataGridViewCellStyle.Font; + if (value != null) + this._color = Color.FromArgb(int.Parse(value.ToString(), System.Globalization.NumberStyles.HexNumber)); } + } - // Implements the IDataGridViewEditingControl.EditingControlRowIndex - // property. - public int EditingControlRowIndex - { - get => rowIndex; - set => rowIndex = value; - } + // Implements the + // IDataGridViewEditingControl.GetEditingControlFormattedValue method. + public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) + { + return EditingControlFormattedValue; + } - // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey - // method. - public bool EditingControlWantsInputKey( - Keys key, bool dataGridViewWantsInputKey) - { - // Let the DateTimePicker handle the keys listed. - switch (key & Keys.KeyCode) - { - case Keys.Left: - case Keys.Up: - case Keys.Down: - case Keys.Right: - case Keys.Home: - case Keys.End: - case Keys.PageDown: - case Keys.PageUp: - return true; - default: - return !dataGridViewWantsInputKey; - } - } + // Implements the + // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. + public void ApplyCellStyleToEditingControl( + DataGridViewCellStyle dataGridViewCellStyle) + { + this.Font = dataGridViewCellStyle.Font; + } - // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit - // method. - public void PrepareEditingControlForEdit(bool selectAll) - { - // No preparation needs to be done. - } + // Implements the IDataGridViewEditingControl.EditingControlRowIndex + // property. + public int EditingControlRowIndex + { + get => rowIndex; + set => rowIndex = value; + } - // Implements the IDataGridViewEditingControl - // .RepositionEditingControlOnValueChange property. - public bool RepositionEditingControlOnValueChange + // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey + // method. + public bool EditingControlWantsInputKey( + Keys key, bool dataGridViewWantsInputKey) + { + // Let the DateTimePicker handle the keys listed. + switch (key & Keys.KeyCode) { - get => false; + case Keys.Left: + case Keys.Up: + case Keys.Down: + case Keys.Right: + case Keys.Home: + case Keys.End: + case Keys.PageDown: + case Keys.PageUp: + return true; + default: + return !dataGridViewWantsInputKey; } + } - // Implements the IDataGridViewEditingControl - // .EditingControlDataGridView property. - public DataGridView EditingControlDataGridView - { - get => dataGridView; - set => dataGridView = value; - } + // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit + // method. + public void PrepareEditingControlForEdit(bool selectAll) + { + // No preparation needs to be done. + } - // Implements the IDataGridViewEditingControl - // .EditingControlValueChanged property. - public bool EditingControlValueChanged - { - get=> valueChanged; - set=> valueChanged = value; - } + // Implements the IDataGridViewEditingControl + // .RepositionEditingControlOnValueChange property. + public bool RepositionEditingControlOnValueChange + { + get => false; + } - // Implements the IDataGridViewEditingControl - public Cursor EditingPanelCursor - { - get => base.Cursor; - } + // Implements the IDataGridViewEditingControl + // .EditingControlDataGridView property. + public DataGridView EditingControlDataGridView + { + get => dataGridView; + set => dataGridView = value; + } - protected virtual void NotifyDataGridViewOfValueChange() - { - this.valueChanged = true; - if (this.dataGridView != null) - { - this.dataGridView.NotifyCurrentCellDirty(true); - } - } + // Implements the IDataGridViewEditingControl + // .EditingControlValueChanged property. + public bool EditingControlValueChanged + { + get=> valueChanged; + set=> valueChanged = value; + } + + // Implements the IDataGridViewEditingControl + public Cursor EditingPanelCursor + { + get => base.Cursor; + } - protected override void OnLeave(EventArgs eventargs) + protected virtual void NotifyDataGridViewOfValueChange() + { + this.valueChanged = true; + if (this.dataGridView != null) { - // Notify the DataGridView that the contents of the cell - // have changed. - base.OnLeave(eventargs); - NotifyDataGridViewOfValueChange(); + this.dataGridView.NotifyCurrentCellDirty(true); } - } + + protected override void OnLeave(EventArgs eventargs) + { + // Notify the DataGridView that the contents of the cell + // have changed. + base.OnLeave(eventargs); + NotifyDataGridViewOfValueChange(); + } + } diff --git a/Simon says/frmAbout.Designer.cs b/Simon says/frmAbout.Designer.cs index fc25951..ed4e28c 100644 --- a/Simon says/frmAbout.Designer.cs +++ b/Simon says/frmAbout.Designer.cs @@ -1,6 +1,6 @@ namespace SimonSays { - partial class frmAbout + partial class FrmAbout { /// /// Variable del diseñador necesaria. diff --git a/Simon says/frmAbout.cs b/Simon says/frmAbout.cs index 3583ab0..f82bdac 100644 --- a/Simon says/frmAbout.cs +++ b/Simon says/frmAbout.cs @@ -2,7 +2,7 @@ namespace SimonSays; -partial class frmAbout : Form +partial class FrmAbout : Form { #region Descriptores de acceso de atributos de ensamblado @@ -20,7 +20,7 @@ public string AssemblyTitle return titleAttribute.Title; } } - return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); + return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location); } } @@ -86,10 +86,10 @@ public string AssemblyCompany #endregion - public frmAbout() + public FrmAbout() { InitializeComponent(); - // this.Text = String.Format("About {0}", AssemblyTitle); + this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; @@ -97,14 +97,12 @@ public frmAbout() this.textBoxDescription.Text = AssemblyDescription; // Set form icons and images - var path = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); + var path = System.IO.Path.GetDirectoryName(Environment.ProcessPath); //if (System.IO.File.Exists(path + @"\images\about.ico")) this.Icon = new Icon(path + @"\images\about.ico"); - - //Bitmap image = new Icon(path + @"\images\logo.ico", 256, 256).ToBitmap(); if (System.IO.File.Exists(path + @"\images\logo@256.png")) this.logoPictureBox.Image = new Bitmap(path + @"\images\logo@256.png"); } - [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] + // [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] protected override void WndProc(ref Message m) { const int WM_PARENTNOTIFY = 0x210; diff --git a/Simon says/frmSettings.Designer.cs b/Simon says/frmSettings.Designer.cs index 0d6991d..367639d 100644 --- a/Simon says/frmSettings.Designer.cs +++ b/Simon says/frmSettings.Designer.cs @@ -2,7 +2,7 @@ namespace SimonSays { - partial class frmSettings + partial class FrmSettings { /// /// Required designer variable. @@ -570,7 +570,7 @@ private void InitializeComponent() this.btnFontFamily.TabIndex = 25; this.btnFontFamily.Text = "Select font..."; this.btnFontFamily.UseVisualStyleBackColor = true; - this.btnFontFamily.Click += new System.EventHandler(this.btnFontFamily_Click); + this.btnFontFamily.Click += new System.EventHandler(this.FontFamily_Click); // // pctIn // diff --git a/Simon says/frmSettings.cs b/Simon says/frmSettings.cs index 6f465f5..cc1bafe 100644 --- a/Simon says/frmSettings.cs +++ b/Simon says/frmSettings.cs @@ -2,16 +2,16 @@ namespace SimonSays; -public partial class frmSettings : Form +public partial class FrmSettings : Form { // Internal variables public ClassSettings Settings { get; private set; } - private DataTable _table; + private readonly DataTable _table; private Color[] _previousColors; // To be used when the state of radSurpise changes only at radSurprise_CheckedChanged private float[] _previousFrequencies; // To be used when the state of radSurpise changes only at radSurprise_CheckedChanged - public frmSettings() + public FrmSettings() { // Set form icon var strPath = System.IO.Path.GetDirectoryName(Environment.ProcessPath); @@ -41,7 +41,7 @@ public frmSettings() } - public frmSettings(ClassSettings settings) + public FrmSettings(ClassSettings settings) : this() { UpdateControls(settings); @@ -72,9 +72,9 @@ private void UpdateControls(ClassSettings settings) this.trackWaiting.Enabled = this.chkWaiting.Checked; this.numButtons.Value = Settings.NumberOfButtons; - this.numButtonMax.Value = Convert.ToDecimal(Settings.OuterButtonRatio, Settings.AppCulture); - this.numButtonMin.Value = Convert.ToDecimal(Settings.InnerButtonRatio, Settings.AppCulture); - this.numButtonDistance.Value = Convert.ToDecimal(Settings.CenterButtonRatio, Settings.AppCulture); + this.numButtonMax.Value = Convert.ToDecimal(Settings.OuterButtonRatio); + this.numButtonMin.Value = Convert.ToDecimal(Settings.InnerButtonRatio); + this.numButtonDistance.Value = Convert.ToDecimal(Settings.CenterButtonRatio); this.numButtonClick.Value = Convert.ToDecimal(Settings.ButtonClickOffset); this.numBoardIn.Value = Convert.ToDecimal(Settings.InnerBoardRatio); @@ -100,20 +100,18 @@ private void UpdateControls(ClassSettings settings) } } - - private void Accept_Click(object sender, EventArgs e) { Settings.NumberOfButtons = Convert.ToInt32(this.numButtons.Value); Settings.ButtonColors = String.Join("-", this.DemoBoard.ButtonColors.Select(x => x.ToArgb().ToString("X"))); Settings.ButtonFrequencies = String.Join("-", this.DemoBoard.ButtonFrequencies); - Settings.OuterButtonRatio = Convert.ToSingle(this.numButtonMax.Value, Settings.AppCulture); - Settings.InnerButtonRatio = Convert.ToSingle(this.numButtonMin.Value, Settings.AppCulture); - Settings.CenterButtonRatio = Convert.ToSingle(this.numButtonDistance.Value, Settings.AppCulture); + Settings.OuterButtonRatio = Convert.ToSingle(this.numButtonMax.Value); + Settings.InnerButtonRatio = Convert.ToSingle(this.numButtonMin.Value); + Settings.CenterButtonRatio = Convert.ToSingle(this.numButtonDistance.Value); - Settings.InnerBoardRatio = Convert.ToSingle(this.numBoardIn.Value, Settings.AppCulture); - Settings.OuterBoardRatio = Convert.ToSingle(this.numBoardOut.Value, Settings.AppCulture); - Settings.BoardRotation = Convert.ToSingle(this.numBoardRotation.Value, Settings.AppCulture); + Settings.InnerBoardRatio = Convert.ToSingle(this.numBoardIn.Value); + Settings.OuterBoardRatio = Convert.ToSingle(this.numBoardOut.Value); + Settings.BoardRotation = Convert.ToSingle(this.numBoardRotation.Value); Settings.ColorBackground = this.pctBack.BackColor.ToArgb(); Settings.ColorOuterCircle = this.pctOut.BackColor.ToArgb(); Settings.ColorInnerCircle = this.pctIn.BackColor.ToArgb(); @@ -136,62 +134,6 @@ private void Accept_Click(object sender, EventArgs e) Close(); } - private void ApplySettings(ProgramSettings _settings) - { - try - { - // tabPlayMode - SimonGame.PlayMode play = (SimonGame.PlayMode)Convert.ToInt32(_settings.ContainsKey("PlayMode")); - this.radClassic.Checked = ((play & SimonGame.PlayMode.SimonClassic) == SimonGame.PlayMode.SimonClassic); - this.radAdds.Checked = ((play & SimonGame.PlayMode.PlayerAdds) == SimonGame.PlayMode.PlayerAdds); - this.radChoose.Checked = ((play & SimonGame.PlayMode.ChooseYourColor) == SimonGame.PlayMode.ChooseYourColor); - this.radBounce.Checked = ((play & SimonGame.PlayMode.SimonBounce) == SimonGame.PlayMode.SimonBounce); - this.radSurprise.Checked = ((play & SimonGame.PlayMode.SimonSurprise) == SimonGame.PlayMode.SimonSurprise); - this.radRewind.Checked = ((play & SimonGame.PlayMode.SimonRewind) == SimonGame.PlayMode.SimonRewind); - this.radRandom.Checked = ((play & SimonGame.PlayMode.SimonRandom) == SimonGame.PlayMode.SimonRandom); - this.chkSpeed.Checked = ((play & SimonGame.PlayMode.TimeIncremental) == SimonGame.PlayMode.TimeIncremental); - this.chkWaiting.Checked = ((play & SimonGame.PlayMode.TimeWaiting) == SimonGame.PlayMode.TimeWaiting); - this.numWaiting.Value = Convert.ToInt32(_settings.GetOrDefault("TimeWaiting")); - this.numWaiting.Enabled = this.chkWaiting.Checked; - this.trackWaiting.Enabled = this.chkWaiting.Checked; - - // tabInterface - this.numButtons.Value = Convert.ToInt32(_settings["NumberOfButtons"]); - this.DemoBoard.ButtonColors = Array.ConvertAll(_settings["ButtonColors"].Split('-'), x => Color.FromArgb(int.Parse(x, System.Globalization.NumberStyles.HexNumber))); - this.DemoBoard.ButtonFrequencies = Array.ConvertAll(_settings["ButtonFrequencies"].Split('-'), float.Parse); - this.numButtonMax.Value = Convert.ToDecimal(_settings.GetOrDefault("OuterButtonRatio"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - this.numButtonMin.Value = Convert.ToDecimal(_settings.GetOrDefault("InnerButtonRatio"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - this.numButtonDistance.Value = Convert.ToDecimal(_settings.GetOrDefault("CenterButtonRatio"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - this.numButtonClick.Value = Convert.ToDecimal(_settings.GetOrDefault("ButtonClickOffset"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - - // tabBoard - this.numBoardIn.Value = Convert.ToDecimal(_settings.GetOrDefault("InnerBoardRatio"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - this.numBoardOut.Value = Convert.ToDecimal(_settings.GetOrDefault("OuterBoardRatio"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - this.numBoardRotation.Value = Convert.ToDecimal(_settings.GetOrDefault("BoardRotation"), System.Globalization.CultureInfo.InvariantCulture.NumberFormat); - this.pctBack.BackColor = Color.FromArgb(Convert.ToInt32(_settings.GetOrDefault("ColorBackground"))); - this.pctOut.BackColor = Color.FromArgb(Convert.ToInt32(_settings.GetOrDefault("ColorOuterCircle"))); - this.pctIn.BackColor = Color.FromArgb(Convert.ToInt32(_settings.GetOrDefault("ColorInnerCircle"))); - - this.DemoBoard.Font = new Font(_settings.GetOrDefault("FontFamilyName"), DemoBoard.Font.SizeInPoints); - this.lblFontFamily.Text = "Font: " + this.DemoBoard.Font.FontFamily.Name; - - this.chkStartUp.Checked = Convert.ToInt32(_settings.GetOrDefault("WindowPosition")) == 1; - - } - catch (KeyNotFoundException e) - { - using (new CenterWinDialog(this)) - { - MessageBox.Show(this, - "Unexpected error while applying settings.\nPlease report the error to the engineer.", - "Settings error", - MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } - - private void Cancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; @@ -203,12 +145,13 @@ private void Reset_Click(object sender, EventArgs e) DialogResult result; using (new CenterWinDialog(this)) { - result = MessageBox.Show(this, "You are about to override the actual settings\n" + - "with the default values.\n\n" + - "Are you sure you want to continue?", - "Override settings", - MessageBoxButtons.YesNo, - MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); + result = MessageBox.Show(this, + "You are about to override the actual settings\n" + + "with the default values.\n\n" + + "Are you sure you want to continue?", + "Override settings", + MessageBoxButtons.YesNo, + MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); } // If "Yes", then reset values to default @@ -533,7 +476,7 @@ private void pctIn_BackColorChanged(object sender, EventArgs e) //pctBack.BackColor = pctBack.BackColor; } - private void btnFontFamily_Click(object sender, EventArgs e) + private void FontFamily_Click(object sender, EventArgs e) { FontDialog frmFont = new() {