I want to move a label ( named Label2 ) to the right by pressing a button and when I press the button again I want it to move again ( Hope You Understand )
This is my code:
private void button3_Click(object sender, EventArgs e)
{
int x = 28;
x++;
label2.Location = new Point(x, 63);
}
But it doesn't work. What am I doing wrong?
This is because you are using a local int x, so it will be reset to 28 each time you click the button.
Move the declaration of x outside the button3_Click() method so that 'x' is a field. Then it will retain its value between each button click.
Obviously you will need to give it a better name; perhaps currentLabelLeft.
This will move it right by 1 pixel each time:
private void button3_Click(object sender, EventArgs e)
{
int x = label2.Location.X;
x++;
label2.Location = new Point(x, 63);
}
Create two css classes and set them as follows (if you have to set it from code behind):
label2.CssClass = "move_to_right"
Related
When playing with clickevents in visual studio i came accross this error:
private void pictureBox1_Click(object sender, EventArgs e)
{
Testcounter = 0;
pictureBox1.MouseClick += myMouseClickEventFunction;
}
private void myMouseClickEventFunction(object sender, MouseEventArgs e)
{
int x = colors.GetUpperBound(0) + 1;
int y = colors.GetUpperBound(1) + 1;
Testcounter++;
var point = new Point(e.X - pictureBox1.Width/2, e.Y - pictureBox1.Height/2);
for (int i = 0; i < x; i++)
{
for (int u = 0; u < y; u++)
{
if (cirkles[i, u].Contains(point))
{
changeIndex(i, u);
}
}
}
this.Refresh();
}
The first time i click my picturebox the counters value is 1, the second time the value is 2, 3th time 3,... Does anyone has any idea why this happends? thnx
pic1
pic2
Because by executing this
pictureBox1.MouseClick += myMouseClickEventFunction;
You're adding the handler one more time with each click. Which should mean, that if you click it once, you add it once and it executes once. But with the second click, you add it one more time, so this time it will execute two times and that's why your counter is increasing to 2. What you need is to move your click handler somewhere else and register it only one time, which means that the best place to move it should be in the initialization of the form. (In public MainForm(){} or whatever form you're using the code in)
P.S.: Sorry for the poor english, I hope you understood me.
Ok so please keep answers very direct and i must say i am very new to C#, i don't know a lot of stuff. Without further adieu my problem.
I am trying to move a picture box horizontally across the screen on a timer.The timer must go infinitely. I have tried all i currently know in C# and searched around quite a lot but nothing answered my exact question which is what i need because of my lesser knowledge of C#. For the last two weeks i worked on graphics mostly and the rest of that was trying to get this to work, So i have no code in my game. This is because for anything to work i need this part to be working. My game is 2D topdown. Any and all help is appreciated.
Thank you for taking the time to read.
Edit
No more answers needed, Thank you Odrai for the answer, it helped me a lot.
Use pictureBox.Location = new Point(x, y) or set pictureBox.Left/Top/Right. You can define x and y as variabels and initialize them with a default value. Increment x on timer tick.
Sample 1:
public partial class Form1 : Form
{
private Random _random
public Form1()
{
InitializeComponent();
_random = new Random();
}
private void timer1_Tick(object sender, EventArgs e)
{
int x = _random.Next(0, 500);
int y = _random.Next(0, 500);
pictureBox1.Top += y;
pictureBox1.Left += x;
}
}
Sample 2:
private void timer1_Tick(object sender, EventArgs e)
{
this.SuspendLayout();
pictureBox.Location = new Point(picust.Location.X + 10, picust.Location.Y);
this.ResumeLayout();
}
Add two buttons with title LEFT and RIGHT to a form and write the following code.
It might give you an idea, how to do simple moving animations.
public partial class Form1 : Form
{
int difference = 0;
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
timer.Interval = 15;
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
pictureBox1.Left += difference;
}
private void btnLeft_Click(object sender, EventArgs e)
{
difference = -2;
}
private void btnRight_Click(object sender, EventArgs e)
{
difference = 2;
}
}
Try This Code it will work :
private void timer1_Tick(object sender, EventArgs e)
{
int width = this.Width; // get the width of Form.
if(pictureBox1.Location.X > width - pictureBox1.Width) //to check condition if pic box is touch the boundroy of form width
{
pictureBox1.Location = new Point(1, pictureBox1.Location.Y); // pic box is set to the new point. here 1 is indicate of X coordinate.
}
else
{
pictureBox1.Location = new Point(pictureBox1.Location.X + 100, pictureBox1.Location.Y); // to move picture box from x coordinate by 100 Point.
}
}
//Try This //
picturebox1.Location = 0,0;
I have a datagridview with some data. I have added a custom button which will show when i click on a cell. By clicking this button a popup form will be opened. My requirement is only set the location of popup form that is should show just below the selected cell of the datagridview. below is the screen shot:
This doesn't work 100% but it's a starting point, based off my comment:
Main Form:
public Form1()
{
InitializeComponent();
}
private Point _cellClick;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var h = dataGridView1.Rows[0].Height;
if (MousePosition.Y % h == 0)
{
_cellClick = new Point(MousePosition.X, MousePosition.Y);
}
else
{
var y = MousePosition.Y;
do
{
y++;
} while (y % h != 0);
_cellClick = new Point(MousePosition.X, y);
}
}
private void button1_Click(object sender, EventArgs e)
{
var f = new Form2(_cellClick);
f.ShowDialog(this);
}
Child Form:
private Point loc;
public Form2(Point location)
{
InitializeComponent();
loc = location;
}
private void Form2_Load(object sender, EventArgs e)
{
this.SetDesktopLocation(loc.X, loc.Y);
}
Edit This is really close to what you're looking for, the only issue is that the child form doesn't show up "adjacent" to the cell, but exactly where the mouse was when they clicked on the cell.
You could probably do some basic arithmetic to figure out the height of a cell to offset MousePosition.Y so that the child form shows up adjacent to it. I think you just need to round the coordinate to the nearest multiple of N, where N is dataGridView1.Rows[0].Height, rounding up.
Edit 2 I just edited the code to try something like this, and now the child form tends to show up just a little bit below the row.
I want to implement Nine Men's Morris Game.
I have a board with 24 pictureboxes and on the left and right side, 9 red pictureboxes and 9 green pictureboxes.
I want to add them in a list:
List<PictureBox> ls = new List<PictureBox>();
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 24; i++)
{
PictureBox p = new PictureBox();
p.Name = "pictureBox" + i;
ls.Add(p);
}
}
is it ok?
and is it possible to do something like this: I want to click on one of the 24 pictureboxes, and make the background of that picturebox to become one time green and one time red?
I mean recursive function or something like that that can recognize when i click on a picturebox, search in the list for that picturebox and changes his backcolor?
You don't need any pictureBox list here.
for (int i = 1; i <= 24; i++)
{
PictureBox p = new PictureBox();
p.Click += p_Click;
//of course, somecontrol.Controls.Add(p);
//for ex: this.Controls.Add(p);
}
-
void p_Click(object sender, EventArgs e)
{
((PictureBox)sender).BackColor = Color.Green;
}
EDIT
It seems you are trying to add an event handler to all pictureBoxes
**parentControl**.Controls.OfType<PictureBox>()
.ToList().ForEach(p => p.Click+=p_Click);
I assume the list of 24 PictureBoxes is supposed to represent the points on a nine man morris board where the player's men can be positioned.
I4V is right that all you need to do is add a click handler to each picture box. If you want to have the background alternate between green and red, keep your original list, but add the click handler in it
for (int i = 1; i <= 24; i++)
{
PictureBox p = new PictureBox();
p.Name = "pictureBox" + i;
p.Click += p_Click; // <----------
ls.Add(p);
}
And modify i4v's click handler to use the current background color to determine the new background color.
void p_Click(object sender, EventArgs e)
{
PictureBox p = (PictureBox)sender);
p.BackColor = p.BackColor == Color.Green ? Color.Red : Color.Green;
}
A couple of other points.
You don't set an initial background color, so it will be the default color until clicked on, when it will be set to Green (as Green isn't the default background color).
Why name your pictureboxes w/ their List index + 1? Why not just use the List index and the natural C# iteration from 0: for (int i = 0; i < 24; i++)?
The method you have outlined would not work, however there is another way to do the same thing using the sender object passed into the event handler:
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 24; i++)
{
PictureBox p = new PictureBox();
p.Name = "pictureBox" + i;
p.Click += PictureBox_Click;
}
}
void PictureBox_Click(object sender, EventArgs e)
{
PictureBox event_picturebox = (PictureBox)sender;
event_picturebox.BackColor = Color.White;
}
You just have to map every picture box you want to run this event to the same event, the event will then be able to perform actions on this pictureBox because a reference to it was passed in.
If you already have the picture boxes defined in the form, you just need to do something like:
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Click += PictureBox_Click;
pictureBox2.Click += PictureBox_Click;
// and keep going
// OR
// this is a bit dangerous if you don't want ALL
// your picture boxes to have this event
// also assumes that you know picturebox1 exists.
foreach (object f in this.Controls)
{
if (f.GetType().Equals(pictureBox1.GetType()))
{
((PictureBox)f).Click += button_Click;
}
}
}
Can someone help about create a winform animation like in Win7 Calculator when you hover mouse over button, currently i use bunch of image then looping it in backgroundworker, but i think its wrong, this is my code:
this occur when mouse enter,
private void bgTurnOn_DoWork(object sender, DoWorkEventArgs e)
{
Label labelSender = (Label)e.Argument;
int ii = labelSender.ImageIndex;
for (int i = ii + 4; i <= 11; i++)
{
if (labelSender.AllowDrop)
{
labelSender.ImageIndex = i;
Thread.Sleep(40);
}
}
}
and this when mouse leave
private void bgTurnOff_DoWork(object sender, DoWorkEventArgs e)
{
Label labelSender = (Label)e.Argument;
int ii = labelSender.ImageIndex;
for (int i = ii; i >= 0; i--)
{
if (!labelSender.AllowDrop)
{
labelSender.ImageIndex = i;
Thread.Sleep(80);
}
}
}
note: I just use AllowDrop so I do not bother to declare new variable, i have 42 button, so i think i need more efficient solution.
It seems that you want a glow effect, so you can use the next idea:
Make an OpacityPictureBox : PictureBox which supports opacity (in levels of 1-100 or double 0-1). See this for more information.
Add two public const int values of MaxOpacity and MinOpacity to the OpacityPictureBox class, for easy and safe range checks from the outside. The values might be 0, 100 or 0, 1, or something else, depending on your implementation of opacity.
Make an AnimatedPictureBox : UserControl which holds 1 PictureBox named pbNormal and 1 OpacityPictureBox named opbHover, both Dock = DockStyle.Fill, and one timer named timer. Make sure that pbNormal is below opbHover.
Have three public properties:
Normal of type Image which delegates into pbNormal.Image
Hover of type Image which delegates into opbHover.Image
AnimationInterval of type int which delgates into timer.Interval
In the constructor of the AnimatedPictureBox, after calling InitializeComponents, do opbHover.Opacity = 0;. You can also do this.Cursor = Cursors.Hand; if you want the cursor to change into a hand when hovering over it.
Have a private members: _animationDirection of type int, which will be -1 or 1.
Have a private method that starts an animation in a given direction:
Code:
private void Animate(int animationDirection)
{
this._animationDirection = animationDirection;
this.timer.Start();
}
Override OnMouseEnter and OnMouseLeave:
Code:
protected override void OnMouseEnter(EventArgs e)
{
this.Animate(1);
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
this.Animate(-1);
base.OnMouseEnter(e);
}
Listen to timer.Tick event and with this:
Code:
private void timer_Tick(object sender, EventArgs e)
{
var hoverOpacity = this.opbHover.Opacity + this._animationDirection;
if (hoverOpacity < OpacityPictureBox.MinOpacity ||
hoverOpacity > OpacityPictureBox.MaxOpacity)
{
this.timer.Stop();
return;
}
this.opbHover.Opacity = hoverOpacity;
}