Using C# paint lines that span all monitors - c#

I have a multi monitor setup and I want to paint a vertical and horizontal line as the user moves their cursor. The lines I want to paint should span all monitors. I'm not entirely sure how to adjust my form to make this possible since when i make it full screen it only maximizes to one monitor.
Do i have to make a form per monitor and send signals to each one when the cursor moves for it to repaint the line?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace fitAllScreens
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FullScreen();
}
public void FullScreen()
{
List<int> xBounds = new List<int>() {};
List<int> yBounds = new List<int>() {};
foreach (Screen screen in Screen.AllScreens)
{
var bounds = screen.Bounds;
xBounds.Add(bounds.X);
xBounds.Add(bounds.Right);
yBounds.Add(bounds.Y);
yBounds.Add(bounds.Bottom);
}
int minX = xBounds.Min();
int maxX = xBounds.Max();
int minY = yBounds.Min();
int maxY = yBounds.Max();
Console.WriteLine(minX + " - " + maxX + " - " + minY + " - " + maxY);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
var graphics = e.Graphics;
base.OnPaint(e);
// Draw ruler guides
Console.WriteLine(Cursor.Position);
var pos = this.PointToClient(Cursor.Position);
using (var pen = new Pen(Color.Red))
{
pen.DashStyle = DashStyle.Dot;
var screenBounds = Screen.PrimaryScreen.Bounds;
graphics.DrawLine(pen, pos.X, screenBounds.Y, pos.X, screenBounds.Height);
graphics.DrawLine(pen, screenBounds.X, pos.Y, screenBounds.Width, pos.Y);
}
}
}
}

I edited your code so it can fit all screens (I test it on 2 screens and it worked well).
public partial class Form1 : Form
{
int minX;
int maxX;
int minY;
int maxY;
public Form1()
{
InitializeComponent();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.FormBorderStyle = FormBorderStyle.None;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.DoubleBuffered = true;
FullScreen();
CreateCloseButtons();
}
private void CloseButtons_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void FullScreen()
{
List<int> xBounds = new List<int>() { };
List<int> yBounds = new List<int>() { };
foreach (Screen screen in Screen.AllScreens)
{
var bounds = screen.WorkingArea;
xBounds.Add(bounds.X);
xBounds.Add(bounds.Right);
yBounds.Add(bounds.Y);
yBounds.Add(bounds.Bottom);
}
minX = xBounds.Min();
maxX = xBounds.Max();
minY = yBounds.Min();
maxY = yBounds.Max();
this.Location = new Point(minX, minY);
//this.Location = this.PointToClient(new Point(minX, minY));
this.Size = new Size(maxX - minX, maxY - minY);
}
protected override void OnMouseMove(MouseEventArgs e)
{
Console.WriteLine(this.Location.X + " - " + this.Location.Y);
Console.WriteLine(this.Size.Width + " - " + this.Location.Y);
base.OnMouseMove(e);
Invalidate(false);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var pos = this.PointToClient(Cursor.Position);
using (var pen = new Pen(Color.Red))
{
pen.Width = 2;
pen.DashStyle = DashStyle.Dot;
e.Graphics.DrawLine(pen, pos.X, minY, pos.X, this.Height);
e.Graphics.DrawLine(pen, minX, pos.Y, this.Width, pos.Y);
}
}
private void CreateCloseButtons()
{
Button button1 = new System.Windows.Forms.Button();
Button button2 = new System.Windows.Forms.Button();
Button button3 = new System.Windows.Forms.Button();
Button button4 = new System.Windows.Forms.Button();
button1.Click += CloseButtons_Click;
button2.Click += CloseButtons_Click;
button3.Click += CloseButtons_Click;
button4.Click += CloseButtons_Click;
//
// top right
//
button1.BackColor = System.Drawing.Color.Red;
button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
button1.ForeColor = System.Drawing.SystemColors.ButtonFace;
button1.Location = new System.Drawing.Point(0, 0);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(21, 23);
button1.TabIndex = 0;
button1.Text = "X";
button1.UseVisualStyleBackColor = false;
//
// bottom left
//
button2.BackColor = System.Drawing.Color.Red;
button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
button2.ForeColor = System.Drawing.SystemColors.ButtonFace;
button2.Location = new System.Drawing.Point(0, this.Height - 23);
button2.Name = "button2";
button2.Size = new System.Drawing.Size(21, 23);
button2.TabIndex = 1;
button2.Text = "X";
button2.UseVisualStyleBackColor = false;
button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
//
// bottom right
//
button3.BackColor = System.Drawing.Color.Red;
button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
button3.ForeColor = System.Drawing.SystemColors.ButtonFace;
button3.Location = new System.Drawing.Point(this.Width - 21, this.Height - 23);
button3.Name = "button3";
button3.Size = new System.Drawing.Size(21, 23);
button3.TabIndex = 2;
button3.Text = "X";
button3.UseVisualStyleBackColor = false;
button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
//
// top right
//
button4.BackColor = System.Drawing.Color.Red;
button4.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
button4.ForeColor = System.Drawing.SystemColors.ButtonFace;
button4.Location = new System.Drawing.Point(this.Width - 21, 0);
button4.Name = "button4";
button4.Size = new System.Drawing.Size(21, 23);
button4.TabIndex = 3;
button4.Text = "X";
button4.UseVisualStyleBackColor = false;
button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Controls.Add(button4);
this.Controls.Add(button3);
this.Controls.Add(button2);
this.Controls.Add(button1);
}
}

Related

Remove Row inside TableLayoutPanel makes a layout problem

I have a WinForms application that has a TableLayoutPanel; this is the definition code:
tableLayoutPanel1 = new TableLayoutPanel();
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.AutoScroll = true;
tableLayoutPanel1.RowCount = users.Count + 1;
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.GrowStyle = TableLayoutPanelGrowStyle.FixedSize;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
foreach (String user in users)
{
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 600F));
}
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 600F));
int index = 0;
foreach (String user in users)
{
AddDockedControl(index, user);
index++;
}
AddDockedControl(index, null);
panel1.Controls.Add(tableLayoutPanel1);
private void AddDockedControl(int row, String userName)
{
AccountRowUC newUser = new AccountRowUC(this, userName, row);
newUser.BorderStyle = BorderStyle.FixedSingle;
newUser.Dock = DockStyle.Top;
tableLayoutPanel1.Controls.Add(newUser, 0, row);
}
Now, when I want to remove one of the rows, I'm using this code:
public void RemoveRowAtIndex(int index)
{
if (index >= tableLayoutPanel1.RowCount)
return;
// delete all controls of row that we want to delete
for (int i = 0; i < tableLayoutPanel1.ColumnCount; i++)
{
var control = tableLayoutPanel1.GetControlFromPosition(i, index);
tableLayoutPanel1.Controls.Remove(control);
}
// move up row controls that comes after row we want to remove
for (int i = index + 1; i < tableLayoutPanel1.RowCount; i++)
{
for (int j = 0; j < tableLayoutPanel1.ColumnCount; j++)
{
var control = tableLayoutPanel1.GetControlFromPosition(j, i);
if (control != null)
tableLayoutPanel1.SetRow(control, i - 1);
}
}
// remove last row
tableLayoutPanel1.RowStyles.RemoveAt(tableLayoutPanel1.RowCount - 1);
//tableLayoutPanel1.RowStyles.RemoveAt(index);
tableLayoutPanel1.RowCount--;
}
The problem is that when I remove a Row, a big space is left at the bottom of the table: the TableLayoutPanel won't reclaim the size of panel1.
A solution base on the layout described in the comments and this answer, previously posted:
Center multiple rows of controls in a FlowLayoutPanel
Description:
(Full code of a test Form provided at bottom of this post)
Create a new Form (here, named frmTLPTest1)
Add two Panels. One is used to host some buttons, the other one will be the Container of a TableLayoutPanel.
Set the Container panel to AutoScroll = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, set all the Anchors (Left, Top, Right, Bottom)
Inside the Container panel, drop a new TableLayoutPanel: set it to AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Dock = DockStyle.Top
Remove all Rows and Columns from the TableLayoutPanel except one of each (you cannot remove all). Set the dimensions of both to AutoSize.
Important note (also reported in the linked answer):
In the Form constructor, one of the RowStyles is removed. This is
important: the TLP will keep 2 RowStyles. One is applied to the
existing Row; the second style will be applied to the first Row you
add: to the first one only, not the others. If this style is not
removed, it will compromise the layout.
The core methods used to Add Rows to/Remove Rows from the TableLayoutPanel, make use of a FlowLayoutPanel as the TLP Row content and can also be used as Container of other controls, eventually.
TlpAddRow(TableLayoutPanel tlp, bool addRowCount) method:
Adds a new FlowLayoutPanel to the Cell of the TableLayoutPanel specified and adds a new Row if requested.
Since the Designer won't allow to remove all the Rows, the First Row (FlowLayoutPanel) must not increment the Rows count: the addRowCount argument will be set to false.
private Control TlpAddRow(TableLayoutPanel tlp, bool addRowCount)
{
var flp = new FlowLayoutPanel() {
Anchor = AnchorStyles.Top | AnchorStyles.Bottom,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
};
tlp.SuspendLayout();
if (addRowCount) tlp.RowCount += 1;
tlp.Controls.Add(flp, 0, tlp.RowCount - 1);
tlp.ResumeLayout(true);
return flp;
}
TLPRemoveRow(TableLayoutPanel tlp, Control control) method (overloaded):
Allows to remove a Row from the specified TableLayoutPanel. The Row to be removed can be derived from the Control that is used as the Row Container (a FlowLayoutPanel, here, but it could be a Panel, another TableLayoutPanel, or some other type of Container control).
The Row can also be removed by directly specifying the Row index.
private void TLPRemoveRow(TableLayoutPanel tlp, Control control)
{
int ctlRow = tlp.GetRow(control);
TLPRemoveRow(tlp, ctlRow);
}
private void TLPRemoveRow(TableLayoutPanel tlp, int row)
{
if (row < tlp.RowCount - 1) {
for (int i = row; i < tlp.RowCount - 1; i++) {
tlp.SetRow(tlp.GetControlFromPosition(0, i + 1), i);
}
}
tlp.RowCount -= 1;
}
Visual results of this Layout:
Since it's easier to understand how it work by testing rather than explaining, here's the full layout of the Form:
Test Form (frmTLPTest1):
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public partial class frmTLPTest1 : Form
{
public frmTLPTest1()
{
InitializeComponent();
tlp1.RowStyles.RemoveAt(1);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
TlpAddRow(tlp1, false);
}
Random rnd = new Random();
Size[] sizes = new Size[] { new Size(75, 75), new Size(100, 100), new Size(125, 125)};
Color[] colors = new Color[] { Color.Red, Color.LightGreen, Color.YellowGreen, Color.SteelBlue };
Control selectedObject = null;
Control selectedParent = null;
private void btnAddControl_Click(object sender, EventArgs e)
{
Size size = new Size(125, 125);
if (chkRandom.Checked) size = sizes[rnd.Next(sizes.Length)];
var pBox = new PictureBox() {
Anchor = AnchorStyles.None,
BackColor = colors[rnd.Next(colors.Length)],
MinimumSize = size,
Size = size
};
bool drawborder = false;
pBox.MouseEnter += (s, evt) => { drawborder = true; pBox.Invalidate(); };
pBox.MouseLeave += (s, evt) => { drawborder = false; pBox.Invalidate(); };
pBox.MouseDown += (s, evt) => { selectedParent = pBox.Parent;
selectedObject = pBox; pBox.Invalidate();
};
pBox.Paint += (s, evt) => {
if (drawborder) {
ControlPaint.DrawBorder(evt.Graphics, pBox.ClientRectangle,
Color.White, ButtonBorderStyle.Solid);
}
};
if (tlp1.RowCount == 0) TlpAddRow(tlp1, true);
var ctl = tlp1.GetControlFromPosition(0, tlp1.RowCount - 1);
int overallWith = 0;
if (ctl.Controls?.Count > 0) {
overallWith = ctl.Controls.OfType<Control>().Sum(c => c.Width + c.Margin.Left + c.Margin.Right);
}
overallWith += ctl.Margin.Right + ctl.Margin.Left + pBox.Size.Width + pBox.Margin.Left + pBox.Margin.Right;
if (overallWith >= tlp1.Width) {
ctl = TlpAddRow(tlp1, true);
}
ctl.Controls.Add(pBox);
}
private void btnRemoveRow_Click(object sender, EventArgs e)
{
if (selectedParent is null) return;
if (selectedParent.Controls.Count > 0) {
for (int i = 0; i == selectedParent.Controls.Count - 1; i++) {
selectedParent.Controls[i].Dispose();
}
}
TLPRemoveRow(tlp1, selectedParent);
selectedParent.Dispose();
}
private void btnRemoveControl_Click(object sender, EventArgs e)
{
if (selectedObject is null) return;
Control parent = selectedObject.Parent;
selectedObject.Dispose();
if (parent?.Controls.Count == 0) {
TLPRemoveRow(tlp1, parent);
parent.Dispose();
}
}
private Control TlpAddRow(TableLayoutPanel tlp, bool addRowCount)
{
var flp = new FlowLayoutPanel() {
Anchor = AnchorStyles.Top | AnchorStyles.Bottom,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
};
tlp.SuspendLayout();
if (addRowCount) tlp.RowCount += 1;
tlp.Controls.Add(flp, 0, tlp.RowCount - 1);
tlp.ResumeLayout(true);
return flp;
}
private void TLPRemoveRow(TableLayoutPanel tlp, Control control)
{
int ctlRow = tlp.GetRow(control);
TLPRemoveRow(tlp, ctlRow);
}
private void TLPRemoveRow(TableLayoutPanel tlp, int row)
{
if (row < tlp.RowCount - 1) {
for (int i = row; i < tlp.RowCount - 1; i++) {
tlp.SetRow(tlp.GetControlFromPosition(0, i + 1), i);
}
}
tlp.RowCount -= 1;
}
}
Test Form Designer:
partial class frmTLPTest1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.panToolbar = new System.Windows.Forms.Panel();
this.btnRemoveRow = new System.Windows.Forms.Button();
this.chkRandom = new System.Windows.Forms.CheckBox();
this.btnRemoveControl = new System.Windows.Forms.Button();
this.btnAddControl = new System.Windows.Forms.Button();
this.panBackground = new System.Windows.Forms.Panel();
this.tlp1 = new System.Windows.Forms.TableLayoutPanel();
this.panToolbar.SuspendLayout();
this.panBackground.SuspendLayout();
this.SuspendLayout();
//
// panToolbar
//
this.panToolbar.BackColor = System.Drawing.Color.DarkOliveGreen;
this.panToolbar.Controls.Add(this.btnRemoveRow);
this.panToolbar.Controls.Add(this.chkRandom);
this.panToolbar.Controls.Add(this.btnRemoveControl);
this.panToolbar.Controls.Add(this.btnAddControl);
this.panToolbar.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panToolbar.Location = new System.Drawing.Point(0, 359);
this.panToolbar.Name = "panToolbar";
this.panToolbar.Size = new System.Drawing.Size(552, 55);
this.panToolbar.TabIndex = 2;
//
// btnRemoveRow
//
this.btnRemoveRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.btnRemoveRow.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveRow.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveRow.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnRemoveRow.ForeColor = System.Drawing.Color.White;
this.btnRemoveRow.Location = new System.Drawing.Point(261, 11);
this.btnRemoveRow.Name = "btnRemoveRow";
this.btnRemoveRow.Size = new System.Drawing.Size(119, 34);
this.btnRemoveRow.TabIndex = 4;
this.btnRemoveRow.Text = "Remove Row";
this.btnRemoveRow.UseVisualStyleBackColor = false;
this.btnRemoveRow.Click += new System.EventHandler(this.btnRemoveRow_Click);
//
// chkRandom
//
this.chkRandom.AutoSize = true;
this.chkRandom.ForeColor = System.Drawing.Color.White;
this.chkRandom.Location = new System.Drawing.Point(446, 20);
this.chkRandom.Name = "chkRandom";
this.chkRandom.Size = new System.Drawing.Size(94, 19);
this.chkRandom.TabIndex = 3;
this.chkRandom.Text = "Random Size";
this.chkRandom.UseVisualStyleBackColor = true;
//
// btnRemoveControl
//
this.btnRemoveControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.btnRemoveControl.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveControl.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnRemoveControl.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnRemoveControl.ForeColor = System.Drawing.Color.White;
this.btnRemoveControl.Location = new System.Drawing.Point(136, 11);
this.btnRemoveControl.Name = "btnRemoveControl";
this.btnRemoveControl.Size = new System.Drawing.Size(119, 34);
this.btnRemoveControl.TabIndex = 2;
this.btnRemoveControl.Text = "Remove Control";
this.btnRemoveControl.UseVisualStyleBackColor = false;
this.btnRemoveControl.Click += new System.EventHandler(this.btnRemoveControl_Click);
//
// btnAddControl
//
this.btnAddControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.btnAddControl.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnAddControl.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.btnAddControl.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnAddControl.ForeColor = System.Drawing.Color.White;
this.btnAddControl.Location = new System.Drawing.Point(11, 11);
this.btnAddControl.Name = "btnAddControl";
this.btnAddControl.Size = new System.Drawing.Size(119, 34);
this.btnAddControl.TabIndex = 0;
this.btnAddControl.Text = "Add Control";
this.btnAddControl.UseVisualStyleBackColor = false;
this.btnAddControl.Click += new System.EventHandler(this.btnAddControl_Click);
//
// panBackground
//
this.panBackground.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panBackground.AutoScroll = true;
this.panBackground.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.panBackground.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.panBackground.Controls.Add(this.tlp1);
this.panBackground.Location = new System.Drawing.Point(0, 0);
this.panBackground.Name = "panBackground";
this.panBackground.Size = new System.Drawing.Size(552, 360);
this.panBackground.TabIndex = 3;
//
// tlp1
//
this.tlp1.AutoSize = true;
this.tlp1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tlp1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32)))));
this.tlp1.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
this.tlp1.ColumnCount = 1;
this.tlp1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tlp1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tlp1.Dock = System.Windows.Forms.DockStyle.Top;
this.tlp1.Location = new System.Drawing.Point(0, 0);
this.tlp1.Name = "tlp1";
this.tlp1.RowCount = 1;
this.tlp1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlp1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 1F));
this.tlp1.Size = new System.Drawing.Size(552, 2);
this.tlp1.TabIndex = 4;
//
// frmTLPTest1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(552, 414);
this.Controls.Add(this.panBackground);
this.Controls.Add(this.panToolbar);
this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "frmTLPTest1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "frmTLPTest1";
this.Load += new System.EventHandler(this.SOfrmTest1_Load);
this.panToolbar.ResumeLayout(false);
this.panToolbar.PerformLayout();
this.panBackground.ResumeLayout(false);
this.panBackground.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.Panel panToolbar;
private System.Windows.Forms.Button btnAddControl;
private System.Windows.Forms.Button btnRemoveControl;
private System.Windows.Forms.CheckBox chkRandom;
private System.Windows.Forms.Panel panBackground;
private System.Windows.Forms.TableLayoutPanel tlp1;
private System.Windows.Forms.Button btnRemoveRow;
}

c# bringtofront() and senttoback() not working

I am new to c# and I'm trying to understand z-index concept. So far I have a simple form created using ConsoleApplication project in visual studio. There are 3 cs files. Here's the code:
In Algorithm.cs (inherited from UI.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
public class Algorithm : UI
{
private Timer refresh = new Timer();
//Ball settings
private const int offset = 25;
private const int rate = 200;
private int ball_bounding_box_x_coord;
private int ball_bounding_box_y_coord;
private int x;
private int y;
private const int width = 50;
private const int height = 50;
Brush brush = new SolidBrush(Color.Blue);
public bool isStartClicked = false;
Button test = new Button();
public Algorithm()
{
test.Text = "test";
test.Location = new Point(0, 800);
test.Size = new Size(100, 50);
test.TabIndex = 0;
bottom.Controls.Add(test);
test.BringToFront();
ball_bounding_box_x_coord = middle.Size.Width / 2 - width / 2;
ball_bounding_box_y_coord = middle.Size.Height / 2 - height / 2;
middle.Paint += new PaintEventHandler(Draw);
start.Click += new EventHandler(Start);
}
private void Calculate()
{
Graphics g = middle.CreateGraphics();
//g.FillEllipse(brush, )
}
private void Draw(object sender, PaintEventArgs e)
{
e.Graphics.FillEllipse(brush, ball_bounding_box_x_coord , ball_bounding_box_y_coord , width, height);
}
public void Start(object sender, EventArgs e)
{
MessageBox.Show("Button clicked");
}
}
In UI.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
public class UI : Form
{
//Window settings
private const int WINDOW_WIDTH = 1600;
private const int WINDOW_HEIGHT = 900;
private Panel top = new Panel();
public Panel middle = new Panel();
public Panel bottom = new Panel();
private Label title = new Label();
//Text box for degree input
private Label degree_input_label = new Label();
private TextBox degree_input = new TextBox();
public double input;
//Label to display x and y coordinates of the ball
public Label ball_x_coord = new Label();
public Label ball_y_coord = new Label();
//Buttons
public Button start = new Button();
private Button quit = new Button();
public UI()
{
//total height of 3 areas != window_height????????????????
//Setup window form
this.Width = WINDOW_WIDTH;
this.Height = WINDOW_HEIGHT;
this.Text = "Project 2";
//Add a badass title
title.Text = "Designed by Me";
title.AutoSize = true;
title.Location = new Point(600, 20);
title.Font = new Font(title.Font.Name, 24, FontStyle.Bold);
title.BackColor = Color.Red;
Controls.Add(title);
top.Location = new Point(0, 0);
top.Size = new Size(WINDOW_WIDTH, 80);
top.BackColor = Color.Red;
middle.Location = new Point(0, top.Location.Y + top.Size.Height);
middle.Size = new Size(WINDOW_WIDTH, 680);
middle.BackColor = Color.Cyan;
bottom.Location = new Point(0, top.Location.Y + top.Size.Height + middle.Size.Height);
bottom.Size = new Size(WINDOW_WIDTH, WINDOW_HEIGHT - top.Height - middle.Height);
bottom.BackColor = Color.Green;
degree_input_label.Text = "Enter a degree:";
degree_input_label.Location = new Point(100, bottom.Location.Y + 20);
degree_input_label.AutoSize = true;
Controls.Add(degree_input_label);
degree_input.Size = new Size(50, 50);
degree_input.Location = new Point(200, bottom.Location.Y + 20);
degree_input.Leave += new EventHandler(TextChange);
degree_input.TabIndex = 2;
Controls.Add(degree_input);
ball_x_coord.Text = "Ball X Coord";
ball_x_coord.Location = new Point(400, bottom.Location.Y + 20);
ball_x_coord.AutoSize = true;
Controls.Add(ball_x_coord);
ball_y_coord.Text = "Ball y coord";
ball_y_coord.Location = new Point(500, bottom.Location.Y + 20);
ball_y_coord.AutoSize = true;
Controls.Add(ball_y_coord);
start.Text = "Start";
start.Location = new Point(1100, bottom.Location.Y + 20);
start.Size = new Size(100, 50);
start.TabIndex = 1;
Controls.Add(start);
quit.Text = "Quit";
quit.Location = new Point(1400, bottom.Location.Y + 20);
quit.Size = new Size(100, 50);
quit.Click += new EventHandler(Quit);
Controls.Add(quit);
//ADD BACKGROUND CONTROLS
Controls.Add(top);
Controls.Add(middle);
Controls.Add(bottom);
}//end constructor
private void TextChange(object sender, EventArgs e)
{
if(degree_input.TextLength <= 0)
{
degree_input.Text = "0";
MessageBox.Show("Please enter a degree");
degree_input.Focus();
}else
{
input = double.Parse(degree_input.Text);
//MessageBox.Show(input.ToString());
}
}
void Quit(object sender, EventArgs e)
{
Application.Exit();
}
}
In Main.cs:
class Program
{
static void Main(string[] args)
{
Algorithm al = new Algorithm();
UI a = new UI();
//Application.Run(a);
Application.Run(al);
}
}
The problem I'm having is that the test button is not visible. If i remove the bottom panel and add the test button directly on the form then it is visible. Why doesn't it appear on the bottom panel even after I used bringtofront() ?
Why doesn't it appear on the bottom panel even after I used bringtofront() ?
Because you've placed it outside the visual boundary of the panel:
test.Location = new Point(0, 800);
That sets the position of the button to a horizontal offset of 0 and a vertical offset of 800. The bottom panel is only 140 pixels high, so 800 is well below the bottom of the visible area.
It's not really clear what you meant to do. Given that the window width is 1600 pixels and 800 is half that, maybe you just transposed the X and Y coordinates and meant this instead:
test.Location = new Point(800, 0);
That would place the button in the middle of the panel, aligned to the top.
Other than that, I can't imagine why if you wanted the button to be visible, you would hard-code a location for it that is not in a visible area.

Custom MessageBox with custom-defined Buttons [duplicate]

I am doing C# application, and I want to change the style of a message box. Is it possible or not?
Example: change button style, fore color, etc.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is the code needed to create your own message box:
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;
namespace MyStuff
{
public class MyLabel : Label
{
public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Label l = new Label();
l.Text = Text;
l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
l.AutoSize = true;
return l;
}
}
public class MyButton : Button
{
public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Button b = new Button();
b.Text = Text;
b.Width = Width;
b.Height = Height;
b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
return b;
}
}
public class MyImage : PictureBox
{
public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
{
PictureBox i = new PictureBox();
if (ImagePath != null)
{
i.BackgroundImageLayout = ImageLayout.Zoom;
i.Location = new Point(9, 9);
i.Margin = new Padding(3, 3, 2, 3);
i.Size = new Size(Width, Height);
i.TabStop = false;
i.Visible = true;
i.BackgroundImage = Image.FromFile(ImagePath);
}
else
{
i.Visible = true;
i.Size = new Size(0, 0);
}
return i;
}
}
public partial class MyMessageBox : Form
{
private MyMessageBox()
{
this.panText = new FlowLayoutPanel();
this.panButtons = new FlowLayoutPanel();
this.SuspendLayout();
//
// panText
//
this.panText.Parent = this;
this.panText.AutoScroll = true;
this.panText.AutoSize = true;
this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
//this.panText.Location = new Point(90, 90);
this.panText.Margin = new Padding(0);
this.panText.MaximumSize = new Size(500, 300);
this.panText.MinimumSize = new Size(108, 50);
this.panText.Size = new Size(108, 50);
//
// panButtons
//
this.panButtons.AutoSize = true;
this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.panButtons.FlowDirection = FlowDirection.RightToLeft;
this.panButtons.Location = new Point(89, 89);
this.panButtons.Margin = new Padding(0);
this.panButtons.MaximumSize = new Size(580, 150);
this.panButtons.MinimumSize = new Size(108, 0);
this.panButtons.Size = new Size(108, 35);
//
// MyMessageBox
//
this.AutoScaleDimensions = new SizeF(8F, 19F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(206, 133);
this.Controls.Add(this.panButtons);
this.Controls.Add(this.panText);
this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Margin = new Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new Size(168, 132);
this.Name = "MyMessageBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(Label);
return Show(Labels, Title, Buttons, Image);
}
public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(MyLabel.Set(Label));
return Show(Labels, Title, Buttons, Image);
}
public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
if (Labels == null) Labels = new List<Label>();
if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
if (Buttons == null) Buttons = new List<Button>();
if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
List<Button> buttons = new List<Button>(Buttons);
buttons.Reverse();
int ImageWidth = 0;
int ImageHeight = 0;
int LabelWidth = 0;
int LabelHeight = 0;
int ButtonWidth = 0;
int ButtonHeight = 0;
int TotalWidth = 0;
int TotalHeight = 0;
MyMessageBox mb = new MyMessageBox();
mb.Text = Title;
//Image
if (Image != null)
{
mb.Controls.Add(Image);
Image.MaximumSize = new Size(150, 300);
ImageWidth = Image.Width + Image.Margin.Horizontal;
ImageHeight = Image.Height + Image.Margin.Vertical;
}
//Labels
List<int> il = new List<int>();
mb.panText.Location = new Point(9 + ImageWidth, 9);
foreach (Label l in Labels)
{
mb.panText.Controls.Add(l);
l.Location = new Point(200, 50);
l.MaximumSize = new Size(480, 2000);
il.Add(l.Width);
}
int mw = Labels.Max(x => x.Width);
il.ToString();
Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
//Buttons
foreach (Button b in buttons)
{
mb.panButtons.Controls.Add(b);
b.Location = new Point(3, 3);
b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
b.Click += new EventHandler(mb.Button_Click);
}
ButtonWidth = mb.panButtons.Width;
ButtonHeight = mb.panButtons.Height;
//Set Widths
if (ButtonWidth > ImageWidth + LabelWidth)
{
Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
}
TotalWidth = ImageWidth + LabelWidth;
//Set Height
TotalHeight = LabelHeight + ButtonHeight;
mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);
mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
mb.ShowDialog();
return mb.Result;
}
private FlowLayoutPanel panText;
private FlowLayoutPanel panButtons;
private int ScrollBarWidth(List<Label> Labels)
{
return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
}
private void Button_Click(object sender, EventArgs e)
{
Result = ((Button)sender).Text;
Close();
}
private string Result = "";
}
}

How do I properly add a custom control to another custom control so that it will render in a form?

I've created a custom control in C#. A highly-simplified version of it is shown below:
class WellControl : Control
{
Pen circlePen = new Pen(Color.Black, 5);
Brush wellShader = new SolidBrush(Color.BlueViolet);
Brush wellBlanker = new SolidBrush(Color.LightGray);
public WellControl(int wellNum)
{
InitializeComponent();
}
private void DrawWell()
{
using (Graphics well = this.CreateGraphics())
{
this.Size = new Size(WellSize, WellSize);
if (this.selected)
{
well.FillEllipse(wellShader, ellipseCoords);
}
else
{
well.FillEllipse(wellBlanker, ellipseCoords);
}
well.DrawEllipse(circlePen, ellipseCoords);
using (Font wellNumberFont = new Font("Arial", 14, FontStyle.Bold))
{
well.DrawString(WellNum.ToString(), wellNumberFont, Brushes.Black, new Point(13, 13));
}
}
}
private void WellPaintEventHandler(object sender, EventArgs e)
{
DrawWell();
}
private void InitializeComponent()
{
this.SuspendLayout();
this.Paint += new System.Windows.Forms.PaintEventHandler(WellPaintEventHandler);
this.ResumeLayout();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
//dispose all the custom stuff
}
}
}
When I add it to a form, it renders properly (again, simplified example):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
for (int i = 0; i < 4; i++)
{
WellControl newWell = new WellControl(i + 1);
newWell.Location = new Point(15, 50 * i);
newWell.Size = new System.Drawing.Size(45, 45);
this.Controls.Add(newWell);
}
}
}
I have another custom control, "Plate", which is intended to hold many "Wells". The code intended to draw the wells evenly across the plate probably sucks right now but I'm just trying to see something:
class PlateControl : Control
{
Pen blackPen = new Pen(Color.Black, 3);
public PlateControl()
{
this.Size = new Size(600, 800);
List<WellControl> plateWells = new List<WellControl>();
int column = 1;
int row = 0;
for (int i = 1; i <= 96; i++)
{
column = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(i / 8)));
row = i % 8;
WellControl newWell = new WellControl(i + 1);
newWell.Name = "wellControl" + i;
newWell.Location = new Point(column * 50, row * 50);
newWell.Size = new System.Drawing.Size(45, 45);
newWell.TabIndex = i;
newWell.WellSize = 45;
plateWells.Add(newWell);
newWell.Visible = true;
}
InitializeComponent();
}
private void InitializeComponent()
{
this.SuspendLayout();
this.Paint += new System.Windows.Forms.PaintEventHandler(PlatePaintEventHandler);
this.ResumeLayout();
}
private void DrawPlate()
{
using (Graphics plate = this.CreateGraphics())
{
Point topLeft = new Point(0, 0);
Point topRight = new Point(600, 0);
Point bottomRight = new Point(600, 400);
Point bottomLeft = new Point(0, 400);
plate.DrawLine(blackPen, topLeft, topRight);
plate.DrawLine(blackPen, topRight, bottomRight);
plate.DrawLine(blackPen, bottomRight, bottomLeft);
plate.DrawLine(blackPen, bottomLeft, topLeft);
}
}
private void PlatePaintEventHandler(object sender, EventArgs e)
{
DrawPlate();
}
}
If I add this control to a Winform using this.Controls.Add(new PlateControl()), the rectangle renders, but not the WellControls I added to the PlateControl in the constructor loop. What am I doing incorrectly?
You need to add List of WallControl to plate control.
public PlateControl()
{
this.Size = new Size(600, 800);
List<WellControl> plateWells = new List<WellControl>();
int column = 1;
int row = 0;
for (int i = 1; i <= 96; i++)
{
column = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(i / 8)));
row = i % 8;
WellControl newWell = new WellControl(i + 1);
newWell.Name = "wellControl" + i;
newWell.Location = new Point(column * 50, row * 50);
newWell.Size = new System.Drawing.Size(45, 45);
newWell.TabIndex = i;
newWell.WellSize = 45;
plateWells.Add(newWell);
newWell.Visible = true;
}
this.Controls.AddRange(plateWells.ToArray());
InitializeComponent();
}

Require help in C# Need to implement moving picture box

I need a help on this,
There are 3 picture boxes, red should grow its Width to left, green should grow its height to top blue's width to right
also if one reaches the top border / any text boxes it should give an error / stop execution
I need to add more picture boxes in future and if two of them collides it should give an error / stop execution. I have managed to code them to go up, however unable to get other functions working. Please some one help me with this.
OR
https://www.box.com/s/d0d302c6c266f52e0abf
Thank you.
RR
My code below,
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.Threading;
namespace ThreadwithmovingPicbxmoving
{
public partial class Form1 : Form
{
Thread t1;
Thread t2;
Thread t3;
delegate void CTMethod(int val);
delegate void CTFinish(string t);
Queue<string> order = new Queue<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int r = int.Parse(textBox1.Text);
int y = int.Parse(textBox2.Text);
int g = int.Parse(textBox3.Text);
t1 = new Thread(new ParameterizedThreadStart(loopred));
t2 = new Thread(new ParameterizedThreadStart(loopyel));
t3 = new Thread(new ParameterizedThreadStart(loopGree));
t1.Start(r);
t2.Start(y);
t3.Start(g);
}
private void updateRed(int val)
{
pictureBox1.Height = val;
pictureBox1.Refresh();
}
private void updateyell(int val)
{
pictureBox2.Height = val;
pictureBox2.Refresh();
}
private void updategree(int val)
{
pictureBox3.Height = val;
pictureBox3.Refresh();
}
private void loopred(object o)
{
int c = (int)o;
CTMethod ctred = new CTMethod(updateRed);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
this.Invoke(ctred, i);
Thread.Sleep(20);
}
}
else
{
MessageBox.Show("Enter a value less than 500 for Red Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Red");
}
private void loopyel(object o)
{
int c = (int)o;
CTMethod ctyell = new CTMethod(updateyell);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
this.Invoke(ctyell, i);
Thread.Sleep(20);
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Yellow Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Yell");
}
private void loopGree(object o)
{
int c = (int)o;
CTMethod ctgree = new CTMethod(updategree);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
this.Invoke(ctgree, i);
Thread.Sleep(20);
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Green Box!!!");
}
CTFinish CTfin = new CTFinish(Threadfinish);
this.Invoke(CTfin, "Green");
}
private void Threadfinish(string t)
{
order.Enqueue(t);
if (order.Count == 3)
{
MessageBox.Show("Threads finished in this order: \n" + "1." + order.Dequeue() + "\n" + "2." + order.Dequeue()
+ "\n" + "3." + order.Dequeue() + "\n", "finished");
}
}
}
}
Try It. Its All Fine with three PictureBoxes
Create New Widows Application with name help and then replace Form1.cs code with Following
Run It. It also includes values from TextBoxes
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
namespace help
{
public partial class Form1 : Form
{
Thread t1;
Thread t2;
Thread t3;
delegate void CTMethod(int val);
delegate void CTFinish(string t);
Queue<string> order = new Queue<string>();
#region Variables of Designer File
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Button button1;
#endregion
public Form1()
{
#region Designer Code I have Cut and Pasted Here
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
this.SuspendLayout();
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.pictureBox3);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.pictureBox1);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Red;
this.pictureBox1.Location = new System.Drawing.Point(161, 268);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(100, 50);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.BackColor = System.Drawing.Color.Green;
this.pictureBox2.Location = new System.Drawing.Point(383, 268);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(100, 50);
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// pictureBox3
//
this.pictureBox3.BackColor = System.Drawing.Color.Blue;
this.pictureBox3.Location = new System.Drawing.Point(605, 268);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(100, 50);
this.pictureBox3.TabIndex = 2;
this.pictureBox3.TabStop = false;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(161, 26);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 3;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(383, 25);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 4;
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(605, 26);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(100, 20);
this.textBox3.TabIndex = 5;
//
// button1
//
this.button1.Location = new System.Drawing.Point(37, 23);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 6;
this.button1.Text = "Go";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
this.PerformLayout();
#endregion
InitializeComponent();
textBox1.Text = "490";
textBox2.Text = "490";
textBox3.Text = "490";
textBox1.Leave += new EventHandler(textBox1_Leave);
textBox2.Leave += new EventHandler(textBox2_Leave);
textBox3.Leave += new EventHandler(textBox3_Leave);
}
// To input Only Valid int values in TextBoxes
#region TextBoxes Input Validation
int t1Val = 490;
int t2Val = 490;
int t3Val = 490;
void textBox1_Leave(object sender, EventArgs e)
{
try
{
int t1Val = Convert.ToInt32(textBox1.Text);
}
catch
{
textBox1.Focus();
}
}
void textBox2_Leave(object sender, EventArgs e)
{
try
{
int t2Val = Convert.ToInt32(textBox2.Text);
}
catch
{
textBox2.Focus();
}
}
void textBox3_Leave(object sender, EventArgs e)
{
try
{
int t3Val = Convert.ToInt32(textBox3.Text);
}
catch
{
textBox3.Focus();
}
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
int r = t1Val;
int y = t2Val;
int g = t3Val;
t1 = new Thread(new ParameterizedThreadStart(loopRed));
t2 = new Thread(new ParameterizedThreadStart(loopGreen));
t3 = new Thread(new ParameterizedThreadStart(loopBlue));
// It will avoid proble if you exit app when threads are working
t1.IsBackground = true;
t2.IsBackground = true;
t3.IsBackground = true;
t1.Start(r);
t2.Start(y);
t3.Start(g);
}
private void updateRed(int val)
{
pictureBox1.Width++;
pictureBox1.Left--;
pictureBox1.Refresh();
}
private void updateGreen(int val)
{
pictureBox2.Height++;
pictureBox2.Top--;
pictureBox2.Refresh();
}
private void updateBlue(int val)
{
pictureBox3.Width++;
pictureBox3.Refresh();
}
private void loopRed(object o)
{
int c = (int)o;
CTMethod ctRed = new CTMethod(updateRed);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
if (pictureBox1.Left > 0)
{
this.Invoke(ctRed, i);
Thread.Sleep(20);
}
}
}
else
{
MessageBox.Show("Enter a value less than 500 for Red Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Red");
}
private void loopGreen(object o)
{
int c = (int)o;
CTMethod ctGreen = new CTMethod(updateGreen);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
if (pictureBox2.Top > 0 && pictureBox2.Top != textBox2.Top + textBox2.Height)
{
this.Invoke(ctGreen, i);
Thread.Sleep(20);
}
else
break;
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Green Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Green");
}
private void loopBlue(object o)
{
int c = (int)o;
CTMethod ctBlue = new CTMethod(updateBlue);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
if (pictureBox3.Left + pictureBox3.Width < this.Width)
{
this.Invoke(ctBlue, i);
Thread.Sleep(20);
}
else
break;
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Blue Box!!!");
}
CTFinish CTfin = new CTFinish(Threadfinish);
this.Invoke(CTfin, "Blue");
}
private void Threadfinish(string t)
{
order.Enqueue(t);
if (order.Count == 3)
{
MessageBox.Show("Threads finished in this order: \n" + "1." + order.Dequeue() + "\n" + "2." + order.Dequeue()
+ "\n" + "3." + order.Dequeue() + "\n", "finished");
}
}
}
}

Categories