From 7df09b91e2753ecdc5b48c45dc6a19c615944889 Mon Sep 17 00:00:00 2001 From: integralfx Date: Tue, 7 May 2019 21:46:14 +1000 Subject: [PATCH] Refactoring --- MemTestHelper/Form1.Designer.cs | 470 +++++++------- MemTestHelper/Form1.cs | 973 +++++++++++------------------ MemTestHelper/MemTest.cs | 182 ++++++ MemTestHelper/MemTestHelper.csproj | 2 + MemTestHelper/WinAPI.cs | 168 +++++ 5 files changed, 951 insertions(+), 844 deletions(-) create mode 100644 MemTestHelper/MemTest.cs create mode 100644 MemTestHelper/WinAPI.cs diff --git a/MemTestHelper/Form1.Designer.cs b/MemTestHelper/Form1.Designer.cs index b777f07..d230e89 100644 --- a/MemTestHelper/Form1.Designer.cs +++ b/MemTestHelper/Form1.Designer.cs @@ -28,90 +28,90 @@ protected override void Dispose(bool disposing) /// private void InitializeComponent() { - this.tab_control = new System.Windows.Forms.TabControl(); + this.tabControl = new System.Windows.Forms.TabControl(); this.tab_main = new System.Windows.Forms.TabPage(); this.btn_hide = new System.Windows.Forms.Button(); - this.lst_coverage = new System.Windows.Forms.ListView(); + this.lstCoverage = new System.Windows.Forms.ListView(); this.hdr_no = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.hdr_coverage = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.hdr_errors = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); - this.lbl_speed_value = new System.Windows.Forms.Label(); + this.lblSpeedValue = new System.Windows.Forms.Label(); this.lbl_speed = new System.Windows.Forms.Label(); - this.lbl_estimated_time = new System.Windows.Forms.Label(); + this.lblEstimatedTime = new System.Windows.Forms.Label(); this.lbl_estimated = new System.Windows.Forms.Label(); - this.lbl_elapsed_time = new System.Windows.Forms.Label(); + this.lblElapsedTime = new System.Windows.Forms.Label(); this.lbl_elapsed = new System.Windows.Forms.Label(); this.btn_show = new System.Windows.Forms.Button(); - this.btn_stop = new System.Windows.Forms.Button(); - this.btn_run = new System.Windows.Forms.Button(); - this.cbo_threads = new System.Windows.Forms.ComboBox(); + this.btnStop = new System.Windows.Forms.Button(); + this.btnRun = new System.Windows.Forms.Button(); + this.cboThreads = new System.Windows.Forms.ComboBox(); this.lbl_num_threads = new System.Windows.Forms.Label(); - this.txt_ram = new System.Windows.Forms.TextBox(); - this.btn_auto_ram = new System.Windows.Forms.Button(); + this.txtRAM = new System.Windows.Forms.TextBox(); + this.btnAutoRAM = new System.Windows.Forms.Button(); this.tab_settings = new System.Windows.Forms.TabPage(); - this.chk_start_min = new System.Windows.Forms.CheckBox(); - this.chk_stop_at_total = new System.Windows.Forms.CheckBox(); - this.chk_stop_on_err = new System.Windows.Forms.CheckBox(); - this.txt_stop_at = new System.Windows.Forms.TextBox(); - this.chk_stop_at = new System.Windows.Forms.CheckBox(); - this.cbo_rows = new System.Windows.Forms.ComboBox(); + this.chkStartMin = new System.Windows.Forms.CheckBox(); + this.chkStopAtTotal = new System.Windows.Forms.CheckBox(); + this.chkStopOnError = new System.Windows.Forms.CheckBox(); + this.txtStopAt = new System.Windows.Forms.TextBox(); + this.chkStopAt = new System.Windows.Forms.CheckBox(); + this.cboRows = new System.Windows.Forms.ComboBox(); this.btn_center = new System.Windows.Forms.Button(); - this.ud_win_height = new System.Windows.Forms.NumericUpDown(); - this.ud_y_offset = new System.Windows.Forms.NumericUpDown(); + this.udWinHeight = new System.Windows.Forms.NumericUpDown(); + this.udYOffset = new System.Windows.Forms.NumericUpDown(); this.lbl_win_height = new System.Windows.Forms.Label(); this.lbl_y_offset = new System.Windows.Forms.Label(); - this.ud_y_spacing = new System.Windows.Forms.NumericUpDown(); + this.udYSpacing = new System.Windows.Forms.NumericUpDown(); this.lbl_rows = new System.Windows.Forms.Label(); this.lbl_y_spacing = new System.Windows.Forms.Label(); - this.ud_x_spacing = new System.Windows.Forms.NumericUpDown(); + this.udXSpacing = new System.Windows.Forms.NumericUpDown(); this.lbl_x_spacing = new System.Windows.Forms.Label(); - this.ud_x_offset = new System.Windows.Forms.NumericUpDown(); + this.udXOffset = new System.Windows.Forms.NumericUpDown(); this.lbl_x_offset = new System.Windows.Forms.Label(); this.tab_about = new System.Windows.Forms.TabPage(); this.txt_discord = new System.Windows.Forms.TextBox(); this.lbl_discord = new System.Windows.Forms.Label(); this.lbl_version = new System.Windows.Forms.Label(); - this.tab_control.SuspendLayout(); + this.tabControl.SuspendLayout(); this.tab_main.SuspendLayout(); this.tab_settings.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.ud_win_height)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_y_offset)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_y_spacing)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_x_spacing)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_x_offset)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.udWinHeight)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.udYOffset)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.udYSpacing)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.udXSpacing)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.udXOffset)).BeginInit(); this.tab_about.SuspendLayout(); this.SuspendLayout(); // // tab_control // - this.tab_control.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); - this.tab_control.Controls.Add(this.tab_main); - this.tab_control.Controls.Add(this.tab_settings); - this.tab_control.Controls.Add(this.tab_about); - this.tab_control.Location = new System.Drawing.Point(0, 0); - this.tab_control.Margin = new System.Windows.Forms.Padding(0); - this.tab_control.Name = "tab_control"; - this.tab_control.SelectedIndex = 0; - this.tab_control.Size = new System.Drawing.Size(227, 382); - this.tab_control.TabIndex = 0; + this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); + this.tabControl.Controls.Add(this.tab_main); + this.tabControl.Controls.Add(this.tab_settings); + this.tabControl.Controls.Add(this.tab_about); + this.tabControl.Location = new System.Drawing.Point(0, 0); + this.tabControl.Margin = new System.Windows.Forms.Padding(0); + this.tabControl.Name = "tab_control"; + this.tabControl.SelectedIndex = 0; + this.tabControl.Size = new System.Drawing.Size(227, 382); + this.tabControl.TabIndex = 0; // // tab_main // this.tab_main.Controls.Add(this.btn_hide); - this.tab_main.Controls.Add(this.lst_coverage); - this.tab_main.Controls.Add(this.lbl_speed_value); + this.tab_main.Controls.Add(this.lstCoverage); + this.tab_main.Controls.Add(this.lblSpeedValue); this.tab_main.Controls.Add(this.lbl_speed); - this.tab_main.Controls.Add(this.lbl_estimated_time); + this.tab_main.Controls.Add(this.lblEstimatedTime); this.tab_main.Controls.Add(this.lbl_estimated); - this.tab_main.Controls.Add(this.lbl_elapsed_time); + this.tab_main.Controls.Add(this.lblElapsedTime); this.tab_main.Controls.Add(this.lbl_elapsed); this.tab_main.Controls.Add(this.btn_show); - this.tab_main.Controls.Add(this.btn_stop); - this.tab_main.Controls.Add(this.btn_run); - this.tab_main.Controls.Add(this.cbo_threads); + this.tab_main.Controls.Add(this.btnStop); + this.tab_main.Controls.Add(this.btnRun); + this.tab_main.Controls.Add(this.cboThreads); this.tab_main.Controls.Add(this.lbl_num_threads); - this.tab_main.Controls.Add(this.txt_ram); - this.tab_main.Controls.Add(this.btn_auto_ram); + this.tab_main.Controls.Add(this.txtRAM); + this.tab_main.Controls.Add(this.btnAutoRAM); this.tab_main.Location = new System.Drawing.Point(4, 22); this.tab_main.Margin = new System.Windows.Forms.Padding(0); this.tab_main.Name = "tab_main"; @@ -128,22 +128,22 @@ private void InitializeComponent() this.btn_hide.TabIndex = 8; this.btn_hide.Text = "Hide"; this.btn_hide.UseVisualStyleBackColor = true; - this.btn_hide.Click += new System.EventHandler(this.btn_hide_Click); + this.btn_hide.Click += new System.EventHandler(this.btnHide_Click); // // lst_coverage // - this.lst_coverage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); - this.lst_coverage.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.lstCoverage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); + this.lstCoverage.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.hdr_no, this.hdr_coverage, this.hdr_errors}); - this.lst_coverage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.lst_coverage.Location = new System.Drawing.Point(4, 154); - this.lst_coverage.Name = "lst_coverage"; - this.lst_coverage.Size = new System.Drawing.Size(210, 199); - this.lst_coverage.TabIndex = 7; - this.lst_coverage.UseCompatibleStateImageBehavior = false; - this.lst_coverage.View = System.Windows.Forms.View.Details; + this.lstCoverage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lstCoverage.Location = new System.Drawing.Point(4, 154); + this.lstCoverage.Name = "lst_coverage"; + this.lstCoverage.Size = new System.Drawing.Size(210, 199); + this.lstCoverage.TabIndex = 7; + this.lstCoverage.UseCompatibleStateImageBehavior = false; + this.lstCoverage.View = System.Windows.Forms.View.Details; // // hdr_no // @@ -162,12 +162,12 @@ private void InitializeComponent() // // lbl_speed_value // - this.lbl_speed_value.AutoSize = true; - this.lbl_speed_value.Location = new System.Drawing.Point(81, 137); - this.lbl_speed_value.Name = "lbl_speed_value"; - this.lbl_speed_value.Size = new System.Drawing.Size(54, 13); - this.lbl_speed_value.TabIndex = 6; - this.lbl_speed_value.Text = "0.00MB/s"; + this.lblSpeedValue.AutoSize = true; + this.lblSpeedValue.Location = new System.Drawing.Point(81, 137); + this.lblSpeedValue.Name = "lbl_speed_value"; + this.lblSpeedValue.Size = new System.Drawing.Size(54, 13); + this.lblSpeedValue.TabIndex = 6; + this.lblSpeedValue.Text = "0.00MB/s"; // // lbl_speed // @@ -180,12 +180,12 @@ private void InitializeComponent() // // lbl_estimated_time // - this.lbl_estimated_time.AutoSize = true; - this.lbl_estimated_time.Location = new System.Drawing.Point(81, 122); - this.lbl_estimated_time.Name = "lbl_estimated_time"; - this.lbl_estimated_time.Size = new System.Drawing.Size(62, 13); - this.lbl_estimated_time.TabIndex = 6; - this.lbl_estimated_time.Text = "00h00m00s"; + this.lblEstimatedTime.AutoSize = true; + this.lblEstimatedTime.Location = new System.Drawing.Point(81, 122); + this.lblEstimatedTime.Name = "lbl_estimated_time"; + this.lblEstimatedTime.Size = new System.Drawing.Size(62, 13); + this.lblEstimatedTime.TabIndex = 6; + this.lblEstimatedTime.Text = "00h00m00s"; // // lbl_estimated // @@ -198,12 +198,12 @@ private void InitializeComponent() // // lbl_elapsed_time // - this.lbl_elapsed_time.AutoSize = true; - this.lbl_elapsed_time.Location = new System.Drawing.Point(81, 107); - this.lbl_elapsed_time.Name = "lbl_elapsed_time"; - this.lbl_elapsed_time.Size = new System.Drawing.Size(62, 13); - this.lbl_elapsed_time.TabIndex = 6; - this.lbl_elapsed_time.Text = "00h00m00s"; + this.lblElapsedTime.AutoSize = true; + this.lblElapsedTime.Location = new System.Drawing.Point(81, 107); + this.lblElapsedTime.Name = "lbl_elapsed_time"; + this.lblElapsedTime.Size = new System.Drawing.Size(62, 13); + this.lblElapsedTime.TabIndex = 6; + this.lblElapsedTime.Text = "00h00m00s"; // // lbl_elapsed // @@ -222,40 +222,40 @@ private void InitializeComponent() this.btn_show.TabIndex = 5; this.btn_show.Text = "Show"; this.btn_show.UseVisualStyleBackColor = true; - this.btn_show.Click += new System.EventHandler(this.btn_show_Click); + this.btn_show.Click += new System.EventHandler(this.btnShow_Click); // // btn_stop // - this.btn_stop.Enabled = false; - this.btn_stop.Location = new System.Drawing.Point(112, 53); - this.btn_stop.Name = "btn_stop"; - this.btn_stop.Size = new System.Drawing.Size(85, 25); - this.btn_stop.TabIndex = 5; - this.btn_stop.Text = "Stop"; - this.btn_stop.UseVisualStyleBackColor = true; - this.btn_stop.Click += new System.EventHandler(this.btn_stop_Click); + this.btnStop.Enabled = false; + this.btnStop.Location = new System.Drawing.Point(112, 53); + this.btnStop.Name = "btn_stop"; + this.btnStop.Size = new System.Drawing.Size(85, 25); + this.btnStop.TabIndex = 5; + this.btnStop.Text = "Stop"; + this.btnStop.UseVisualStyleBackColor = true; + this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // btn_run // - this.btn_run.Location = new System.Drawing.Point(21, 53); - this.btn_run.Name = "btn_run"; - this.btn_run.Size = new System.Drawing.Size(85, 25); - this.btn_run.TabIndex = 5; - this.btn_run.Text = "Run"; - this.btn_run.UseVisualStyleBackColor = true; - this.btn_run.Click += new System.EventHandler(this.btn_run_Click); + this.btnRun.Location = new System.Drawing.Point(21, 53); + this.btnRun.Name = "btn_run"; + this.btnRun.Size = new System.Drawing.Size(85, 25); + this.btnRun.TabIndex = 5; + this.btnRun.Text = "Run"; + this.btnRun.UseVisualStyleBackColor = true; + this.btnRun.Click += new System.EventHandler(this.btnRun_Click); // // cbo_threads // - this.cbo_threads.DropDownHeight = 100; - this.cbo_threads.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.cbo_threads.FormattingEnabled = true; - this.cbo_threads.IntegralHeight = false; - this.cbo_threads.Location = new System.Drawing.Point(146, 28); - this.cbo_threads.Name = "cbo_threads"; - this.cbo_threads.Size = new System.Drawing.Size(50, 21); - this.cbo_threads.TabIndex = 4; - this.cbo_threads.SelectionChangeCommitted += new System.EventHandler(this.cbo_threads_SelectionChangeCommitted); + this.cboThreads.DropDownHeight = 100; + this.cboThreads.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.cboThreads.FormattingEnabled = true; + this.cboThreads.IntegralHeight = false; + this.cboThreads.Location = new System.Drawing.Point(146, 28); + this.cboThreads.Name = "cbo_threads"; + this.cboThreads.Size = new System.Drawing.Size(50, 21); + this.cboThreads.TabIndex = 4; + this.cboThreads.SelectionChangeCommitted += new System.EventHandler(this.cboThreads_SelectionChangeCommitted); // // lbl_num_threads // @@ -268,41 +268,41 @@ private void InitializeComponent() // // txt_ram // - this.txt_ram.Location = new System.Drawing.Point(146, 3); - this.txt_ram.Name = "txt_ram"; - this.txt_ram.Size = new System.Drawing.Size(50, 20); - this.txt_ram.TabIndex = 2; + this.txtRAM.Location = new System.Drawing.Point(146, 3); + this.txtRAM.Name = "txt_ram"; + this.txtRAM.Size = new System.Drawing.Size(50, 20); + this.txtRAM.TabIndex = 2; // // btn_auto_ram // - this.btn_auto_ram.Location = new System.Drawing.Point(21, 3); - this.btn_auto_ram.Margin = new System.Windows.Forms.Padding(0); - this.btn_auto_ram.Name = "btn_auto_ram"; - this.btn_auto_ram.Size = new System.Drawing.Size(100, 20); - this.btn_auto_ram.TabIndex = 1; - this.btn_auto_ram.Text = "RAM to test (MB):"; - this.btn_auto_ram.UseVisualStyleBackColor = true; - this.btn_auto_ram.Click += new System.EventHandler(this.btn_auto_ram_Click); + this.btnAutoRAM.Location = new System.Drawing.Point(21, 3); + this.btnAutoRAM.Margin = new System.Windows.Forms.Padding(0); + this.btnAutoRAM.Name = "btn_auto_ram"; + this.btnAutoRAM.Size = new System.Drawing.Size(100, 20); + this.btnAutoRAM.TabIndex = 1; + this.btnAutoRAM.Text = "RAM to test (MB):"; + this.btnAutoRAM.UseVisualStyleBackColor = true; + this.btnAutoRAM.Click += new System.EventHandler(this.btnAutoRam_Click); // // tab_settings // - this.tab_settings.Controls.Add(this.chk_start_min); - this.tab_settings.Controls.Add(this.chk_stop_at_total); - this.tab_settings.Controls.Add(this.chk_stop_on_err); - this.tab_settings.Controls.Add(this.txt_stop_at); - this.tab_settings.Controls.Add(this.chk_stop_at); - this.tab_settings.Controls.Add(this.cbo_rows); + this.tab_settings.Controls.Add(this.chkStartMin); + this.tab_settings.Controls.Add(this.chkStopAtTotal); + this.tab_settings.Controls.Add(this.chkStopOnError); + this.tab_settings.Controls.Add(this.txtStopAt); + this.tab_settings.Controls.Add(this.chkStopAt); + this.tab_settings.Controls.Add(this.cboRows); this.tab_settings.Controls.Add(this.btn_center); - this.tab_settings.Controls.Add(this.ud_win_height); - this.tab_settings.Controls.Add(this.ud_y_offset); + this.tab_settings.Controls.Add(this.udWinHeight); + this.tab_settings.Controls.Add(this.udYOffset); this.tab_settings.Controls.Add(this.lbl_win_height); this.tab_settings.Controls.Add(this.lbl_y_offset); - this.tab_settings.Controls.Add(this.ud_y_spacing); + this.tab_settings.Controls.Add(this.udYSpacing); this.tab_settings.Controls.Add(this.lbl_rows); this.tab_settings.Controls.Add(this.lbl_y_spacing); - this.tab_settings.Controls.Add(this.ud_x_spacing); + this.tab_settings.Controls.Add(this.udXSpacing); this.tab_settings.Controls.Add(this.lbl_x_spacing); - this.tab_settings.Controls.Add(this.ud_x_offset); + this.tab_settings.Controls.Add(this.udXOffset); this.tab_settings.Controls.Add(this.lbl_x_offset); this.tab_settings.Location = new System.Drawing.Point(4, 22); this.tab_settings.Margin = new System.Windows.Forms.Padding(0); @@ -314,69 +314,69 @@ private void InitializeComponent() // // chk_start_min // - this.chk_start_min.AutoSize = true; - this.chk_start_min.Checked = true; - this.chk_start_min.CheckState = System.Windows.Forms.CheckState.Checked; - this.chk_start_min.Location = new System.Drawing.Point(21, 181); - this.chk_start_min.Name = "chk_start_min"; - this.chk_start_min.Size = new System.Drawing.Size(96, 17); - this.chk_start_min.TabIndex = 8; - this.chk_start_min.Text = "Start minimised"; - this.chk_start_min.UseVisualStyleBackColor = true; + this.chkStartMin.AutoSize = true; + this.chkStartMin.Checked = true; + this.chkStartMin.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkStartMin.Location = new System.Drawing.Point(21, 181); + this.chkStartMin.Name = "chk_start_min"; + this.chkStartMin.Size = new System.Drawing.Size(96, 17); + this.chkStartMin.TabIndex = 8; + this.chkStartMin.Text = "Start minimised"; + this.chkStartMin.UseVisualStyleBackColor = true; // // chk_stop_at_total // - this.chk_stop_at_total.AutoSize = true; - this.chk_stop_at_total.Enabled = false; - this.chk_stop_at_total.Location = new System.Drawing.Point(156, 134); - this.chk_stop_at_total.Name = "chk_stop_at_total"; - this.chk_stop_at_total.Size = new System.Drawing.Size(50, 17); - this.chk_stop_at_total.TabIndex = 6; - this.chk_stop_at_total.Text = "Total"; - this.chk_stop_at_total.UseVisualStyleBackColor = true; + this.chkStopAtTotal.AutoSize = true; + this.chkStopAtTotal.Enabled = false; + this.chkStopAtTotal.Location = new System.Drawing.Point(156, 134); + this.chkStopAtTotal.Name = "chk_stop_at_total"; + this.chkStopAtTotal.Size = new System.Drawing.Size(50, 17); + this.chkStopAtTotal.TabIndex = 6; + this.chkStopAtTotal.Text = "Total"; + this.chkStopAtTotal.UseVisualStyleBackColor = true; // // chk_stop_on_err // - this.chk_stop_on_err.AutoSize = true; - this.chk_stop_on_err.Checked = true; - this.chk_stop_on_err.CheckState = System.Windows.Forms.CheckState.Checked; - this.chk_stop_on_err.Location = new System.Drawing.Point(21, 157); - this.chk_stop_on_err.Name = "chk_stop_on_err"; - this.chk_stop_on_err.Size = new System.Drawing.Size(87, 17); - this.chk_stop_on_err.TabIndex = 4; - this.chk_stop_on_err.Text = "Stop on error"; - this.chk_stop_on_err.UseVisualStyleBackColor = true; + this.chkStopOnError.AutoSize = true; + this.chkStopOnError.Checked = true; + this.chkStopOnError.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkStopOnError.Location = new System.Drawing.Point(21, 157); + this.chkStopOnError.Name = "chk_stop_on_err"; + this.chkStopOnError.Size = new System.Drawing.Size(87, 17); + this.chkStopOnError.TabIndex = 4; + this.chkStopOnError.Text = "Stop on error"; + this.chkStopOnError.UseVisualStyleBackColor = true; // // txt_stop_at // - this.txt_stop_at.Enabled = false; - this.txt_stop_at.Location = new System.Drawing.Point(100, 131); - this.txt_stop_at.Name = "txt_stop_at"; - this.txt_stop_at.Size = new System.Drawing.Size(50, 20); - this.txt_stop_at.TabIndex = 5; + this.txtStopAt.Enabled = false; + this.txtStopAt.Location = new System.Drawing.Point(100, 131); + this.txtStopAt.Name = "txt_stop_at"; + this.txtStopAt.Size = new System.Drawing.Size(50, 20); + this.txtStopAt.TabIndex = 5; // // chk_stop_at // - this.chk_stop_at.AutoSize = true; - this.chk_stop_at.Location = new System.Drawing.Point(21, 134); - this.chk_stop_at.Name = "chk_stop_at"; - this.chk_stop_at.Size = new System.Drawing.Size(80, 17); - this.chk_stop_at.TabIndex = 4; - this.chk_stop_at.Text = "Stop at (%):"; - this.chk_stop_at.UseVisualStyleBackColor = true; - this.chk_stop_at.CheckedChanged += new System.EventHandler(this.chk_stop_at_CheckedChanged); + this.chkStopAt.AutoSize = true; + this.chkStopAt.Location = new System.Drawing.Point(21, 134); + this.chkStopAt.Name = "chk_stop_at"; + this.chkStopAt.Size = new System.Drawing.Size(80, 17); + this.chkStopAt.TabIndex = 4; + this.chkStopAt.Text = "Stop at (%):"; + this.chkStopAt.UseVisualStyleBackColor = true; + this.chkStopAt.CheckedChanged += new System.EventHandler(this.chkStopAt_CheckedChanged); // // cbo_rows // - this.cbo_rows.DropDownHeight = 100; - this.cbo_rows.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.cbo_rows.FormattingEnabled = true; - this.cbo_rows.IntegralHeight = false; - this.cbo_rows.Location = new System.Drawing.Point(106, 104); - this.cbo_rows.Name = "cbo_rows"; - this.cbo_rows.Size = new System.Drawing.Size(50, 21); - this.cbo_rows.TabIndex = 3; - this.cbo_rows.SelectionChangeCommitted += new System.EventHandler(this.cbo_rows_SelectionChangeCommitted); + this.cboRows.DropDownHeight = 100; + this.cboRows.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.cboRows.FormattingEnabled = true; + this.cboRows.IntegralHeight = false; + this.cboRows.Location = new System.Drawing.Point(106, 104); + this.cboRows.Name = "cbo_rows"; + this.cboRows.Size = new System.Drawing.Size(50, 21); + this.cboRows.TabIndex = 3; + this.cboRows.SelectionChangeCommitted += new System.EventHandler(this.cboRows_SelectionChangeCommitted); // // btn_center // @@ -386,48 +386,48 @@ private void InitializeComponent() this.btn_center.TabIndex = 2; this.btn_center.Text = "Center"; this.btn_center.UseVisualStyleBackColor = true; - this.btn_center.Click += new System.EventHandler(this.btn_center_Click); + this.btn_center.Click += new System.EventHandler(this.btnCenter_Click); // // ud_win_height // - this.ud_win_height.Location = new System.Drawing.Point(100, 202); - this.ud_win_height.Maximum = new decimal(new int[] { + this.udWinHeight.Location = new System.Drawing.Point(100, 202); + this.udWinHeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); - this.ud_win_height.Minimum = new decimal(new int[] { + this.udWinHeight.Minimum = new decimal(new int[] { 420, 0, 0, 0}); - this.ud_win_height.Name = "ud_win_height"; - this.ud_win_height.Size = new System.Drawing.Size(50, 20); - this.ud_win_height.TabIndex = 1; - this.ud_win_height.Value = new decimal(new int[] { + this.udWinHeight.Name = "ud_win_height"; + this.udWinHeight.Size = new System.Drawing.Size(50, 20); + this.udWinHeight.TabIndex = 1; + this.udWinHeight.Value = new decimal(new int[] { 420, 0, 0, 0}); - this.ud_win_height.ValueChanged += new System.EventHandler(this.ud_win_height_ValueChanged); + this.udWinHeight.ValueChanged += new System.EventHandler(this.udWinHeight_ValueChanged); // // ud_y_offset // - this.ud_y_offset.Location = new System.Drawing.Point(66, 30); - this.ud_y_offset.Maximum = new decimal(new int[] { + this.udYOffset.Location = new System.Drawing.Point(66, 30); + this.udYOffset.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); - this.ud_y_offset.Minimum = new decimal(new int[] { + this.udYOffset.Minimum = new decimal(new int[] { 10000, 0, 0, -2147483648}); - this.ud_y_offset.Name = "ud_y_offset"; - this.ud_y_offset.Size = new System.Drawing.Size(50, 20); - this.ud_y_offset.TabIndex = 1; - this.ud_y_offset.ValueChanged += new System.EventHandler(this.offset_changed); + this.udYOffset.Name = "ud_y_offset"; + this.udYOffset.Size = new System.Drawing.Size(50, 20); + this.udYOffset.TabIndex = 1; + this.udYOffset.ValueChanged += new System.EventHandler(this.offset_Changed); // // lbl_win_height // @@ -449,21 +449,21 @@ private void InitializeComponent() // // ud_y_spacing // - this.ud_y_spacing.Location = new System.Drawing.Point(76, 81); - this.ud_y_spacing.Maximum = new decimal(new int[] { + this.udYSpacing.Location = new System.Drawing.Point(76, 81); + this.udYSpacing.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); - this.ud_y_spacing.Minimum = new decimal(new int[] { + this.udYSpacing.Minimum = new decimal(new int[] { 1000, 0, 0, -2147483648}); - this.ud_y_spacing.Name = "ud_y_spacing"; - this.ud_y_spacing.Size = new System.Drawing.Size(50, 20); - this.ud_y_spacing.TabIndex = 1; - this.ud_y_spacing.ValueChanged += new System.EventHandler(this.offset_changed); + this.udYSpacing.Name = "ud_y_spacing"; + this.udYSpacing.Size = new System.Drawing.Size(50, 20); + this.udYSpacing.TabIndex = 1; + this.udYSpacing.ValueChanged += new System.EventHandler(this.offset_Changed); // // lbl_rows // @@ -485,21 +485,21 @@ private void InitializeComponent() // // ud_x_spacing // - this.ud_x_spacing.Location = new System.Drawing.Point(76, 56); - this.ud_x_spacing.Maximum = new decimal(new int[] { + this.udXSpacing.Location = new System.Drawing.Point(76, 56); + this.udXSpacing.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); - this.ud_x_spacing.Minimum = new decimal(new int[] { + this.udXSpacing.Minimum = new decimal(new int[] { 1000, 0, 0, -2147483648}); - this.ud_x_spacing.Name = "ud_x_spacing"; - this.ud_x_spacing.Size = new System.Drawing.Size(50, 20); - this.ud_x_spacing.TabIndex = 1; - this.ud_x_spacing.ValueChanged += new System.EventHandler(this.offset_changed); + this.udXSpacing.Name = "ud_x_spacing"; + this.udXSpacing.Size = new System.Drawing.Size(50, 20); + this.udXSpacing.TabIndex = 1; + this.udXSpacing.ValueChanged += new System.EventHandler(this.offset_Changed); // // lbl_x_spacing // @@ -512,21 +512,21 @@ private void InitializeComponent() // // ud_x_offset // - this.ud_x_offset.Location = new System.Drawing.Point(66, 5); - this.ud_x_offset.Maximum = new decimal(new int[] { + this.udXOffset.Location = new System.Drawing.Point(66, 5); + this.udXOffset.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); - this.ud_x_offset.Minimum = new decimal(new int[] { + this.udXOffset.Minimum = new decimal(new int[] { 10000, 0, 0, -2147483648}); - this.ud_x_offset.Name = "ud_x_offset"; - this.ud_x_offset.Size = new System.Drawing.Size(50, 20); - this.ud_x_offset.TabIndex = 1; - this.ud_x_offset.ValueChanged += new System.EventHandler(this.offset_changed); + this.udXOffset.Name = "ud_x_offset"; + this.udXOffset.Size = new System.Drawing.Size(50, 20); + this.udXOffset.TabIndex = 1; + this.udXOffset.ValueChanged += new System.EventHandler(this.offset_Changed); // // lbl_x_offset // @@ -582,7 +582,7 @@ private void InitializeComponent() this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(226, 381); - this.Controls.Add(this.tab_control); + this.Controls.Add(this.tabControl); this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size(242, 1000); this.MinimumSize = new System.Drawing.Size(242, 420); @@ -592,16 +592,16 @@ private void InitializeComponent() this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); this.Resize += new System.EventHandler(this.Form1_Resize); - this.tab_control.ResumeLayout(false); + this.tabControl.ResumeLayout(false); this.tab_main.ResumeLayout(false); this.tab_main.PerformLayout(); this.tab_settings.ResumeLayout(false); this.tab_settings.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.ud_win_height)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_y_offset)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_y_spacing)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_x_spacing)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.ud_x_offset)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.udWinHeight)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.udYOffset)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.udYSpacing)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.udXSpacing)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.udXOffset)).EndInit(); this.tab_about.ResumeLayout(false); this.tab_about.PerformLayout(); this.ResumeLayout(false); @@ -610,48 +610,48 @@ private void InitializeComponent() #endregion - private System.Windows.Forms.TabControl tab_control; + private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tab_main; private System.Windows.Forms.TabPage tab_settings; private System.Windows.Forms.TabPage tab_about; - private System.Windows.Forms.Button btn_auto_ram; - private System.Windows.Forms.TextBox txt_ram; + private System.Windows.Forms.Button btnAutoRAM; + private System.Windows.Forms.TextBox txtRAM; private System.Windows.Forms.Label lbl_num_threads; - private System.Windows.Forms.ComboBox cbo_threads; + private System.Windows.Forms.ComboBox cboThreads; private System.Windows.Forms.Button btn_show; - private System.Windows.Forms.Button btn_stop; - private System.Windows.Forms.Button btn_run; - private System.Windows.Forms.Label lbl_speed_value; + private System.Windows.Forms.Button btnStop; + private System.Windows.Forms.Button btnRun; + private System.Windows.Forms.Label lblSpeedValue; private System.Windows.Forms.Label lbl_speed; - private System.Windows.Forms.Label lbl_estimated_time; + private System.Windows.Forms.Label lblEstimatedTime; private System.Windows.Forms.Label lbl_estimated; - private System.Windows.Forms.Label lbl_elapsed_time; + private System.Windows.Forms.Label lblElapsedTime; private System.Windows.Forms.Label lbl_elapsed; - private System.Windows.Forms.ListView lst_coverage; + private System.Windows.Forms.ListView lstCoverage; private System.Windows.Forms.ColumnHeader hdr_no; private System.Windows.Forms.ColumnHeader hdr_coverage; private System.Windows.Forms.ColumnHeader hdr_errors; private System.Windows.Forms.Label lbl_x_offset; - private System.Windows.Forms.NumericUpDown ud_x_offset; - private System.Windows.Forms.NumericUpDown ud_y_offset; + private System.Windows.Forms.NumericUpDown udXOffset; + private System.Windows.Forms.NumericUpDown udYOffset; private System.Windows.Forms.Label lbl_y_offset; - private System.Windows.Forms.NumericUpDown ud_y_spacing; + private System.Windows.Forms.NumericUpDown udYSpacing; private System.Windows.Forms.Label lbl_y_spacing; - private System.Windows.Forms.NumericUpDown ud_x_spacing; + private System.Windows.Forms.NumericUpDown udXSpacing; private System.Windows.Forms.Label lbl_x_spacing; private System.Windows.Forms.Button btn_center; - private System.Windows.Forms.ComboBox cbo_rows; + private System.Windows.Forms.ComboBox cboRows; private System.Windows.Forms.Label lbl_rows; - private System.Windows.Forms.CheckBox chk_stop_at_total; - private System.Windows.Forms.TextBox txt_stop_at; - private System.Windows.Forms.CheckBox chk_stop_at; - private System.Windows.Forms.CheckBox chk_stop_on_err; + private System.Windows.Forms.CheckBox chkStopAtTotal; + private System.Windows.Forms.TextBox txtStopAt; + private System.Windows.Forms.CheckBox chkStopAt; + private System.Windows.Forms.CheckBox chkStopOnError; private System.Windows.Forms.TextBox txt_discord; private System.Windows.Forms.Label lbl_discord; private System.Windows.Forms.Label lbl_version; - private System.Windows.Forms.CheckBox chk_start_min; + private System.Windows.Forms.CheckBox chkStartMin; private System.Windows.Forms.Button btn_hide; - private System.Windows.Forms.NumericUpDown ud_win_height; + private System.Windows.Forms.NumericUpDown udWinHeight; private System.Windows.Forms.Label lbl_win_height; } } diff --git a/MemTestHelper/Form1.cs b/MemTestHelper/Form1.cs index a084c84..559854e 100644 --- a/MemTestHelper/Form1.cs +++ b/MemTestHelper/Form1.cs @@ -1,148 +1,162 @@ using Microsoft.VisualBasic.Devices; using System; -using System.Collections; using System.Collections.Generic; using System.ComponentModel; -using System.Data; using System.Diagnostics; using System.Drawing; -using System.Globalization; using System.IO; using System.Linq; -using System.Management; using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; -using System.Windows; using System.Windows.Forms; namespace MemTestHelper { public partial class Form1 : Form { + private readonly int NUM_THREADS, MAX_THREADS; + + private const string MEMTEST_EXE = "memtest.exe", + MEMTEST_CLASSNAME = "#32770", + MEMTEST_BTN_START = "Button1", + MEMTEST_BTN_STOP = "Button2", + MEMTEST_EDT_RAM = "Edit1", + MEMTEST_STATIC_COVERAGE = "Static1", + // If you find this free version useful... + MEMTEST_STATIC_FREE_VER = "Static2", + CFG_FILENAME = "MemTestHelper.cfg"; + + private const int MEMTEST_WIDTH = 217, + MEMTEST_HEIGHT = 247, + MEMTEST_MAX_RAM = 2048, + // interval (in ms) for coverage info list + UPDATE_INTERVAL = 200; + + private MemTest[] memtests; + private BackgroundWorker coverageWorker; + private DateTime startTime; + private System.Timers.Timer timer; + private bool isMinimised = true; + public Form1() { InitializeComponent(); - init_cbo_threads(); - init_lst_coverage(); - init_cbo_rows(); - center_xy_offsets(); + NUM_THREADS = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS")); + MAX_THREADS = NUM_THREADS * 4; + memtests = new MemTest[MAX_THREADS]; - bw_coverage = new BackgroundWorker(); - bw_coverage.WorkerSupportsCancellation = true; - bw_coverage.DoWork += new DoWorkEventHandler(delegate (object o, DoWorkEventArgs args) - { - BackgroundWorker worker = o as BackgroundWorker; + InitCboThreads(); + InitLstCoverage(); + InitCboRows(); + CentreXYOffsets(); + coverageWorker = new BackgroundWorker(); + coverageWorker.WorkerSupportsCancellation = true; + coverageWorker.DoWork += new DoWorkEventHandler((sender, e) => + { + var worker = sender as BackgroundWorker; while (!worker.CancellationPending) { - update_coverage_info(); + UpdateCoverageInfo(); Thread.Sleep(UPDATE_INTERVAL); } - args.Cancel = true; + e.Cancel = true; }); - bw_coverage.RunWorkerCompleted += - new RunWorkerCompletedEventHandler(delegate (object o, RunWorkerCompletedEventArgs args) + coverageWorker.RunWorkerCompleted += + new RunWorkerCompletedEventHandler((sender, e) => { // wait for all MemTests to stop completely - while (is_any_memtest_stopping()) + while (IsAnyMemTestStopping()) Thread.Sleep(100); - update_coverage_info(false); + // TODO: figure out why total coverage is sometimes + // reporting as 0.0 after stopping + UpdateCoverageInfo(false); }); timer = new System.Timers.Timer(1000); - timer.Elapsed += new System.Timers.ElapsedEventHandler(delegate - (object sender, System.Timers.ElapsedEventArgs e) + timer.Elapsed += new System.Timers.ElapsedEventHandler((sender, e) => { Invoke(new MethodInvoker(delegate { - int threads = (int)cbo_threads.SelectedItem; - var elapsed = e.SignalTime - start_time; + var threads = (int)cboThreads.SelectedItem; + var elapsed = e.SignalTime - startTime; - lbl_elapsed_time.Text = String.Format("{0:00}h{1:00}m{2:00}s", - (int)(elapsed.TotalHours), - elapsed.Minutes, - elapsed.Seconds); + lblElapsedTime.Text = String.Format("{0:00}h{1:00}m{2:00}s", + (int)(elapsed.TotalHours), + elapsed.Minutes, + elapsed.Seconds); - double total_coverage = 0; - for (int i = 1; i <= threads; i++) + var total_coverage = 0.0; + for (var i = 1; i <= threads; i++) { - MemTestState state = memtest_states[i - 1]; - var info = get_coverage_info(state.proc.MainWindowHandle); - if (info == null) continue; + var memtest = memtests[i - 1]; + var info = memtest.GetCoverageInfo(); + if (info == null) return; - // for some reason, this sometimes won't close in start_memtests() - close_nag_msg(state.proc.Id, "Message for first-time users", 1); + // For some reason, this sometimes won't close. + memtest.ClickNagMessageBox("Message for first-time users", 1); - close_nag_msg(state.proc.Id, "Memory error detected!", 1); + memtest.ClickNagMessageBox("Memory error detected!", 1); total_coverage += info.Item1; } - if (total_coverage == 0) return; - // round up to next multiple of 100 - int cov = ((int)(total_coverage / 100) + 1) * 100; - double diff = elapsed.TotalMilliseconds, - est = (diff / total_coverage * cov) - diff; - - TimeSpan est_time = TimeSpan.FromMilliseconds(est); - lbl_estimated_time.Text = String.Format("{0:00}h{1:00}m{2:00}s to {3}%", - (int)(est_time.TotalHours), - est_time.Minutes, - est_time.Seconds, - cov); - - int ram = Convert.ToInt32(txt_ram.Text); - double speed = (total_coverage / 100) * ram / (diff / 1000); - lbl_speed_value.Text = $"{speed:f2}MB/s"; + var cov = ((int)(total_coverage / 100) + 1) * 100; + var diff = elapsed.TotalMilliseconds; + var est = (diff / total_coverage * cov) - diff; + + TimeSpan estimatedTime = TimeSpan.FromMilliseconds(est); + lblEstimatedTime.Text = String.Format("{0:00}h{1:00}m{2:00}s to {3}%", + (int)(estimatedTime.TotalHours), + estimatedTime.Minutes, + estimatedTime.Seconds, + cov); + + var ram = Convert.ToInt32(txtRAM.Text); + var speed = (total_coverage / 100) * ram / (diff / 1000); + lblSpeedValue.Text = $"{speed:f2}MB/s"; })); }); } - // event handling + // Event Handling // private void Form1_Load(object sender, EventArgs e) { - load_cfg(); + LoadConfig(); - update_form_height(); - update_lst_coverage_items(); - cbo_rows.Items.Clear(); - init_cbo_rows(); - center_xy_offsets(); + UpdateFormHeight(); + UpdateLstCoverageItems(); + cboRows.Items.Clear(); + InitCboRows(); + CentreXYOffsets(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { - close_memtests(); - save_cfg(); + CloseMemTests(); + SaveConfig(); } private void Form1_Resize(object sender, EventArgs e) { - int threads = (int)cbo_threads.SelectedItem; + var threads = (int)cboThreads.SelectedItem; switch (WindowState) { // minimise MemTest instances case FormWindowState.Minimized: - run_in_background(new MethodInvoker(delegate + RunInBackground(new MethodInvoker(delegate { - for (int i = 0; i < threads; i++) + for (var i = 0; i < threads; i++) { - if (memtest_states[i] != null) + if (memtests[i] != null) { - IntPtr hwnd = memtest_states[i].proc.MainWindowHandle; - - if (!IsIconic(hwnd)) - ShowWindow(hwnd, SW_MINIMIZE); - + memtests[i].Minimised = true; Thread.Sleep(10); } } @@ -151,28 +165,25 @@ private void Form1_Resize(object sender, EventArgs e) // restore previous state of MemTest instances case FormWindowState.Normal: - run_in_background(new MethodInvoker(delegate + RunInBackground(new MethodInvoker(delegate { /* - * is_minimised is true when user clicked the hide button - * this means that the memtest instances should be kept minimised - */ - if (!is_minimised) + * isMinimised is true when user clicked the hide button. + * This means that the memtest instances should be kept minimised. + */ + if (!isMinimised) { - for (int i = 0; i < threads; i++) + for (var i = 0; i < threads; i++) { - if (memtest_states[i] != null) + if (memtests[i] != null) { - IntPtr hwnd = memtest_states[i].proc.MainWindowHandle; - - ShowWindow(hwnd, SW_RESTORE); - + memtests[i].Minimised = false; Thread.Sleep(10); } } // user may have changed offsets while minimised - move_memtests(); + LayOutMemTests(); // hack to bring form to top TopMost = true; @@ -185,15 +196,15 @@ private void Form1_Resize(object sender, EventArgs e) // update the height if (Size.Height >= MinimumSize.Height && Size.Height <= MaximumSize.Height) - ud_win_height.Value = Size.Height; + udWinHeight.Value = Size.Height; } - private void btn_auto_ram_Click(object sender, EventArgs e) + private void btnAutoRam_Click(object sender, EventArgs e) { - txt_ram.Text = get_free_ram().ToString(); + txtRAM.Text = GetFreeRAM().ToString(); } - private void btn_run_Click(object sender, EventArgs e) + private void btnRun_Click(object sender, EventArgs e) { if (!File.Exists(MEMTEST_EXE)) { @@ -201,166 +212,158 @@ private void btn_run_Click(object sender, EventArgs e) return; } - if (!validate_input()) return; + if (!ValidateInput()) return; - btn_auto_ram.Enabled = false; - txt_ram.Enabled = false; - cbo_threads.Enabled = false; + btnAutoRAM.Enabled = false; + txtRAM.Enabled = false; + cboThreads.Enabled = false; //cbo_rows.Enabled = false; - btn_run.Enabled = false; - btn_stop.Enabled = true; - chk_stop_at.Enabled = false; - txt_stop_at.Enabled = false; - chk_stop_at_total.Enabled = false; - chk_stop_on_err.Enabled = false; - chk_start_min.Enabled = false; + btnRun.Enabled = false; + btnStop.Enabled = true; + chkStopAt.Enabled = false; + txtStopAt.Enabled = false; + chkStopAtTotal.Enabled = false; + chkStopOnError.Enabled = false; + chkStartMin.Enabled = false; // run in background as start_memtests can block - run_in_background(new MethodInvoker(delegate + RunInBackground(new MethodInvoker(delegate { - start_memtests(); + StartMemTests(); - if (!bw_coverage.IsBusy) - bw_coverage.RunWorkerAsync(); - start_time = DateTime.Now; + if (!coverageWorker.IsBusy) + coverageWorker.RunWorkerAsync(); + startTime = DateTime.Now; timer.Start(); Activate(); })); } - private void btn_stop_Click(object sender, EventArgs e) + private void btnStop_Click(object sender, EventArgs e) { - Parallel.For(0, (int)cbo_threads.SelectedItem, i => + Parallel.For(0, (int)cboThreads.SelectedItem, i => { - if (!memtest_states[i].is_finished) - ControlClick(memtest_states[i].proc.MainWindowHandle, MEMTEST_BTN_STOP); + if (!memtests[i].Finished) + memtests[i].Stop(); }); - bw_coverage.CancelAsync(); + coverageWorker.CancelAsync(); timer.Stop(); - btn_auto_ram.Enabled = true; - txt_ram.Enabled = true; - cbo_threads.Enabled = true; - //cbo_rows.Enabled = true; - btn_run.Enabled = true; - btn_stop.Enabled = false; - chk_stop_at.Enabled = true; - if (chk_stop_at.Checked) + btnAutoRAM.Enabled = true; + txtRAM.Enabled = true; + cboThreads.Enabled = true; + btnRun.Enabled = true; + btnStop.Enabled = false; + chkStopAt.Enabled = true; + if (chkStopAt.Checked) { - txt_stop_at.Enabled = true; - chk_stop_at_total.Enabled = true; + txtStopAt.Enabled = true; + chkStopAtTotal.Enabled = true; } - chk_stop_on_err.Enabled = true; - chk_start_min.Enabled = true; + chkStopOnError.Enabled = true; + chkStartMin.Enabled = true; // wait for all memtests to fully stop - while (is_any_memtest_stopping()) + while (IsAnyMemTestStopping()) Thread.Sleep(100); MessageBox.Show("Please press Ok to update coverage and errors", "MemTest finished"); } - private void btn_show_Click(object sender, EventArgs e) + private void btnShow_Click(object sender, EventArgs e) { - // run in background as Thread.Sleep can lockup the GUI - int threads = (int)cbo_threads.SelectedItem; - run_in_background(new MethodInvoker(delegate + // Run in background as Thread.Sleep can lockup the GUI. + var threads = (int)cboThreads.SelectedItem; + RunInBackground(new MethodInvoker(delegate { - for (int i = 0; i < threads; i++) + for (var i = 0; i < threads; i++) { - if (memtest_states[i] != null) + var memtest = memtests[i]; + if (memtest != null) { - IntPtr hwnd = memtest_states[i].proc.MainWindowHandle; - - if (IsIconic(hwnd)) - ShowWindow(hwnd, SW_RESTORE); - else - SetForegroundWindow(hwnd); + memtest.Minimised = false; Thread.Sleep(10); } } - is_minimised = false; + isMinimised = false; - // user may have changed offsets while minimised - move_memtests(); + // User may have changed offsets while minimised. + LayOutMemTests(); Activate(); })); } - private void btn_hide_Click(object sender, EventArgs e) + private void btnHide_Click(object sender, EventArgs e) { - int threads = (int)cbo_threads.SelectedItem; - run_in_background(new MethodInvoker(delegate + var threads = (int)cboThreads.SelectedItem; + RunInBackground(new MethodInvoker(delegate { - for (int i = 0; i < threads; i++) + for (var i = 0; i < threads; i++) { - if (memtest_states[i] != null) + var memtest = memtests[i]; + if (memtest != null) { - IntPtr hwnd = memtest_states[i].proc.MainWindowHandle; - - if (!IsIconic(hwnd)) - ShowWindow(hwnd, SW_MINIMIZE); - + memtest.Minimised = true; Thread.Sleep(10); } } - is_minimised = true; + isMinimised = true; })); } - private void offset_changed(object sender, EventArgs e) + private void offset_Changed(object sender, EventArgs e) { - run_in_background(new MethodInvoker(delegate { move_memtests(); })); + RunInBackground(new MethodInvoker(delegate { LayOutMemTests(); })); } - private void btn_center_Click(object sender, EventArgs e) + private void btnCenter_Click(object sender, EventArgs e) { - center_xy_offsets(); + CentreXYOffsets(); } - private void cbo_rows_SelectionChangeCommitted(object sender, EventArgs e) + private void cboRows_SelectionChangeCommitted(object sender, EventArgs e) { - center_xy_offsets(); + CentreXYOffsets(); } - private void cbo_threads_SelectionChangeCommitted(object sender, EventArgs e) + private void cboThreads_SelectionChangeCommitted(object sender, EventArgs e) { - update_lst_coverage_items(); + UpdateLstCoverageItems(); - cbo_rows.Items.Clear(); - init_cbo_rows(); - center_xy_offsets(); + cboRows.Items.Clear(); + InitCboRows(); + CentreXYOffsets(); } - private void chk_stop_at_CheckedChanged(object sender, EventArgs e) + private void chkStopAt_CheckedChanged(object sender, EventArgs e) { - if (chk_stop_at.Checked) + if (chkStopAt.Checked) { - txt_stop_at.Enabled = true; - chk_stop_at_total.Enabled = true; + txtStopAt.Enabled = true; + chkStopAtTotal.Enabled = true; } else { - txt_stop_at.Enabled = false; - chk_stop_at_total.Enabled = false; + txtStopAt.Enabled = false; + chkStopAtTotal.Enabled = false; } } - private void ud_win_height_ValueChanged(object sender, EventArgs e) + private void udWinHeight_ValueChanged(object sender, EventArgs e) { - update_form_height(); + UpdateFormHeight(); } - // helper functions + // Helper Functions // - // returns free RAM in MB - private ulong get_free_ram() + // Returns free RAM in MB. + private ulong GetFreeRAM() { /* * Available RAM = Free + Standby @@ -383,12 +386,12 @@ private ulong get_free_ram() } // TODO: error checking - private bool load_cfg() + private bool LoadConfig() { - string[] valid_keys = { "ram", "threads", "x_offset", "y_offset", - "x_spacing", "y_spacing", "rows", "stop_at", - "stop_at_value", "stop_at_total", "stop_on_error", - "start_min", "win_height" }; + string[] validKeys = { "ram", "threads", "x_offset", "y_offset", + "x_spacing", "y_spacing", "rows", "stop_at", + "stop_at_value", "stop_at_total", "stop_on_error", + "start_min", "win_height" }; try { @@ -397,13 +400,14 @@ private bool load_cfg() foreach (string l in lines) { - string[] s = l.Split('='); + var s = l.Split('='); if (s.Length != 2) continue; s[0] = s[0].Trim(); s[1] = s[1].Trim(); - if (valid_keys.Contains(s[0])) + if (validKeys.Contains(s[0])) { + // skip blank values if (s[1].Length == 0) continue; int v; @@ -414,56 +418,57 @@ private bool load_cfg() else return false; } + // input values in controls foreach (KeyValuePair kv in cfg) { switch (kv.Key) { case "ram": - txt_ram.Text = kv.Value.ToString(); + txtRAM.Text = kv.Value.ToString(); break; case "threads": - cbo_threads.SelectedItem = kv.Value; + cboThreads.SelectedItem = kv.Value; break; case "x_offset": - ud_x_offset.Value = kv.Value; + udXOffset.Value = kv.Value; break; case "y_offset": - ud_y_offset.Value = kv.Value; + udYOffset.Value = kv.Value; break; case "x_spacing": - ud_x_spacing.Value = kv.Value; + udXSpacing.Value = kv.Value; break; case "y_spacing": - ud_y_spacing.Value = kv.Value; + udYSpacing.Value = kv.Value; break; case "stop_at": - chk_stop_at.Checked = kv.Value != 0; + chkStopAt.Checked = kv.Value != 0; break; case "stop_at_value": - txt_stop_at.Text = kv.Value.ToString(); + txtStopAt.Text = kv.Value.ToString(); break; case "stop_at_total": - chk_stop_at_total.Checked = kv.Value != 0; + chkStopAtTotal.Checked = kv.Value != 0; break; case "stop_on_error": - chk_stop_on_err.Checked = kv.Value != 0; + chkStopOnError.Checked = kv.Value != 0; break; case "start_min": - chk_start_min.Checked = kv.Value != 0; + chkStartMin.Checked = kv.Value != 0; break; case "win_height": - ud_win_height.Value = kv.Value; + udWinHeight.Value = kv.Value; break; } } } - catch(FileNotFoundException e) + catch(FileNotFoundException) { return false; } @@ -471,81 +476,86 @@ private bool load_cfg() return true; } - private bool save_cfg() + private bool SaveConfig() { + StreamWriter file = null; try { - var file = new StreamWriter(CFG_FILENAME); - List lines = new List(); + file = new StreamWriter(CFG_FILENAME); + var lines = new List(); - lines.Add($"ram = {txt_ram.Text}"); - lines.Add($"threads = {(int)cbo_threads.SelectedItem}"); + lines.Add($"ram = {txtRAM.Text}"); + lines.Add($"threads = {(int)cboThreads.SelectedItem}"); - lines.Add($"x_offset = {ud_x_offset.Value}"); - lines.Add($"y_offset = {ud_y_offset.Value}"); - lines.Add($"x_spacing = {ud_x_spacing.Value}"); - lines.Add($"y_spacing = {ud_y_spacing.Value}"); - lines.Add($"rows = {cbo_rows.SelectedItem}"); + lines.Add($"x_offset = {udXOffset.Value}"); + lines.Add($"y_offset = {udYOffset.Value}"); + lines.Add($"x_spacing = {udXSpacing.Value}"); + lines.Add($"y_spacing = {udYSpacing.Value}"); + lines.Add($"rows = {cboRows.SelectedItem}"); - lines.Add(string.Format("stop_at = {0}", chk_stop_at.Checked ? 1 : 0)); - lines.Add($"stop_at_value = {txt_stop_at.Text}"); - lines.Add(string.Format("stop_at_total = {0}", chk_stop_at_total.Checked ? 1 : 0)); - lines.Add(string.Format("stop_on_error = {0}", chk_stop_on_err.Checked ? 1 : 0)); + lines.Add(string.Format("stop_at = {0}", chkStopAt.Checked ? 1 : 0)); + lines.Add($"stop_at_value = {txtStopAt.Text}"); + lines.Add(string.Format("stop_at_total = {0}", chkStopAtTotal.Checked ? 1 : 0)); + lines.Add(string.Format("stop_on_error = {0}", chkStopOnError.Checked ? 1 : 0)); - lines.Add(string.Format("start_min = {0}", chk_start_min.Checked ? 1 : 0)); + lines.Add(string.Format("start_min = {0}", chkStartMin.Checked ? 1 : 0)); - lines.Add($"win_height = {ud_win_height.Value}"); + lines.Add($"win_height = {udWinHeight.Value}"); - foreach (string l in lines) + foreach (var l in lines) file.WriteLine(l); - - file.Close(); } - catch (Exception e) + catch (Exception) { return false; } + finally + { + // BaseStream isn't null when open. + if (file != null && file.BaseStream != null) + file.Close(); + } return true; } - private void update_form_height() + private void UpdateFormHeight() { - Size = new Size(Size.Width, (int)ud_win_height.Value); + Size = new Size(Size.Width, (int)udWinHeight.Value); } - private bool validate_input() + private bool ValidateInput() { - ComputerInfo ci = new ComputerInfo(); - UInt64 total_ram = ci.TotalPhysicalMemory / (1024 * 1024), - avail_ram = ci.AvailablePhysicalMemory / (1024 * 1024); + var ci = new ComputerInfo(); + UInt64 totalRAM = ci.TotalPhysicalMemory / (1024 * 1024), + availableRAM = ci.AvailablePhysicalMemory / (1024 * 1024); - string str_ram = txt_ram.Text; + var ramText = txtRAM.Text; // automatically input available ram if empty - if (str_ram.Length == 0) + if (ramText.Length == 0) { - str_ram = get_free_ram().ToString(); - txt_ram.Text = str_ram; + ramText = GetFreeRAM().ToString(); + txtRAM.Text = ramText; } else { - if (!str_ram.All(char.IsDigit)) + if (!ramText.All(char.IsDigit)) { - show_error_msgbox("Amount of RAM must be an integer"); + ShowErrorMsgBox("Amount of RAM must be an integer"); return false; } } - int threads = (int)cbo_threads.SelectedItem, - ram = Convert.ToInt32(str_ram); + int threads = (int)cboThreads.SelectedItem, + ram = Convert.ToInt32(ramText); if (ram < threads) { - show_error_msgbox($"Amount of RAM must be greater than {threads}"); + ShowErrorMsgBox($"Amount of RAM must be greater than {threads}"); return false; } if (ram > MEMTEST_MAX_RAM * threads) { - show_error_msgbox( + ShowErrorMsgBox( $"Amount of RAM must be at most {MEMTEST_MAX_RAM * threads}\n" + "Try increasing the number of threads\n" + "or reducing amount of RAM" @@ -553,16 +563,16 @@ private bool validate_input() return false; } - if ((UInt64)ram > total_ram) + if ((ulong)ram > totalRAM) { - show_error_msgbox($"Amount of RAM exceeds total RAM ({total_ram})"); + ShowErrorMsgBox($"Amount of RAM exceeds total RAM ({totalRAM})"); return false; } - if ((UInt64)ram > avail_ram) + if ((ulong)ram > availableRAM) { var res = MessageBox.Show( - $"Amount of RAM exceeds available RAM ({avail_ram})\n" + + $"Amount of RAM exceeds available RAM ({availableRAM})\n" + "This will cause RAM to be paged to your storage,\n" + "which may make MemTest really slow.\n" + "Continue?", @@ -575,26 +585,26 @@ private bool validate_input() } // validate stop at % and error count - if (chk_stop_at.Checked) + if (chkStopAt.Checked) { - string str_stop_at = txt_stop_at.Text; + var stopAtText = txtStopAt.Text; - if (str_stop_at == "") + if (stopAtText == "") { - show_error_msgbox("Please enter stop at (%)"); + ShowErrorMsgBox("Please enter stop at (%)"); return false; } - if (!str_stop_at.All(char.IsDigit)) + if (!stopAtText.All(char.IsDigit)) { - show_error_msgbox("Stop at (%) must be an integer"); + ShowErrorMsgBox("Stop at (%) must be an integer"); return false; } - int stop_at = Convert.ToInt32(str_stop_at); - if (stop_at <= 0) + var stopAt = Convert.ToInt32(stopAtText); + if (stopAt <= 0) { - show_error_msgbox("Stop at (%) must be greater than 0"); + ShowErrorMsgBox("Stop at (%) must be greater than 0"); return false; } } @@ -602,276 +612,219 @@ private bool validate_input() return true; } - private void init_lst_coverage() + private void InitLstCoverage() { - /* - * stop flickering - * https://stackoverflow.com/a/15268338 - */ + // Stop flickering: https://stackoverflow.com/a/15268338 var method = typeof(ListView).GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic); - method.Invoke(lst_coverage, new object[] { ControlStyles.OptimizedDoubleBuffer, true }); + method.Invoke(lstCoverage, new object[] { ControlStyles.OptimizedDoubleBuffer, true }); - for (int i = 0; i <= (int)cbo_threads.SelectedItem; i++) + for (var i = 0; i <= (int)cboThreads.SelectedItem; i++) { string[] row = { i.ToString(), "-", "-" }; // first row is total if (i == 0) row[0] = "T"; - lst_coverage.Items.Add(new ListViewItem(row)); + lstCoverage.Items.Add(new ListViewItem(row)); } } - private void update_lst_coverage_items() + private void UpdateLstCoverageItems() { - int threads = (int)cbo_threads.SelectedItem; - var items = lst_coverage.Items; + var threads = (int)cboThreads.SelectedItem; + var items = lstCoverage.Items; if (threads < items.Count) { - for (int i = items.Count - 1; i > threads; i--) + for (var i = items.Count - 1; i > threads; i--) items.RemoveAt(i); } else { - for (int i = items.Count; i <= threads; i++) + for (var i = items.Count; i <= threads; i++) { string[] row = { i.ToString(), "-", "-" }; - lst_coverage.Items.Add(new ListViewItem(row)); + lstCoverage.Items.Add(new ListViewItem(row)); } } } - private void init_cbo_threads() + private void InitCboThreads() { - for (int i = 0; i < MAX_THREADS; i++) - cbo_threads.Items.Add(i + 1); + for (var i = 0; i < MAX_THREADS; i++) + cboThreads.Items.Add(i + 1); - cbo_threads.SelectedItem = NUM_THREADS; + cboThreads.SelectedItem = NUM_THREADS; } - private void init_cbo_rows() + private void InitCboRows() { - int threads = (int)cbo_threads.SelectedItem; + var threads = (int)cboThreads.SelectedItem; - for (int i = 1; i <= threads; i++) + for (var i = 1; i <= threads; i++) { if (threads % i == 0) - cbo_rows.Items.Add(i); + cboRows.Items.Add(i); } - cbo_rows.SelectedItem = threads % 2 == 0 ? 2 : 1; + cboRows.SelectedItem = threads % 2 == 0 ? 2 : 1; } - void center_xy_offsets() + private void CentreXYOffsets() { - Rectangle screen = Screen.FromControl(this).Bounds; - int rows = (int)cbo_rows.SelectedItem, - cols = (int)cbo_threads.SelectedItem / rows, - x_offset = (screen.Width - MEMTEST_WIDTH * cols) / 2, - y_offset = (screen.Height - MEMTEST_HEIGHT * rows) / 2; - - ud_x_offset.Value = x_offset; - ud_y_offset.Value = y_offset; + var screen = Screen.FromControl(this).Bounds; + int rows = (int)cboRows.SelectedItem, + cols = (int)cboThreads.SelectedItem / rows, + xOffset = (screen.Width - MEMTEST_WIDTH * cols) / 2, + yOffset = (screen.Height - MEMTEST_HEIGHT * rows) / 2; + + udXOffset.Value = xOffset; + udYOffset.Value = yOffset; } - private void start_memtests() + private void StartMemTests() { - close_all_memtests(); + CloseAllMemTests(); - int threads = (int)cbo_threads.SelectedItem; + var threads = (int)cboThreads.SelectedItem; Parallel.For(0, threads, i => { - MemTestState state = new MemTestState(); - state.proc = Process.Start(MEMTEST_EXE); - state.is_finished = false; - memtest_states[i] = state; - - // wait for process to start - while (string.IsNullOrEmpty(state.proc.MainWindowTitle)) - { - close_nag_msg(state.proc.Id, "Welcome, New MemTest User"); - Thread.Sleep(100); - state.proc.Refresh(); - } - - IntPtr hwnd = state.proc.MainWindowHandle; - double ram = Convert.ToDouble(txt_ram.Text) / threads; - - ControlSetText(hwnd, MEMTEST_EDT_RAM, $"{ram:f2}"); - ControlSetText(hwnd, MEMTEST_STATIC_FREE_VER, "MemTestHelper by ∫ntegral#7834"); - ControlClick(hwnd, MEMTEST_BTN_START); - - while (!close_nag_msg(state.proc.Id, "Message for first-time users")) - Thread.Sleep(100); - - if (chk_start_min.Checked) - ShowWindow(hwnd, SW_MINIMIZE); + double ram = Convert.ToDouble(txtRAM.Text) / threads; + memtests[i] = new MemTest(); + memtests[i].Start(ram, chkStartMin.Checked); }); - if (!chk_start_min.Checked) - move_memtests(); + if (!chkStartMin.Checked) + LayOutMemTests(); } - private void move_memtests() + private void LayOutMemTests() { - int x_offset = (int)ud_x_offset.Value, - y_offset = (int)ud_y_offset.Value, - x_spacing = (int)ud_x_spacing.Value - 5, - y_spacing = (int)ud_y_spacing.Value - 3, - rows = (int)cbo_rows.SelectedItem, - cols = (int)cbo_threads.SelectedItem / rows; - - Parallel.For(0, (int)cbo_threads.SelectedItem, i => + int xOffset = (int)udXOffset.Value, + yOffset = (int)udYOffset.Value, + xSpacing = (int)udXSpacing.Value - 5, + ySpacing = (int)udYSpacing.Value - 3, + rows = (int)cboRows.SelectedItem, + cols = (int)cboThreads.SelectedItem / rows; + + Parallel.For(0, (int)cboThreads.SelectedItem, i => { - MemTestState state = memtest_states[i]; - if (state == null) return; + var memtest = memtests[i]; + if (memtest == null || !memtest.Started) return; - IntPtr hwnd = state.proc.MainWindowHandle; int r = i / cols, c = i % cols, - x = c * MEMTEST_WIDTH + c * x_spacing + x_offset, - y = r * MEMTEST_HEIGHT + r * y_spacing + y_offset; + x = c * MEMTEST_WIDTH + c * xSpacing + xOffset, + y = r * MEMTEST_HEIGHT + r * ySpacing + yOffset; - MoveWindow(hwnd, x, y, MEMTEST_WIDTH, MEMTEST_HEIGHT, true); + memtest.Location = new Point(x, y); }); } - // only close MemTests started by MemTestHelper - private void close_memtests() + // Only close MemTests started by MemTestHelper. + private void CloseMemTests() { - Parallel.ForEach(memtest_states, s => + Parallel.For(0, (int)cboThreads.SelectedItem, i => { - try { - if (s != null) s.proc.Kill(); + try + { + memtests[i].Close(); + } + catch (Exception) + { + Console.WriteLine($"Failed to close MemTest #{i}"); } - catch (Exception) { } }); } /* - * close all MemTests, regardless of if they were - * started by MemTestHelper + * Close all MemTests, regardless of if they were + * started by MemTestHelper. */ - private void close_all_memtests() + private void CloseAllMemTests() { // remove the .exe - string name = MEMTEST_EXE.Substring(0, MEMTEST_EXE.Length - 4); - var procs = Process.GetProcessesByName(name); - Parallel.ForEach(procs, p => { p.Kill(); }); + var name = MEMTEST_EXE.Substring(0, MEMTEST_EXE.Length - 4); + var processes = Process.GetProcessesByName(name); + Parallel.ForEach(processes, p => { p.Kill(); }); } - // returns (coverage, errors) - private Tuple get_coverage_info(IntPtr hwnd) + private void UpdateCoverageInfo(bool shouldCheck = true) { - string str = ControlGetText(hwnd, MEMTEST_STATIC_COVERAGE); - if (str == "" || !str.Contains("Coverage")) return null; - - // Test over. 47.3% Coverage, 0 Errors - // ^^^^^^^^^^^^^^^^^^^^^^^^ - int start = str.IndexOfAny("0123456789".ToCharArray()); - if (start == -1) return null; - str = str.Substring(start); - - // 47.3% Coverage, 0 Errors - // ^^^^ - // some countries use a comma as the decimal point - string coverage_str = str.Split("%".ToCharArray())[0].Replace(',', '.'); - double coverage = 0; - double.TryParse(coverage_str, NumberStyles.Any, CultureInfo.InvariantCulture, out coverage); - - // 47.3% Coverage, 0 Errors - // ^^^^^^^^ - start = str.IndexOf("Coverage, ") + "Coverage, ".Length; - str = str.Substring(start); - // 0 Errors - // ^ - int errors = Convert.ToInt32(str.Substring(0, str.IndexOf(" Errors"))); - - return Tuple.Create(coverage, errors); - } - - private void update_coverage_info(bool should_check = true) - { - lst_coverage.Invoke(new MethodInvoker(delegate + lstCoverage.Invoke(new MethodInvoker(delegate { - int threads = (int)cbo_threads.SelectedItem; - double total_coverage = 0; - int total_errors = 0; + var threads = (int)cboThreads.SelectedItem; + var totalCoverage = 0.0; + var totalErrors = 0; // total is index 0 - for (int i = 1; i <= threads; i++) + for (var i = 1; i <= threads; i++) { - var hwnd = memtest_states[i - 1].proc.MainWindowHandle; - var info = get_coverage_info(hwnd); + var memtest = memtests[i - 1]; + var info = memtest.GetCoverageInfo(); if (info == null) continue; double coverage = info.Item1; int errors = info.Item2; - lst_coverage.Items[i].SubItems[1].Text = string.Format("{0:f1}", coverage); - lst_coverage.Items[i].SubItems[2].Text = errors.ToString(); + lstCoverage.Items[i].SubItems[1].Text = string.Format("{0:f1}", coverage); + lstCoverage.Items[i].SubItems[2].Text = errors.ToString(); - if (should_check) + if (shouldCheck) { // check coverage % - if (chk_stop_at.Checked && !chk_stop_at_total.Checked) + if (chkStopAt.Checked && !chkStopAtTotal.Checked) { - int stop_at = Convert.ToInt32(txt_stop_at.Text); - if (coverage > stop_at) + var stopAt = Convert.ToInt32(txtStopAt.Text); + if (coverage > stopAt) { - if (!memtest_states[i - 1].is_finished) - { - ControlClick(hwnd, MEMTEST_BTN_STOP); - memtest_states[i - 1].is_finished = true; - } + if (!memtest.Finished) + memtest.Stop(); } } // check error count - if (chk_stop_on_err.Checked) + if (chkStopOnError.Checked) { if (errors > 0) { - lst_coverage.Items[i].SubItems[1].ForeColor = Color.Red; - - click_btn_stop(); + lstCoverage.Items[i].SubItems[1].ForeColor = Color.Red; + ClickBtnStop(); } } } - total_coverage += coverage; - total_errors += errors; + totalCoverage += coverage; + totalErrors += errors; } // update the total coverage and errors - lst_coverage.Items[0].SubItems[1].Text = string.Format("{0:f1}", total_coverage); - lst_coverage.Items[0].SubItems[2].Text = total_errors.ToString(); + lstCoverage.Items[0].SubItems[1].Text = string.Format("{0:f1}", totalCoverage); + lstCoverage.Items[0].SubItems[2].Text = totalErrors.ToString(); - if (should_check) + if (shouldCheck) { // check total coverage - if (chk_stop_at.Checked && chk_stop_at_total.Checked) + if (chkStopAt.Checked && chkStopAtTotal.Checked) { - int stop_at = Convert.ToInt32(txt_stop_at.Text); - if (total_coverage > stop_at) - click_btn_stop(); + var stopAt = Convert.ToInt32(txtStopAt.Text); + if (totalCoverage > stopAt) + ClickBtnStop(); } - if (is_all_finished()) - click_btn_stop(); + if (IsAllFinished()) + ClickBtnStop(); } })); } /* * MemTest can take a while to stop, - * which causes the total to return 0 + * which causes the total to return 0. */ - private bool is_any_memtest_stopping() + private bool IsAnyMemTestStopping() { - for (int i = 0; i < (int)cbo_threads.SelectedItem; i++) + for (var i = 0; i < (int)cboThreads.SelectedItem; i++) { - IntPtr hwnd = memtest_states[i].proc.MainWindowHandle; - string str = ControlGetText(hwnd, MEMTEST_STATIC_COVERAGE); - if (str != "" && str.Contains("Ending")) return true; + if (memtests[i].Stopping) + return true; } return false; @@ -880,19 +833,19 @@ private bool is_any_memtest_stopping() /* * PerformClick() only works if the button is visible * switch to main tab and PerformClick() then switch - * back to the tab that the user was on + * back to the tab that the user was on. */ - private void click_btn_stop() + private void ClickBtnStop() { - var curr_tab = tab_control.SelectedTab; - if (curr_tab != tab_main) - tab_control.SelectedTab = tab_main; + var currTab = tabControl.SelectedTab; + if (currTab != tab_main) + tabControl.SelectedTab = tab_main; - btn_stop.PerformClick(); - tab_control.SelectedTab = curr_tab; + btnStop.PerformClick(); + tabControl.SelectedTab = currTab; } - private void show_error_msgbox(string msg) + private void ShowErrorMsgBox(string msg) { MessageBox.Show( msg, @@ -902,18 +855,18 @@ private void show_error_msgbox(string msg) ); } - private bool is_all_finished() + private bool IsAllFinished() { - for (int i = 0; i < (int)cbo_threads.SelectedItem; i++) + for (int i = 0; i < (int)cboThreads.SelectedItem; i++) { - if (!memtest_states[i].is_finished) + if (!memtests[i].Finished) return false; } return true; } - private void run_in_background(Delegate method) + private void RunInBackground(Delegate method) { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(delegate (object s, DoWorkEventArgs args) @@ -922,203 +875,5 @@ private void run_in_background(Delegate method) }); bw.RunWorkerAsync(); } - - private bool close_nag_msg(int pid, String window_title, int max_attempts = 100) - { - IntPtr hwnd = IntPtr.Zero; - int attempts = 0; - do - { - hwnd = get_hwnd_from_pid(pid, window_title); - attempts++; - } while (hwnd == IntPtr.Zero && attempts < max_attempts); - - if (hwnd == IntPtr.Zero) return false; - else - { - // click Ok - ControlClick(hwnd, "Button1"); - return true; - } - } - - private IntPtr get_hwnd_from_pid(int pid, String window_title) - { - IntPtr hwnd = IntPtr.Zero; - - EnumWindows( - delegate (IntPtr curr_hwnd, IntPtr lParam) - { - int len = GetWindowTextLength(curr_hwnd); - if (len != window_title.Length) return true; - StringBuilder sb = new StringBuilder(len + 1); - GetWindowText(curr_hwnd, sb, len + 1); - - uint proc_id; - GetWindowThreadProcessId(curr_hwnd, out proc_id); - - if (sb.ToString() == window_title && proc_id == pid) - { - hwnd = curr_hwnd; - return false; - } - else return true; - }, - IntPtr.Zero); - - return hwnd; - } - - /* - * class_name should be - * tries to split class_name as above - * returns (, ) if possible - * otherwise, returns null - */ - private Tuple split_class_name(string class_name) - { - Regex regex = new Regex(@"([a-zA-Z]+)(\d+)"); - Match match = regex.Match(class_name); - - if (!match.Success) return null; - - return Tuple.Create( - match.Groups[1].Value, - Convert.ToInt32(match.Groups[2].Value) - ); - } - - /* - * class_name should be - * where is the name of the class to find - * is the nth window with that matches (1 indexed) - * e.g. Edit1 - * returns the handle to the window if found - * otherwise, returns IntPtr.Zero - */ - private IntPtr find_window(IntPtr hwnd_parent, string class_name) - { - if (hwnd_parent == IntPtr.Zero) - return IntPtr.Zero; - - var name = split_class_name(class_name); - if (name == null) return IntPtr.Zero; - - IntPtr hwnd = IntPtr.Zero; - for (int i = 0; i < name.Item2; i++) - hwnd = FindWindowEx(hwnd_parent, hwnd, name.Item1, null); - - return hwnd; - } - - // emulate AutoIT Control functions - private bool ControlClick(IntPtr hwnd_parent, string class_name) - { - IntPtr hwnd = find_window(hwnd_parent, class_name); - if (hwnd == IntPtr.Zero) return false; - SendNotifyMessage(hwnd, BM_CLICK, IntPtr.Zero, null); - return true; - } - - private bool ControlSetText(IntPtr hwnd_parent, string class_name, string text) - { - IntPtr hwnd = find_window(hwnd_parent, class_name); - if (hwnd == IntPtr.Zero) return false; - return SendMessage(hwnd, WM_SETTEXT, IntPtr.Zero, text) != IntPtr.Zero; - } - - private string ControlGetText(IntPtr hwnd, string class_name) - { - IntPtr hwnd_control = find_window(hwnd, class_name); - if (hwnd_control == IntPtr.Zero) return null; - int len = GetWindowTextLength(hwnd_control); - StringBuilder str = new StringBuilder(len + 1); - GetWindowText(hwnd_control, str, str.Capacity); - return str.ToString(); - } - - [DllImport("user32.dll", SetLastError = true)] - internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); - - [DllImport("user32.dll", SetLastError = true)] - static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); - - // blocks - [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); - - // doesn't block - [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] - static extern bool SendNotifyMessage(IntPtr hWnd, int Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); - - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); - - [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] - static extern int GetWindowTextLength(IntPtr hWnd); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool SetForegroundWindow(IntPtr hWnd); - - [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)] - static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - - // is minimised - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool IsIconic(IntPtr hWnd); - - [DllImport("user32.dll", SetLastError = true)] - static extern int CloseWindow(IntPtr hWnd); - - [DllImport("user32.dll", SetLastError = true)] - static extern IntPtr FindWindow(string lpClassName, string lpWindowName); - - public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); - - [DllImport("user32.dll", SetLastError = true)] - static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); - - public const int WM_SETTEXT = 0xC, WM_LBUTTONDOWN = 0x201, WM_LBUTTONUP = 0x202, - SW_SHOW = 5, SW_RESTORE = 9, SW_MINIMIZE = 6, BM_CLICK = 0xF5; - - private static int NUM_THREADS = Convert.ToInt32(System.Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS")), - MAX_THREADS = NUM_THREADS * 4, - UPDATE_INTERVAL = 200; // interval (in ms) for coverage info list - - private const string MEMTEST_EXE = "memtest.exe", - MEMTEST_CLASSNAME = "#32770", - MEMTEST_BTN_START = "Button1", - MEMTEST_BTN_STOP = "Button2", - MEMTEST_EDT_RAM = "Edit1", - MEMTEST_STATIC_COVERAGE = "Static1", - // If you find this free version useful... - MEMTEST_STATIC_FREE_VER = "Static2", - CFG_FILENAME = "MemTestHelper.cfg"; - - private const int MEMTEST_WIDTH = 217, - MEMTEST_HEIGHT = 247, - MEMTEST_MAX_RAM = 2048; - - private MemTestState[] memtest_states = new MemTestState[MAX_THREADS]; - private BackgroundWorker bw_coverage; - private DateTime start_time; - private System.Timers.Timer timer; - private bool is_minimised = true; - - class MemTestState - { - public Process proc; - public bool is_finished; - } } } diff --git a/MemTestHelper/MemTest.cs b/MemTestHelper/MemTest.cs new file mode 100644 index 0000000..2b50a24 --- /dev/null +++ b/MemTestHelper/MemTest.cs @@ -0,0 +1,182 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.Threading; + +namespace MemTestHelper +{ + class MemTest + { + private const string MEMTEST_EXE = "memtest.exe", + MEMTEST_CLASSNAME = "#32770", + MEMTEST_BTN_START = "Button1", + MEMTEST_BTN_STOP = "Button2", + MEMTEST_EDT_RAM = "Edit1", + MEMTEST_STATIC_COVERAGE = "Static1", + // If you find this free version useful... + MEMTEST_STATIC_FREE_VER = "Static2"; + private const int MEMTEST_WIDTH = 217, + MEMTEST_HEIGHT = 247; + + private Process process = null; + private bool hasStarted = false, isFinished = false; + + public bool Started + { + get { return hasStarted; } + } + + public bool Finished + { + get { return isFinished; } + } + + public bool Minimised + { + get { return hasStarted ? WinAPI.IsIconic(process.MainWindowHandle) : false; } + set + { + if (hasStarted) + { + if (value) + { + WinAPI.ShowWindow(process.MainWindowHandle, WinAPI.SW_MINIMIZE); + } + else + { + if (WinAPI.IsIconic(process.MainWindowHandle)) + WinAPI.ShowWindow(process.MainWindowHandle, WinAPI.SW_RESTORE); + else + WinAPI.SetForegroundWindow(process.MainWindowHandle); + } + } + } + } + + public Point Location + { + set + { + if (process != null && !process.HasExited) + WinAPI.MoveWindow(process.MainWindowHandle, value.X, value.Y, MEMTEST_WIDTH, MEMTEST_HEIGHT, true); + } + } + + public bool Stopping + { + get + { + if (!hasStarted || isFinished || process == null || process.HasExited) + return false; + + string str = WinAPI.ControlGetText(process.MainWindowHandle, MEMTEST_STATIC_COVERAGE); + if (str != "" && str.Contains("Ending")) return true; + + return false; + } + } + + public void Start(double ram, bool startMinimised) + { + process = Process.Start(MEMTEST_EXE); + hasStarted = true; + isFinished = false; + + // wait for process to start + while (string.IsNullOrEmpty(process.MainWindowTitle)) + { + ClickNagMessageBox("Welcome, New MemTest User"); + Thread.Sleep(100); + process.Refresh(); + } + + var hwnd = process.MainWindowHandle; + WinAPI.ControlSetText(hwnd, MEMTEST_EDT_RAM, $"{ram:f2}"); + WinAPI.ControlSetText(hwnd, MEMTEST_STATIC_FREE_VER, "MemTestHelper by ∫ntegral#7834"); + WinAPI.ControlClick(hwnd, MEMTEST_BTN_START); + + while (!ClickNagMessageBox("Message for first-time users")) + Thread.Sleep(100); + + if (startMinimised) + WinAPI.ShowWindow(hwnd, WinAPI.SW_MINIMIZE); + } + + public void Stop() + { + if (process != null && !process.HasExited && + hasStarted && !isFinished) + { + WinAPI.ControlClick(process.MainWindowHandle, MEMTEST_BTN_STOP); + isFinished = true; + } + } + + public void Close() + { + if (hasStarted && !process.HasExited) + process.Kill(); + + process = null; + hasStarted = false; + isFinished = false; + } + + // Returns (coverage, errors). + public Tuple GetCoverageInfo() + { + if (process == null || process.HasExited) + return null; + + var str = WinAPI.ControlGetText(process.MainWindowHandle, MEMTEST_STATIC_COVERAGE); + if (str == "" || !str.Contains("Coverage")) return null; + + // Test over. 47.3% Coverage, 0 Errors + // ^^^^^^^^^^^^^^^^^^^^^^^^ + var start = str.IndexOfAny("0123456789".ToCharArray()); + if (start == -1) return null; + str = str.Substring(start); + + // 47.3% Coverage, 0 Errors + // ^^^^ + // some countries use a comma as the decimal point + var coverageStr = str.Split("%".ToCharArray())[0].Replace(',', '.'); + double coverage; + Double.TryParse(coverageStr, NumberStyles.Any, CultureInfo.InvariantCulture, out coverage); + + // 47.3% Coverage, 0 Errors + // ^^^^^^^^ + start = str.IndexOf("Coverage, ") + "Coverage, ".Length; + str = str.Substring(start); + // 0 Errors + // ^ + var errors = Convert.ToInt32(str.Substring(0, str.IndexOf(" Errors"))); + + return Tuple.Create(coverage, errors); + } + + public bool ClickNagMessageBox(String messageBoxCaption, int maxAttempts = 100) + { + if (!hasStarted || isFinished || process == null || process.HasExited) + return false; + + var hwnd = IntPtr.Zero; + var attempts = 0; + do + { + hwnd = WinAPI.GetHWNDFromPID(process.Id, messageBoxCaption); + attempts++; + } while (hwnd == IntPtr.Zero && attempts < maxAttempts); + + if (hwnd == IntPtr.Zero) return false; + else + { + // click Ok + WinAPI.ControlClick(hwnd, "Button1"); + return true; + } + } + + } +} diff --git a/MemTestHelper/MemTestHelper.csproj b/MemTestHelper/MemTestHelper.csproj index 79f9ab3..6ea3d0c 100644 --- a/MemTestHelper/MemTestHelper.csproj +++ b/MemTestHelper/MemTestHelper.csproj @@ -45,6 +45,8 @@ + + Form diff --git a/MemTestHelper/WinAPI.cs b/MemTestHelper/WinAPI.cs new file mode 100644 index 0000000..8fac221 --- /dev/null +++ b/MemTestHelper/WinAPI.cs @@ -0,0 +1,168 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; + +namespace MemTestHelper +{ + class WinAPI + { + public const int WM_SETTEXT = 0xC, WM_LBUTTONDOWN = 0x201, WM_LBUTTONUP = 0x202, + SW_SHOW = 5, SW_RESTORE = 9, SW_MINIMIZE = 6, BM_CLICK = 0xF5; + + // Emulate AutoIT Control functions + public static bool ControlClick(IntPtr hwndParent, string className) + { + IntPtr hwnd = FindWindow(hwndParent, className); + if (hwnd == IntPtr.Zero) return false; + SendNotifyMessage(hwnd, BM_CLICK, IntPtr.Zero, null); + return true; + } + + public static bool ControlSetText(IntPtr hwndParent, string className, string text) + { + IntPtr hwnd = FindWindow(hwndParent, className); + if (hwnd == IntPtr.Zero) return false; + return SendMessage(hwnd, WM_SETTEXT, IntPtr.Zero, text) != IntPtr.Zero; + } + + public static string ControlGetText(IntPtr hwndParent, string className) + { + IntPtr hwnd = FindWindow(hwndParent, className); + if (hwnd == IntPtr.Zero) return null; + int len = GetWindowTextLength(hwnd); + StringBuilder str = new StringBuilder(len + 1); + GetWindowText(hwnd, str, str.Capacity); + return str.ToString(); + } + + public static IntPtr GetHWNDFromPID(int pid, String window_title = "") + { + IntPtr hwnd = IntPtr.Zero; + + EnumWindows( + delegate (IntPtr curr_hwnd, IntPtr lParam) + { + int len = GetWindowTextLength(curr_hwnd); + if (len != window_title.Length) return true; + StringBuilder sb = new StringBuilder(len + 1); + GetWindowText(curr_hwnd, sb, len + 1); + + uint proc_id; + GetWindowThreadProcessId(curr_hwnd, out proc_id); + + if (proc_id == pid) + { + if (window_title.Length == 0) + hwnd = curr_hwnd; + else + { + if (sb.ToString() == window_title) + hwnd = curr_hwnd; + } + + return false; + } + else return true; + }, + IntPtr.Zero); + + return hwnd; + } + + // Imports + + [DllImport("user32.dll", SetLastError = true)] + public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); + + // blocks + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); + + // doesn't block + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + public static extern bool SendNotifyMessage(IntPtr hWnd, int Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); + + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); + + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + public static extern int GetWindowTextLength(IntPtr hWnd); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)] + public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + // is minimised + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool IsIconic(IntPtr hWnd); + + [DllImport("user32.dll", SetLastError = true)] + public static extern int CloseWindow(IntPtr hWnd); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); + + /* + * className should be + * tries to split class_name as above + * returns (, ) if possible + * otherwise, returns null + */ + private static Tuple SplitClassName(string className) + { + Regex regex = new Regex(@"([a-zA-Z]+)(\d+)"); + Match match = regex.Match(className); + + if (!match.Success) return null; + + return Tuple.Create( + match.Groups[1].Value, + Convert.ToInt32(match.Groups[2].Value) + ); + } + + /* + * className should be + * where is the name of the class to find + * is the nth window with that matches (1 indexed) + * e.g. Edit1 + * returns the handle to the window if found + * otherwise, returns IntPtr.Zero + */ + private static IntPtr FindWindow(IntPtr hwndParent, string className) + { + if (hwndParent == IntPtr.Zero) + return IntPtr.Zero; + + var name = SplitClassName(className); + if (name == null) return IntPtr.Zero; + + IntPtr hwnd = IntPtr.Zero; + for (int i = 0; i < name.Item2; i++) + hwnd = FindWindowEx(hwndParent, hwnd, name.Item1, null); + + return hwnd; + } + } +}