How to identify dynamically created panels in c#? - c#

I am doing a Windows Form Application in c# in which I create a panel for every click i do in "Panel_Inside".
But my problem is when I have to select one especific panel. I do not know how can I identify each panel.
Also I'm having problems when Dragging and Dropping for the same reason.
public void Coloco_Figura(string figura, int Punto_X, int Punto_Y)
{
panel_foto = new Panel();
panel_foto.BackColor = Color.Transparent; //saco fondo
panel_foto.BackgroundImage = Image.FromFile(figura); //asigno imagen al panel
panel_foto.BackgroundImageLayout = ImageLayout.Stretch;
panel_foto.Size = new Size(45, 45);
panel_foto.Location = new Point(Punto_X - 10, Punto_Y - 10);
panel_foto.BringToFront();
panel1.SendToBack();
panel_inside.Controls.Add(panel_foto);
dame_x = Punto_X;
this.panel_foto.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MouseDown);
this.panel_foto.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MouseUp);
this.panel_foto.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MouseMove);
}
here are mouse events
private void MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
# region Borrar Notas
if (Estado_Borro == true)
{
foreach (Panel p in panel_inside.Controls)
{
if (p is Panel)
{
panel_inside.Controls.Remove(p);
if (panel_inside.Controls.Count == 0)
{
listanotas.Clear();
}
else
{
for (int i = 0; i < listanotas.Count; i++)
{
Notas nota = listanotas[i];
if (nota.posX == dame_x)
{
listanotas.Remove(nota);
}
}
}
}
}
Estado_Borro = false;
}
if (e.Button == MouseButtons.Left)
{
drag = true;
x = e.X;
y = e.Y;
}
}
public void MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
drag = false;
}
public void MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (drag)
{
this.panel_foto.Location = new Point(Cursor.Position.X-this.Left, Cursor.Position.Y-this.Top);
}

To identify each panel, first you must set the Name or Tag property:
panel_foto.Name = "panel_foto1";
Then in your event handler,do something like this:
Panel p=(Panel)sender;
if (p.Name == "panel_foto1")
{
//Do your staff
}

Related

Moving Pictureboxes from left to right

I have 4 pictureBoxes. I need they move until hit right side and then move to left side and again. But after 1st picturebox hit left side other move closer to him. How fix it ??
link on video with problem
int changePositionX;
bool change = true;
private void timer1_Tick(object sender, EventArgs e)
{
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag != null && x.Tag.ToString() == "enemy")
{
if (x.Location.X < 750 && change == true)
{
changePositionX = x.Location.X + 50;
x.Location = new Point(changePositionX, x.Location.Y);
}
else
{
change = false;
}
if(x.Location.X >= 100 && change == false)
{
changePositionX = x.Location.X - 50;
x.Location = new Point(changePositionX, x.Location.Y);
}
else
{
change = true;
}
}
}
}
Try it like this instead:
private int jumpDistance = 50;
private bool goingRight = true;
private List<PictureBox> PBs = new List<PictureBox>();
private void Form1_Load(object sender, EventArgs e)
{
foreach (PictureBox pb in this.Controls.OfType<PictureBox>())
{
if (pb.Tag != null && pb.Tag.ToString() == "enemy")
{
PBs.Add(pb);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (goingRight)
{
if (PBs.Any(pb => pb.Location.X >= 750))
{
goingRight = !goingRight;
}
}
else
{
if (PBs.Any(pb => pb.Location.X < 100))
{
goingRight = !goingRight; ;
}
}
foreach (PictureBox pb in PBs)
{
if (goingRight)
{
pb.Location = new Point(pb.Location.X + jumpDistance, pb.Location.Y);
}
else // going left
{
pb.Location = new Point(pb.Location.X - jumpDistance, pb.Location.Y);
}
}
}
Here's my code doing its thing with four PictureBoxes:

Control flicker while dragging in run time

Stack Overflow users. In a C# VS 2010 Windows Form project I have a problem regarding control flicker when dragging a user created control around on a tab page during run time. I used the following code:
private void control_MouseMove(object sender, MouseEventArgs e)
{
if (isDragged)
{
Point newPoint = ((Control)sender).PointToScreen(new Point(e.X,
e.Y));
newPoint.Offset(ptOffset);
((Control)sender).Location = newPoint;
((Control)sender).Refresh();
}
}
private void control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragged = true;
Point ptStartPosition = ((Control)sender).PointToScreen(new
Point(e.X, e.Y));
ptOffset = new Point();
ptOffset.X = ((Control)sender).Location.X - ptStartPosition.X;
ptOffset.Y = ((Control)sender).Location.Y - ptStartPosition.Y;
}
else
{
isDragged = false;
}
}
private void control_MouseUp(object sender, MouseEventArgs e)
{
((Control)sender).Refresh();
isDragged = false;
}
private void createButton_PB_Click(object sender, EventArgs e)
{
int ctrlExists = 0;
string btnName = btnName_TB.Text;
foreach (Button button in tabControl1.SelectedTab.Controls)
{
if (button.Text == btnName)
{
ctrlExists = 1;
}
}
if (btnName_TB.Text != "" && ctrlExists == 0)
{
Button newButton = new Button();
newButton.Name = btnName.Replace(" ", String.Empty);
newButton.Name += "u";
newButton.Text = btnName;
tabControl1.SelectedTab.Controls.Add(newButton);
newButton.Left = 10;
newButton.Top = 420;
lastBtnClicked = newButton;
}
SetupClickEvents(tabControl1.SelectedTab);
}
So, the problem is that I can add a button and drag it around in run time. But, when I add another Button and drag it around...after I've done that, and go back to trying to drag the first button, that button flickers and acts as if it is trying to move all over the place. Sometimes it disappears. I feel like this has something to do with the fact that the controls are inside a tab page. Perhaps I am not properly calculating the "newPoint" variable. Any ideas guys?
Ok, so I found a few fundamental flaws related to the button creation and the events that were being added at the time of creation. I made some considerable changes and the issue seems to have gone away. Following is the updated code.
private void control_MouseMove(object sender, MouseEventArgs e)
{
if (isDragged)
{
Point newPoint = ((Control)sender).PointToScreen(new Point(e.X,
e.Y));
newPoint.Offset(ptOffset);
((Control)sender).Location = newPoint;
((Control)sender).Refresh();
}
}
private void control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && checkBox1.Checked)
{
isDragged = true;
((Control)sender).MouseMove += new
MouseEventHandler(control_MouseMove);
Point ptStartPosition = ((Control)sender).PointToScreen(new
Point(e.X, e.Y));
ptOffset = new Point();
ptOffset.X = ((Control)sender).Location.X - ptStartPosition.X;
ptOffset.Y = ((Control)sender).Location.Y - ptStartPosition.Y;
}
else
{
isDragged = false;
}
}
private void control_MouseUp(object sender, MouseEventArgs e)
{
((Control)sender).MouseMove -= control_MouseMove;
((Control)sender).Refresh();
isDragged = false;
}
private void SetupClickEvents(Control control)
{
control.Click += new EventHandler(StoreLastClick);
control.MouseDown += new MouseEventHandler(control_MouseDown);
//control.MouseMove += new MouseEventHandler(control_MouseMove);
control.MouseUp += new MouseEventHandler(control_MouseUp);
}
private void createButton_PB_Click(object sender, EventArgs e)
{
ctrlExists = 0;
string btnName = btnName_TB.Text;
foreach (Button button in tabControl1.SelectedTab.Controls)
{
if (button.Name == btnName)
{
ctrlExists = 1;
}
}
if (btnName_TB.Text != "" && ctrlExists == 0)
{
Button newButton = new Button();
newButton.Name = btnName.Replace(" ", String.Empty);
newButton.Text = btnName;
tabControl1.SelectedTab.Controls.Add(newButton);
newButton.Left = 10;
newButton.Top = 420;
SetupClickEvents(newButton);
}
}
private void deleteButton_PB_Click(object sender, EventArgs e)
{
ctrlExists = 0;
if (lastCtrlClicked != null)
{
string btnName = lastCtrlClicked.Name;
foreach (Button button in tabControl1.SelectedTab.Controls)
{
if (button.Name == btnName)
{
ctrlExists = 1;
}
}
}
if (ctrlExists == 1 && lastCtrlClicked != null)
{
tabControl1.SelectedTab.Controls.Remove(lastCtrlClicked);
lastCtrlClicked.Dispose();
ctrlExists = 0;
}
lastCtrlClicked = null;
}

C# gui the mouse move event cannot select a list element?

This title might be a bit not precise, what I am really having is this issue. I plotted a few lines, each is stored in a list, as line path. Then I use IsOutlineVisible to measure if the mouse location is on any of them, if mouse is on one, draw it as a different color or do something.
But it only recognize the last line in the list.
I would attach only the relevant part of the code, but this I really am not too sure where is the problem, so here is the entire code
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<GraphicsPath> LineGroup = new List<GraphicsPath>();
Point Latest{get;set;}
List<Point> pointtemp = new List<Point>();
bool startdrawline = true;
bool selectlinestate = false;
int selectedline;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
// Save the mouse coordinates
Latest = new Point(e.X, e.Y);
// Force to invalidate the form client area and immediately redraw itself.
Refresh();
if (startdrawline == false)
{
selectedline = Linesel(LineGroup);
}
}
protected override void OnPaint(PaintEventArgs e)
{
this.DoubleBuffered = true;
var g = e.Graphics;
base.OnPaint(e);
Pen penb = new Pen(Color.Navy,2);
Pen peny=new Pen(Color.Yellow,2);
for (int i = 0; i < LineGroup.Count; i++)
{
if (i == selectedline)
{
g.DrawPath(peny, LineGroup[i]);
}
else
{
g.DrawPath(penb, LineGroup[i]);
}
}
penb.Dispose();
peny.Dispose();
if (startdrawline == true)
{
GraphicsPath tracepath = new GraphicsPath();
Pen penr = new Pen(Color.Red,2);
if (pointtemp.Count == 1)
{
tracepath.AddLine(pointtemp[0], Latest);
}
else if (pointtemp.Count > 1)
{
tracepath.AddLine(pointtemp[1], Latest);
}
g.DrawPath(penr, tracepath);
penr.Dispose();
}
Refresh();
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
startdrawline = false;
pointtemp.Clear();
}
else if (e.Button == MouseButtons.Left )
{
startdrawline = true;
Latest = new Point(e.X, e.Y);
if (pointtemp.Count < 2)
{
pointtemp.Add(Latest);
}
else
{
pointtemp[0] = pointtemp[1];
pointtemp[1] = Latest;
}
if (pointtemp.Count == 2)
{
LineP2P(pointtemp);
}
Refresh();
}
}
private void LineP2P(List<Point> pointtemp){
GraphicsPath path = new GraphicsPath();
path.AddLine(pointtemp[0], pointtemp[1]);
LineGroup.Add(path);
}
private int Linesel(List<GraphicsPath> LineGroup)
{
int selectedline=-1;
for (int i =0; i < LineGroup.Count; i++)
{
Pen pen = new Pen(Color.Navy, 8);
if (LineGroup[i].IsOutlineVisible(Latest, pen))
{
selectedline = i;
}
else if (!LineGroup[i].IsOutlineVisible(Latest, pen))
{
selectedline = -1;
}
label1.Text = selectedline.ToString();
}
return selectedline;
}
}
}
When I put the test label.Text under the if
if (LineGroup[i].IsOutlineVisible(Latest, pen))
{
selectedline = i;
label1.Text = selectedline.ToString();
}
it actually works (varies with lines)
Can anyone identify the cause? Lot of Thanks.
The problem is that you did not break out of the loop once you find your line
lets say the line your mouse is on is at index 0. You are going to call
selectedline = 0 on the first iteration
and then on the second iteration
if (LineGroup[1].IsOutlineVisible(Latest, pen))
would be false so
selectedline = -1;
Thus unless you are mouse is on the last line selectedline will always be -1
What you want to do is probably
selectedline = -1;
for (int i =0; i < LineGroup.Count; i++)
{
Pen pen = new Pen(Color.Navy, 8);
if (LineGroup[i].IsOutlineVisible(Latest, pen))
{
selectedline = i;
break;
}
}
label1.Text = selectedline.ToString();
return selectedline;

C# Drawing Lines with TextBox

I have an application where I can add a textBox on the screen and move it.
When I add more than two textBox, I double-click on top of two textbox and a line connects both.
My question is: How to make the line move along with the textBox?
code below:
public partial class principal : Form
{
int posMouseFormX, posMouseFormY;
int posMouseTXT_X, posMouseTXT_Y;
int posActTXT_X, posActTXT_Y;
bool txtPressionado = false;
int qntClick;
Pen myPen = new Pen(System.Drawing.Color.DarkGreen, 1);
Graphics Tela;
List<TextBox> listaNós = new List<TextBox>();
List<Point> origem = new List<Point>();
List<Point> destino = new List<Point>();
Point ponto1, ponto2;
ContextMenuStrip menu;
public principal()
{
InitializeComponent();
menu = new ContextMenuStrip();
menu.Items.Add("Remover");
menu.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuStrip1_ItemClicked);
}
//TextBox event when the mouse moves over the TXT
private void txtMover_MouseMove(object sender, MouseEventArgs e)
{
TextBox textBox = sender as TextBox;
posMouseFormX = textBox.Location.X + e.Location.X;
posMouseFormY = textBox.Location.Y + e.Location.Y;
if (txtPressionado == true) moverTxt(textBox);
}
//Retrieve the X and Y coordinates where clicked within the component.
private void txtMover_MouseDown(object sender, MouseEventArgs e)
{
posMouseTXT_X = e.Location.X;
posMouseTXT_Y = e.Location.Y;
txtPressionado = true;
}
private void txtMover_MouseUp(object sender, MouseEventArgs e)
{
txtPressionado = false;
}
private void moverTxt(TextBox a)
{
a.Location = new System.Drawing.Point(posMouseFormX - posMouseTXT_X, posMouseFormY - posMouseTXT_Y);
posActTXT_X = a.Location.X;
posActTXT_Y = a.Location.Y;
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
}
//insert new TextBox
private void sb_Inserir_No_Click(object sender, EventArgs e)
{
TextBox noFilho = new TextBox();
noFilho = new System.Windows.Forms.TextBox();
noFilho.Location = new System.Drawing.Point(379, 284);
noFilho.Size = new System.Drawing.Size(100, 30);
noFilho.TabIndex = 20;
noFilho.Text = "";
noFilho.BackColor = Color.White;
posActTXT_X = noFilho.Location.X;
posActTXT_Y = noFilho.Location.Y;
this.Controls.Add(noFilho);
noFilho.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
noFilho.DoubleClick += new System.EventHandler(this.textBox1_Click);
noFilho.MouseUp += new System.Windows.Forms.MouseEventHandler(txtMover_MouseUp);
noFilho.MouseDown += new System.Windows.Forms.MouseEventHandler(txtMover_MouseDown);
noFilho.MouseMove += new System.Windows.Forms.MouseEventHandler(txtMover_MouseMove);
noFilho.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
noFilho.ContextMenuStrip = menu;
}
//event to resize the txt on the screen as the content.
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox textBox1 = sender as TextBox;
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width + 10;
textBox1.Height = size.Height;
}
//Event to control the connection between two give us when double click on the textbox
private void textBox1_Click(object sender, EventArgs e)
{
TextBox textBox1 = sender as TextBox;
int meio = textBox1.Size.Width / 2;
Tela = CreateGraphics();
qntClick = qntClick + 1;
if (this.qntClick == 1)
{
origem.Add(ponto1);
ponto1 = new Point(textBox1.Location.X + meio, textBox1.Location.Y);
}
if (this.qntClick == 2)
{
qntClick = 0;
destino.Add(ponto2);
ponto2 = new Point(textBox1.Location.X + meio, textBox1.Location.Y);
DesenhaSeta(Tela, ponto1, ponto2);
}
}
//draw arrow between two TXT
void DesenhaSeta(Graphics Tela, Point x, Point y)
{
myPen.StartCap = LineCap.Triangle;
myPen.EndCap = LineCap.ArrowAnchor;
Tela.DrawLine(myPen, x, y);
}
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ContextMenuStrip menu = sender as ContextMenuStrip;
//recuperando o controle associado com o contextmenu
Control sourceControl = menu.SourceControl;
DialogResult result = MessageBox.Show("Tem Certeza que deseja remover o nó selecionado?", "Excluir", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if(result == DialogResult.Yes)
{
sourceControl.Dispose();
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Determine whether the key entered is the F1 key. Display help if it is.
if (e.KeyCode == Keys.Space)
{
TextBox textBox1 = sender as TextBox;
novoNó tela = new novoNó(textBox1.Text);
tela.Show();
}
}
}
Each control, TextBox included has a Move, event. Put an Invalidate() call there!
The lines should be drawn in the Paint event of the container that holds the TextBoxes, probably the Form; if it is the Form indeed call this.Invalidate().
Please move the line drawing code out of the DoubleClick event into the Paint event or else the lines will not persist, say minimize/maximize events or other situation, when the system has to redraw the application!
You probably will need to create a data structure to maintain information about which TextBox-pairs need to be connected, maybe a List<Tuple> or a List<someStructure>. This would get filled/modified in the DoubleClick event, then call this.Invalidate() and in the Form.Paint you have a foreach loop over the list of TextBox-pairs..
If you are drawing on the Form do make sure to turn DoubleBuffered on!
Update: To compare the reults here is a minimal example the expects two TextBoxes on a Form:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
this.DoubleBuffered = true;
pairs.Add(new Tuple<Control, Control>(textBox1, textBox2));
}
List<Tuple<Control, Control>> pairs = new List<Tuple<Control, Control>>();
Point mDown = Point.Empty;
private void Form2_Paint(object sender, PaintEventArgs e)
{
foreach (Tuple<Control, Control> cc in pairs)
drawConnection(e.Graphics, cc.Item1, cc.Item2);
}
void drawConnection(Graphics G, Control c1, Control c2)
{
using (Pen pen = new Pen(Color.DeepSkyBlue, 3f) )
{
Point p1 = new Point(c1.Left + c1.Width / 2, c1.Top + c1.Height / 4);
Point p2 = new Point(c2.Left + c2.Width / 2, c2.Top + c2.Height / 4);
G.DrawLine(pen, p1, p2);
}
}
void DragBox_MouseDown(object sender, MouseEventArgs e)
{
mDown = e.Location;
}
void DragBox_MouseMove(object sender, MouseEventArgs e)
{
TextBox tb = sender as TextBox;
if (e.Button == MouseButtons.Left)
{
tb.Location = new Point(e.X + tb.Left - mDown.X, e.Y + tb.Top - mDown.Y);
}
}
void DragBox_MouseUp(object sender, MouseEventArgs e)
{
mDown = Point.Empty;
}
private void DragBox_Move(object sender, EventArgs e)
{
this.Invalidate();
}
}

How do i trigger the mouse middle button in enter event of the mouse?

I have this code:
public void globalPbsMouseEnterEvent(object sender, System.EventArgs e)
{
if (e.Button == MouseButtons.Middle)
{
MessageBox.Show("hi");
}
PictureBox p = sender as PictureBox;
pb.SizeMode = PictureBoxSizeMode.StretchImage;
if (file_array != null)
{
if (file_array.Length > 0)
{
for (int i = 0; i < file_array.Length; i++)
{
if (p == pbs[i])
pb.Animate(file_array[i]);
}
}
}
pb.Visible = true;
pb.BringToFront();
leave = true;
}
But e.Button not exist Button not exist as property for e
This is the code in the constructor of form1 where i make the instance for the global enter event. The variable pbs is is array of AnimatedPictureBoxs:
pbs = new AnimatedPictureBox.AnimatedPictureBoxs[8];
progressbars = new ProgressBar[8];
for (int i = 0; i < pbs.Length; i++)
{
progressbars[i] = new ProgressBar();
progressbars[i].Size = new Size(100, 10);
progressbars[i].Margin = new Padding(0, 0, 0, 70);
progressbars[i].Dock = DockStyle.Top;
pbs[i] = new AnimatedPictureBox.AnimatedPictureBoxs();
pbs[i].MouseEnter += globalPbsMouseEnterEvent;
pbs[i].MouseLeave += globalPbsMouseLeaveEvent;
pbs[i].Tag = "PB" + i.ToString();
pbs[i].Size = new Size(100, 100);
pbs[i].Margin = new Padding(0, 0, 0, 60);
pbs[i].Dock = DockStyle.Top;
pbs[i].SizeMode = PictureBoxSizeMode.StretchImage;
Panel p = i < 4 ? panel1 : panel2;
p.Controls.Add(pbs[i]);
p.Controls.Add(progressbars[i]);
pbs[i].BringToFront();
progressbars[i].BringToFront();
}
This is the code in the class AnimatedPictureBox:
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DannyGeneral;
namespace WeatherMaps
{
class AnimatedPictureBox
{
//Use this custom PictureBox for convenience
public class AnimatedPictureBoxs : PictureBox
{
public static bool images;
List<string> imageFilenames;
Timer t = new Timer();
public AnimatedPictureBoxs()
{
images = false;
AnimationInterval = 10; //It's up to you, the smaller, the faster.
t.Tick += Tick_Animate;
}
public int AnimationInterval
{
get { return t.Interval; }
set { t.Interval = value; }
}
public void Animate(List<string> imageFilenames)
{
this.imageFilenames = imageFilenames;
t.Start();
}
public void StopAnimate()
{
t.Stop();
i = 0;
}
int i;
private void Tick_Animate(object sender, EventArgs e)
{
if (images == true)
{
imageFilenames = null;
}
if (imageFilenames == null)
{
return;
}
else
{
try
{
if (i >= imageFilenames.Count)
{
i = 0;
}
else
{
Load(imageFilenames[i]);
i = (i + 1) % imageFilenames.Count;
}
}
catch (Exception err)
{
Logger.Write(err.ToString());
}
}
}
}
}
}
What i want to do is when the user click on the middle mouse button it will pause the animation and when he click again on the middle button of the mouse the animation will continue.
But in the globalenter event e dosent have the Button property.
In your code, specifically here
public void globalPbsMouseEnterEvent(object sender, System.EventArgs e)
{
if (e.Button == MouseButtons.Middle)
{
MessageBox.Show("hi");
}
....................
}
You can't do it on MouseEnter actually need to use MouseDown, MouseWheel [for example] to have MouseEventArgs
public void globalPb_MouseDown(object sender, MouseEventArgs e)
{
if (e.MiddleButton = MouseButtonState.Pressed)
{
MessageBox.Show("hi");
}
....................
}

Categories