BackgroundWorker's RunWorkerCompleted is triggered twice - c#

I have created a small project with a progress bar to test how BackgroundWorker does its job. So the progress bar goes from 0 to 100%. But now what I want to do is to trigger another BackgroundWorker after the first one finishes its job. The second BackgroundWorker simply has to display a MessageBox. I have put the second worker's RunWorkerAsync() event at the end of the first worker's RunWorkerCompleted() event. To make sure the first worker's method is completed.
Strange thing that happens is that my second worker's DoWork() event is triggered twice.
This is a simplified version of the error I am getting in my main program.
Can anyone spot the issue?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace backgroundworker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw1 = new BackgroundWorker();
bw1.DoWork += new DoWorkEventHandler(bw1_DoWork);
bw1.ProgressChanged += new ProgressChangedEventHandler(bw1_ProgressChanged);
bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw1_RunWorkerCompleted);
bw1.WorkerReportsProgress = true;
bw1.WorkerSupportsCancellation = true;
bw2.DoWork += new DoWorkEventHandler(bw2_DoWork);
bw2.ProgressChanged += new ProgressChangedEventHandler(bw2_ProgressChanged);
bw2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw2_RunWorkerCompleted);
}
private void bw1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(50);
bw1.ReportProgress(i);
if (bw1.CancellationPending)
{
e.Cancel = true;
bw1.ReportProgress(0);
return;
}
}
bw1.ReportProgress(100);
}
private void bw1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
}
private void bw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
}
btnStartAsyncOperation.Enabled = true;
btnCancel.Enabled = false;
bw2.RunWorkerAsync();
}
private void btnStartAsyncOperation_Click(object sender, EventArgs e)
{
btnStartAsyncOperation.Enabled = false;
btnCancel.Enabled = true;
bw1.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
if (bw1.IsBusy)
{
bw1.CancelAsync();
}
}
private void bw2_DoWork(object sender, DoWorkEventArgs e)
{
}
private void bw2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void bw2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Second task is done too.");
}
}
}
Update: Form1.Designer.cs
namespace backgroundworker
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.lblStatus = new System.Windows.Forms.Label();
this.bw1 = new System.ComponentModel.BackgroundWorker();
this.btnStartAsyncOperation = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.bw2 = new System.ComponentModel.BackgroundWorker();
this.SuspendLayout();
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(12, 154);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(1164, 100);
this.progressBar1.TabIndex = 1;
//
// lblStatus
//
this.lblStatus.AutoSize = true;
this.lblStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblStatus.Location = new System.Drawing.Point(469, 42);
this.lblStatus.Name = "lblStatus";
this.lblStatus.Size = new System.Drawing.Size(70, 25);
this.lblStatus.TabIndex = 2;
this.lblStatus.Text = "label1";
//
// bw1
//
this.bw1.WorkerReportsProgress = true;
this.bw1.WorkerSupportsCancellation = true;
this.bw1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bw1_DoWork);
this.bw1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bw1_ProgressChanged);
this.bw1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw1_RunWorkerCompleted);
//
// btnStartAsyncOperation
//
this.btnStartAsyncOperation.Location = new System.Drawing.Point(12, 109);
this.btnStartAsyncOperation.Name = "btnStartAsyncOperation";
this.btnStartAsyncOperation.Size = new System.Drawing.Size(160, 39);
this.btnStartAsyncOperation.TabIndex = 3;
this.btnStartAsyncOperation.Text = "Start";
this.btnStartAsyncOperation.UseVisualStyleBackColor = true;
this.btnStartAsyncOperation.Click += new System.EventHandler(this.btnStartAsyncOperation_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(1024, 109);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(152, 39);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// bw2
//
this.bw2.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bw2_DoWork);
this.bw2.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bw2_ProgressChanged);
this.bw2.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw2_RunWorkerCompleted);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1188, 272);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnStartAsyncOperation);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.progressBar1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label lblStatus;
private System.ComponentModel.BackgroundWorker bw1;
private System.Windows.Forms.Button btnStartAsyncOperation;
private System.Windows.Forms.Button btnCancel;
private System.ComponentModel.BackgroundWorker bw2;
}
}

You have registered the completed event on the designer.
this.bw1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw1_RunWorkerCompleted‌​);
this.bw2.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw2_RunWorkerCompleted‌​);
And then you registered it again on code behind.
bw1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw1_RunWorkerCompleted);
bw2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw2_RunWorkerCompleted);
You need to remove ones of them.

Related

How to remove and stop a thread based on its entry in a Listview/List?

I have some code that starts a new thread every time a button is clicked. Each new thread draws a randomly colored circle in a random location in a primitive graphics engine and is added to a Listview. The link to this engine is https://github.com/NAIT-CNT/GDIDrawer.
I need to find a way to remove and abort a thread based on whatever Listview item the user clicks.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GDIDrawer;
using System.Threading;
namespace ica7
{
public partial class Form1 : Form
{
CDrawer _gdi = new CDrawer();
List<Thread> _threads = new List<Thread>();
Random _rng = new Random();
Point _coords;
int _diameter;
bool _isRunning;
public Form1()
{
InitializeComponent();
_diameter = 10;
_isRunning = true;
btnStopThreads.Enabled = false;
}
private Color RandomColor()
{
return Color.FromArgb(_rng.Next(256), _rng.Next(256), _rng.Next(256));
}
private void DrawCircle(int diameter, Point coords, CDrawer gdi)
{
gdi.AddCenteredEllipse(coords, diameter, diameter, RandomColor());
}
private void btnStartThread_Click(object sender, EventArgs e)
{
btnStopThreads.Enabled = true;
Thread t = new Thread(() =>
{
int diameter = _diameter;
while (_isRunning)
{
_coords.X = _rng.Next(800);
_coords.Y = _rng.Next(600);
DrawCircle(diameter, _coords, _gdi);
Thread.Sleep(10);
}
});
_threads.Add(t);
ListViewItem lvi = new ListViewItem(t.ToString());
lboxThreads.Items.Add(lvi);
t.Start();
}
private void btnStopThreads_Click(object sender, EventArgs e)
{
_threads.ElementAt(lboxThreads.SelectedIndex).Abort();
lboxThreads.Items.RemoveAt(lboxThreads.SelectedIndex);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
_diameter = trackBar1.Value;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
_threads.ForEach(x => x.Abort());
}
}
}
Here is the designer file, in case it's needed:
namespace ica7
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnStartThread = new System.Windows.Forms.Button();
this.btnStopThreads = new System.Windows.Forms.Button();
this.lboxThreads = new System.Windows.Forms.ListBox();
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.lblTbMin = new System.Windows.Forms.Label();
this.lblTbMax = new System.Windows.Forms.Label();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.SuspendLayout();
//
// btnStartThread
//
this.btnStartThread.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.btnStartThread.Location = new System.Drawing.Point(9, 11);
this.btnStartThread.Name = "btnStartThread";
this.btnStartThread.Size = new System.Drawing.Size(121, 23);
this.btnStartThread.TabIndex = 0;
this.btnStartThread.Text = "Start a Thread";
this.btnStartThread.UseVisualStyleBackColor = true;
this.btnStartThread.Click += new System.EventHandler(this.btnStartThread_Click);
//
// btnStopThreads
//
this.btnStopThreads.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.btnStopThreads.Location = new System.Drawing.Point(9, 40);
this.btnStopThreads.Name = "btnStopThreads";
this.btnStopThreads.Size = new System.Drawing.Size(121, 23);
this.btnStopThreads.TabIndex = 1;
this.btnStopThreads.Text = "Stop Selected Thread";
this.btnStopThreads.UseVisualStyleBackColor = true;
this.btnStopThreads.Click += new System.EventHandler(this.btnStopThreads_Click);
//
// lboxThreads
//
this.lboxThreads.FormattingEnabled = true;
this.lboxThreads.Location = new System.Drawing.Point(138, 11);
this.lboxThreads.Name = "lboxThreads";
this.lboxThreads.Size = new System.Drawing.Size(303, 134);
this.lboxThreads.TabIndex = 2;
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(9, 69);
this.trackBar1.Maximum = 50;
this.trackBar1.Minimum = 10;
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(121, 45);
this.trackBar1.TabIndex = 3;
this.trackBar1.Value = 10;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// lblTbMin
//
this.lblTbMin.AutoSize = true;
this.lblTbMin.Location = new System.Drawing.Point(6, 101);
this.lblTbMin.Name = "lblTbMin";
this.lblTbMin.Size = new System.Drawing.Size(19, 13);
this.lblTbMin.TabIndex = 4;
this.lblTbMin.Text = "10";
//
// lblTbMax
//
this.lblTbMax.AutoSize = true;
this.lblTbMax.Location = new System.Drawing.Point(111, 101);
this.lblTbMax.Name = "lblTbMax";
this.lblTbMax.Size = new System.Drawing.Size(19, 13);
this.lblTbMax.TabIndex = 5;
this.lblTbMax.Text = "50";
//
// timer1
//
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.ClientSize = new System.Drawing.Size(453, 157);
this.Controls.Add(this.lblTbMax);
this.Controls.Add(this.lblTbMin);
this.Controls.Add(this.trackBar1);
this.Controls.Add(this.lboxThreads);
this.Controls.Add(this.btnStopThreads);
this.Controls.Add(this.btnStartThread);
this.ForeColor = System.Drawing.SystemColors.ActiveCaption;
this.Name = "Form1";
this.Text = "Form1";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnStartThread;
private System.Windows.Forms.Button btnStopThreads;
private System.Windows.Forms.ListBox lboxThreads;
private System.Windows.Forms.TrackBar trackBar1;
private System.Windows.Forms.Label lblTbMin;
private System.Windows.Forms.Label lblTbMax;
private System.Windows.Forms.Timer timer1;
}
}
If there are superior ways of doing any of this, please let me know. This is my first foray into threads. This is homework.

No overload for 'MainFormLoad' matches delegate 'System.EventHandler' (CS0123)

I've just started to learn programming in C# and I have a problem. I made a simple application (just a window with two buttons). One button starts another program and the other button shows this window again in 2 minutes (it's a sort of reminder). There's no X button, but it can still be closed by ALTF4 which I want to disable.
I've tried e.Cancel = true;, but I am obviously doing something wrong. What I did was doubleclick on the main window, then void MainFormLoad(object sender, EventArgs e) appeared in the code and I changed EventArgs e to FormClosingEventArgs and pasted the above e.Cancel = true; in there.
I am getting the following error:
No overload for 'MainFormLoad' matches delegate 'System.EventHandler' (CS0123)
It refers me to this line in MainForm.Designer.cs:
this.Load += new System.EventHandler(this.MainFormLoad);
Here's the whole code:
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Reminder
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
int duration = 0;
void Timer1Tick(object sender, EventArgs e)
{
duration++;
System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo();
start.FileName = #"C:\ThisProgram.exe";
Process.Start(start);
Application.Exit();
if (duration == 1)
{
Timer.Stop();
}
}
void LaterClick(object sender, EventArgs e)
{
Timer.Enabled = true;
Timer.Start();
Hide();
}
void OKClick(object sender, EventArgs e)
{
System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo();
start.FileName = #"C:\OtherExternalProgram.exe";
Process.Start(start);
Application.Exit();
}
void MainFormLoad(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
}
}
And here is the MainForm.Designer.cs code:
namespace Reminder
{
partial class MainForm
{
/// <summary>
/// Designer variable used to keep track of non-visual components.
/// </summary>
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.Button OK;
private System.Windows.Forms.Timer Timer;
private System.Windows.Forms.Button Later;
/// <summary>
/// Disposes resources used by the form.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.OK = new System.Windows.Forms.Button();
this.Timer = new System.Windows.Forms.Timer(this.components);
this.Later = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// OK
//
this.OK.Location = new System.Drawing.Point(12, 253);
this.OK.Name = "OK";
this.OK.Size = new System.Drawing.Size(75, 23);
this.OK.TabIndex = 0;
this.OK.Text = "OK";
this.OK.UseVisualStyleBackColor = true;
this.OK.Click += new System.EventHandler(this.OKClick);
//
// Timer
//
this.Timer.Interval = 24000;
this.Timer.Tick += new System.EventHandler(this.Timer1Tick);
//
// Later
//
this.Later.Location = new System.Drawing.Point(425, 253);
this.Later.Name = "Later";
this.Later.Size = new System.Drawing.Size(75, 23);
this.Later.TabIndex = 1;
this.Later.Text = "Later";
this.Later.UseVisualStyleBackColor = true;
this.Later.Click += new System.EventHandler(this.LaterClick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Window;
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.ClientSize = new System.Drawing.Size(512, 288);
this.Controls.Add(this.Later);
this.Controls.Add(this.OK);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MainForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.TopMost = true;
this.Load += new System.EventHandler(this.MainFormLoad);
this.ResumeLayout(false);
}
}
}
Thank you in advance for your help.

Nlog write log to RichTextBox error

I'm using Nlog in my project, and now there's a problem, here it is:
I want to write logs into a RichTextBox, everything is OK at first, but when I clear the lines in RTB, and then restart to write logs, it goes wrong, it will not show any line in the RTB.
But, if I use
log.Error("Error\n"); // there is a "\n" in the end
instead of
log.Error("Error");
it will be OK, I don't know why is that...
any clue of this? thanks very much for any suggestion.
BTW I'm using Win7 X64, VS 2013, C# WinForm, .NET 4.0, NLog 3.2.0
using System;
using System.Windows.Forms;
using NLog;
using NLog.Targets;
namespace RTBLogDemo
{
public partial class LogForm : Form
{
#region Designer
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.logRichTextBox = new System.Windows.Forms.RichTextBox();
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.logTimer = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// logRichTextBox
//
this.logRichTextBox.Dock = System.Windows.Forms.DockStyle.Bottom;
this.logRichTextBox.Location = new System.Drawing.Point(0, 173);
this.logRichTextBox.Name = "logRichTextBox";
this.logRichTextBox.Size = new System.Drawing.Size(656, 299);
this.logRichTextBox.TabIndex = 0;
this.logRichTextBox.Text = "";
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(100, 48);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(75, 39);
this.btnStart.TabIndex = 1;
this.btnStart.Text = "start";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(261, 48);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(75, 39);
this.btnStop.TabIndex = 2;
this.btnStop.Text = "stop";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(417, 48);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(75, 39);
this.btnClear.TabIndex = 3;
this.btnClear.Text = "Clear";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// logTimer
//
this.logTimer.Tick += new System.EventHandler(this.logTimer_Tick);
//
// LogForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(656, 472);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.logRichTextBox);
this.Name = "LogForm";
this.Text = "Log Form";
this.Load += new System.EventHandler(this.LogForm_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox logRichTextBox;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Timer logTimer;
#endregion
public LogForm()
{
InitializeComponent();
}
private Logger log;
private void logTimer_Tick(object sender, EventArgs e)
{
log.Error("Error"); // WRONG
// log.Error("Error\n"); // OK
}
private void btnStart_Click(object sender, EventArgs e)
{
logTimer.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
logTimer.Stop();
}
private void btnClear_Click(object sender, EventArgs e)
{
logRichTextBox.Clear();
}
private void InitLogger()
{
RichTextBoxTarget target = new RichTextBoxTarget();
target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
target.ControlName = logRichTextBox.Name;
target.FormName = this.Name;
target.UseDefaultRowColoringRules = true;
target.AutoScroll = true;
target.MaxLines = 50;
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
log = LogManager.GetCurrentClassLogger();
}
private void LogForm_Load(object sender, EventArgs e)
{
InitLogger();
}
}
}

Custom button doesn't work

I want to make a custom button in an UserControl... Like with a hover animation. But in the usercontrol it won't let me execute the events?!
EDIT: I tried taking it out of the user control but that doesn't change anything...
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Title_Bar : UserControl
{
public Title_Bar()
{
InitializeComponent();
}
private void cross_idle_MouseEnter(object sender, EventArgs e)
{
cross_hover.Show();
}
private void cross_hover_MouseLeave(object sender, EventArgs e)
{
cross_hover.Hide();
}
private void max_idle_MouseEnter(object sender, EventArgs e)
{
max_hover.Show();
}
private void max_hover_MouseLeave(object sender, EventArgs e)
{
max_hover.Hide();
}
private void min_idle_MouseEnter(object sender, EventArgs e)
{
min_hover.Show();
}
private void min_hover_MouseLeave(object sender, EventArgs e)
{
min_hover.Hide();
}
private void cross_hover_Click(object sender, EventArgs e)
{
this.ParentForm.Close();
}
}
}
Designer Code:
namespace WindowsFormsApplication1
{
partial class Title_Bar
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Title_Bar));
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.cross_idle = new System.Windows.Forms.PictureBox();
this.max_idle = new System.Windows.Forms.PictureBox();
this.max_hover = new System.Windows.Forms.PictureBox();
this.min_idle = new System.Windows.Forms.PictureBox();
this.min_hover = new System.Windows.Forms.PictureBox();
this.cross_hover = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cross_idle)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.max_idle)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.max_hover)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.min_idle)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.min_hover)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cross_hover)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(49, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(272, 10);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(318, 0);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(50, 10);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// pictureBox3
//
this.pictureBox3.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox3.Image")));
this.pictureBox3.Location = new System.Drawing.Point(0, 0);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(50, 10);
this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox3.TabIndex = 2;
this.pictureBox3.TabStop = false;
//
// cross_idle
//
this.cross_idle.Image = ((System.Drawing.Image)(resources.GetObject("cross_idle.Image")));
this.cross_idle.Location = new System.Drawing.Point(358, 0);
this.cross_idle.Name = "cross_idle";
this.cross_idle.Size = new System.Drawing.Size(10, 10);
this.cross_idle.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.cross_idle.TabIndex = 3;
this.cross_idle.TabStop = false;
this.cross_idle.MouseEnter += new System.EventHandler(this.cross_idle_MouseEnter);
//
// max_idle
//
this.max_idle.Image = ((System.Drawing.Image)(resources.GetObject("max_idle.Image")));
this.max_idle.Location = new System.Drawing.Point(349, 0);
this.max_idle.Name = "max_idle";
this.max_idle.Size = new System.Drawing.Size(10, 10);
this.max_idle.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.max_idle.TabIndex = 4;
this.max_idle.TabStop = false;
this.max_idle.MouseEnter += new System.EventHandler(this.max_idle_MouseEnter);
//
// max_hover
//
this.max_hover.Image = ((System.Drawing.Image)(resources.GetObject("max_hover.Image")));
this.max_hover.Location = new System.Drawing.Point(267, 0);
this.max_hover.Name = "max_hover";
this.max_hover.Size = new System.Drawing.Size(10, 10);
this.max_hover.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.max_hover.TabIndex = 5;
this.max_hover.TabStop = false;
this.max_hover.Visible = false;
this.max_hover.MouseLeave += new System.EventHandler(this.max_hover_MouseLeave);
//
// min_idle
//
this.min_idle.Image = ((System.Drawing.Image)(resources.GetObject("min_idle.Image")));
this.min_idle.Location = new System.Drawing.Point(340, 0);
this.min_idle.Name = "min_idle";
this.min_idle.Size = new System.Drawing.Size(10, 10);
this.min_idle.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.min_idle.TabIndex = 6;
this.min_idle.TabStop = false;
this.min_idle.MouseEnter += new System.EventHandler(this.min_idle_MouseEnter);
//
// min_hover
//
this.min_hover.Image = ((System.Drawing.Image)(resources.GetObject("min_hover.Image")));
this.min_hover.Location = new System.Drawing.Point(237, 0);
this.min_hover.Name = "min_hover";
this.min_hover.Size = new System.Drawing.Size(10, 10);
this.min_hover.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.min_hover.TabIndex = 7;
this.min_hover.TabStop = false;
this.min_hover.Visible = false;
this.min_hover.MouseLeave += new System.EventHandler(this.min_hover_MouseLeave);
//
// cross_hover
//
this.cross_hover.Image = ((System.Drawing.Image)(resources.GetObject("cross_hover.Image")));
this.cross_hover.Location = new System.Drawing.Point(302, 0);
this.cross_hover.Name = "cross_hover";
this.cross_hover.Size = new System.Drawing.Size(10, 10);
this.cross_hover.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.cross_hover.TabIndex = 8;
this.cross_hover.TabStop = false;
this.cross_hover.Visible = false;
this.cross_hover.Click += new System.EventHandler(this.cross_hover_Click);
this.cross_hover.MouseLeave += new System.EventHandler(this.cross_hover_MouseLeave);
//
// Title_Bar
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.cross_hover);
this.Controls.Add(this.min_hover);
this.Controls.Add(this.min_idle);
this.Controls.Add(this.max_hover);
this.Controls.Add(this.max_idle);
this.Controls.Add(this.cross_idle);
this.Controls.Add(this.pictureBox3);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.pictureBox1);
this.Name = "Title_Bar";
this.Size = new System.Drawing.Size(368, 10);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cross_idle)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.max_idle)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.max_hover)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.min_idle)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.min_hover)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cross_hover)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.PictureBox cross_idle;
private System.Windows.Forms.PictureBox max_idle;
private System.Windows.Forms.PictureBox max_hover;
private System.Windows.Forms.PictureBox min_idle;
private System.Windows.Forms.PictureBox min_hover;
private System.Windows.Forms.PictureBox cross_hover;
}
}
I have put in all the picture boxes, but nothing happens!
this.cross_hover.Visible is set to false in the designer file, and calling Show is not going to change that value. Hence, the PictureBox is never shown.
Instead of calling Show(), set Visible to true:
private void cross_idle_MouseEnter(object sender, EventArgs e)
{
this.cross_hover.Visible = true;
}

Load data by Thread

C#:
I want to load big data from Database and in loading progress i want display available to DatagridView. I use IDataReader and BackgroundWorker. But in hard try some way, i get error.
I want when Execute Script to server, the data receive will have Schema information, and it will dynamic to create structure of DatagridView and base from that structure the available data will add to grid row by row and User can see this changed.
My code is below, but error. Any answer to help my I deal, i thanks very much!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
partial class Form1
{
string conectionString = "";
IDbConnection connection;
BackgroundWorker worker;
BindingSource binding;
IDbCommand GetExecuteCommand()
{
string commandText = "select * from dbo.B20DmBp";
SqlCommand command = new SqlCommand();
command.Connection = (SqlConnection)this.connection;
command.CommandText = commandText;
command.CommandType = CommandType.Text;
return command;
}
public Form1()
{
InitializeComponent();
Initialize();
RegisterHandler();
}
void Initialize()
{
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
binding = new BindingSource();
this.dataGridView1.DataSource = binding;
connection = new SqlConnection(conectionString);
}
void RegisterHandler()
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
DataTable table = this.binding.DataSource as DataTable;
IDataReader reader = e.UserState as IDataReader;
table.Rows.Add(this.BuildDataRow(reader));
this.binding.ResetBindings(false);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
IDbCommand command = e.Argument as IDbCommand;
BackgroundWorker worker2 = sender as BackgroundWorker;
try
{
command.Connection.Open();
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (worker.CancellationPending)
{
e.Cancel = true;
}
else
{
worker.ReportProgress(0, reader);
}
}
reader.Close();
command.Connection.Close();
}
catch (Exception)
{
throw;
}
finally
{
command.Connection.Close();
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
throw new NotImplementedException();
}
void StartExecute()
{
this.binding.DataSource = new DataTable();
this.worker.RunWorkerAsync(this.GetExecuteCommand());
}
void CancelExecute()
{
if (this.worker.WorkerSupportsCancellation)
{
this.worker.CancelAsync();
}
}
DataRow BuildDataRow(IDataReader reader)
{
DataTable table = this.binding.DataSource as DataTable;
if (table.Columns.Count == 0)
{
foreach (DataRow row in reader.GetSchemaTable().Rows)
{
string columnName = row["ColumnName"].ToString();
table.Columns.Add(columnName);
}
this.binding.ResetBindings(true);
}
DataRow row2 = table.NewRow();
foreach (DataRow row in reader.GetSchemaTable().Rows)
{
string columnName = row["ColumnName"].ToString();
row2[columnName] = reader[columnName];
}
return row2;
}
private void button1_Click(object sender, EventArgs e)
{
this.StartExecute();
}
private void button2_Click(object sender, EventArgs e)
{
this.CancelExecute();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(35, 26);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(240, 150);
this.dataGridView1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(35, 194);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(127, 194);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(323, 262);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
Are cross thread access error occurs?
if yes, you can resolve as in topic: http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx

Categories

Resources