Flip Image(Mirror) in a PictureBox Control - c#

First of all I am a beginner with C#.
I have a picturebox and a timer (enabled, interval = 25).
I have inserted a gif image of a bird in the picturebox.
And in the Timer event I have written,
bool positionBird = true;
private void timer1_Tick(object sender, EventArgs e)
{
if (PictureBox1.Location.X == Screen.PrimaryScreen.Bounds.Width)
{
positionBird = false;
}
else if (PictureBox1.Location.X == 0)
{
positionBird = true;
}
if(positionBird)
{
PictureBox1.Left += 1;
}
else
{
PictureBox1.Left += -1;
}
}
But what I want to achieve is, when the picture box touches the right
boundary and condition become false, I want to flip the image of bird in
the picturebox. Right now the bird is doing Michael Jackson's Moonwalk!
I tried to flip the bird (mirror the bird) using the below code.
else
{
PictureBox pict = new PictureBox();
pict = PictureBox1;
pict.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);
pict.Left += -1;
}
But it looks weird. It shows the flip image and normal image both. Can
someone help me on this? As I already said I am a beginner. Some simple
code with explanation would be very helpful. Also can someone tell me
what I am doing wrong?

DO NOT CREATE another Picture Box. You are seeing the original picture because you have not modified the original but the newly created one.
So the modified code is follows:
bool positionBird = true;
private void timer1_Tick(object sender, EventArgs e)
{
if (PictureBox1.Location.X == Screen.PrimaryScreen.Bounds.Width)
{
positionBird = false;
PictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipX); // picture flips only once when touches boundary
}
else if (PictureBox1.Location.X == 0)
{
positionBird = true;
PictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipX); // picture flips only once when touches boundary
}
if(positionBird)
{
PictureBox1.Left += 1;
}
else
{
PictureBox1.Left += -1;
}
}

Related

I have a glitch in my program which keeps opening a specific form over and over again after the form is hidden

I am an AS Software Development student and I have made an Electronics Quiz for my CA. I have come across a glitch which I cannot seem to fix. It has started to bug me and I can't think of what is wrong. My teacher also cannot see what is wrong. Everything else is working. Here is the code:
namespace MyQuiz2
{
public partial class DragDropYear8_Question1 : Form
{
public DragDropYear8_Question1(string name, int quizSelection)
{
InitializeComponent();
CenterToScreen();
setupQuestion();
}
private void setupQuestion()
{
AllowDropping();
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
LEDImg.Visible = true;
ResistorImg.Visible = true;
VairiableResistorImg.Visible = true;
timer1.Interval = 1000;
timer1.Start();
if (_time1 == 0)
{
ShowNextQuestion();
}
}
//variable decleration
private int _time1 = 15;
private int _correctAnswers = 0;
//Set up timer
private void timer1_Tick(object sender, EventArgs e)
{
_time1--;
TimerLbl.Text = "Time: " + _time1;
}
//Question setup
private void ShowNextQuestion()
{
_time1 = 0;
Hide();
new DragDropYear8_Question2(StartScreen.Player.Username, 10).Show();
}
private void AllowDropping()//allows the label to be dropped onto a picture box.
{
VairiableResistorImg.AllowDrop = true;
ResistorImg.AllowDrop = true;
LEDImg.AllowDrop = true;
}
//Tells the program that a label has been grabbed
private void LabelGrabbed(object sender, MouseEventArgs e)
{
Label selectedLabel = (Label)sender;
selectedLabel.DoDragDrop(selectedLabel.Text, DragDropEffects.Copy);
}
//allows the label to be droped onto the PictureBox
private void AllowDragDropCopy(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void UpdateScoreAndLabelWhenCorrect()//updates all labels on the current form if the answers are correct
{
_correctAnswers++;
StartScreen.Player.IncreaseScore();
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
if (_correctAnswers == 3)
{
ShowNextQuestion();
}
}
private void UpdateScoreAndLabelWhenWrong()//updates all labels on the current form if the answers are incorrect
{
_correctAnswers++;
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
if (_correctAnswers == 3)
{
ShowNextQuestion();
}
}
//checks if the right label has been dropped onto the correct picture box
private void VairiableResistorDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Vairiable Resistor")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
VairiableResistorImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorLbl.Visible = false;
VairiableResistorImg.Visible = false;
}
else if (result == "Light Emmiting Diode")
{
UpdateScoreAndLabelWhenWrong();
LEDLbl.Visible = false;
VairiableResistorImg.Visible = false;
}
}
private void LEDDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Light Emmiting Diode")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
LEDImg.Visible = false;
LEDLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorLbl.Visible = false;
LEDImg.Visible = false;
}
else if (result == "Vairiable Resistor")
{
UpdateScoreAndLabelWhenWrong();
LEDImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
}
private void ResistorDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Resistor")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
ResistorImg.Visible = false;
ResistorLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Light Emmiting Diode")
{
UpdateScoreAndLabelWhenWrong();
ResistorImg.Visible = false;
LEDLbl.Visible = false;
}
else if (result == "Vairiable Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
}
}`
The problem is that when I change from the first dragdrop question to the second dragdrop question. Randomly during the second form, the first dragdrop question form will open. It does this the hole way through the quiz. Latter on in the quiz the game loadscreen also does this. The code is as follows:
namespace MyQuiz2
{
public partial class GameLoading : Form
{
public GameLoading()
{
InitializeComponent();
CenterToScreen();
timer1.Start();
}
//Timer and Progressbar setup
private void timer1_Tick(object sender, EventArgs e)
{
//randome number generator for ProgressBar increments
Random random = new Random();
int Increment = random.Next(10, 20);
Random random2 = new Random();
int _Increment = random2.Next(1, 5);
timer1.Interval = 1000;
if (progressBar1.Value <= 80)
{
progressBar1.Increment(Increment);
/*picks a random number between 5 and 10 to increment the ProgressBar by if
the value of the Progress bar is less than or equal to 80*/
}
else
{
progressBar1.Increment(_Increment);
// picks a randome number between 1 and 5 to incremnt by when the ProgressBar is more then 80
}
LoadingLbl.Text = "Loading Game..." + progressBar1.Value + "%";
//When progress bar is at its maximum value the next form will show
if (progressBar1.Value == progressBar1.Maximum)
{
timer1.Stop();
LoadingLbl.Text = "Loading Game... 100%";
CheckScore();
}
}
private void CheckScore()
{
if (StartScreen.Player.Score >= 20)
{
MessageBox.Show("Congratulations, you got more than 80% of the quiz correct. You can proceed to the Game", "Well done!!");
timer1.Stop();
new GameMenu().Show();
Hide();
}
else
{
MessageBox.Show("You got under 80% in the quiz but you can't play the game. Try again.", "Unlucky, Try again");
timer1.Stop();
new EndScreen(false).Show();
Hide();
}
}
}
}
I have
I will link if you would like to have a look for yourself(the source code and a video is included). Thanks
This screen shot shows the problem at the drag drop questions. As you an see from this image, it keeps on multiplying. The same thing happens with the game loading screen
I think the problem is that the timer does not stop which will keep on opening the forms but I'm not sure. I hope this lets you understand my problem better. Thanks
You an still call each question as a form. I would have a function that shows the requested question. This can be called by a second function that can keep track of the question you are on. Also, I would probably call and destroy each form, so that you don't have unnecessary forms hanging around. Something like this (writing this on my phone so take it as an outline more than direct code) :
public void CallQuestions()
{
int QuestionNumber = 1;
do {
if Question(QuestionNumber)
QuestionNumber++;
} while (Exit == false) ;
}
public boolean Question(int number)
{
Form QuestionForm = null;
switch (number)
{
case 1:
QuestionForm = new DragDropYear8_Question1;
break;
//...
}
if (QuestionForm.ShowDialog() == DialogResult.Ok)
return true;
return false;
}

Collision only works 2 sides

So i am trying to make a pacman clone in c#, Visual studio express 2013. I have the maze, and ive put labels on the edges. I have a point with the future coordinates of pacman. If that point doesnt intersect with the labels, pacmans location will take the location of the point. This works just fine when pacman is comming from down or right, however it doesnt work if he comes from right or top. This is also true for the ghosts, whose movement is randomly generated. They both seem to consider the label bigger. I tried to search the internet for why this might be, but i cant seem to find an answer. Ive put down the part with collision check and pacman movement. Thanks in advance
private void timer_Tick(object sender, EventArgs e)
{
//colision check
PictureBox intermed = new PictureBox
{
Location = new Point(pictureBox1.Location.X + pacdirx, pictureBox1.Location.Y + pacdiry),
};
if (!intermed.Bounds.IntersectsWith(label1.Bounds) )
pictureBox1.Location = new Point(pictureBox1.Location.X + pacdirx, pictureBox1.Location.Y + pacdiry);
private void Form3_KeyDown(object sender, KeyEventArgs e)
{
//pacman movement
if (e.KeyCode == Keys.W)
{
pacdiry = -3;
pacdirx = 0;
pictureBox1.Image = Image.FromFile("eat_up.gif");
}
if (e.KeyCode == Keys.S)
{
pacdiry = 3;
pacdirx = 0;
pictureBox1.Image = Image.FromFile("eat_down.gif");
}
if (e.KeyCode == Keys.D)
{
pacdiry = 0;
pacdirx = 3;
pictureBox1.Image = Image.FromFile("eat_right.gif");
}
if (e.KeyCode == Keys.A)
{
pacdiry = 0;
pacdirx = -3;
pictureBox1.Image = Image.FromFile("eat_left.gif");
}
}

C# Searchable, Positionable PictureBox

I've been searching about this for a while and haven't found what I'm looking for.
I want to be able to have an image in a picturebox that can be positioned to a point by means of a "search box". Basically, mapping locations in pixels to certain phrases or letters that then shift the position on the picturebox.
I tried to set the location using points, however this does not change the picture at all; the location after calculating the code below stubbornly stays at (3,3).
The picture also is large (~3500 x ~3000) and needs scrolls bars to fully view it.
Here's my code
public Form1()
{
InitializeComponent();
flowLayoutPanel1.AutoScroll = true;
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
flowLayoutPanel1.Controls.Add(pictureBox1);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "m")
{
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox1.Image = Image.FromFile(#"C:\User\Desktop\map.jpg");
pictureBox1.Location = new Point(700, 200);
// ^ The location does not change and stays at (3,3)
// The picturebox is not set as locked
}
Do I need to do something different? Or is the issue with my picture for not allowing me to change the location?
EDIT I found the Solution thanks to the help below. I had to use a panel and place the picturebox within. Below is the code I used.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.AutoScroll = true;
panel1.Controls.Add(pictureBox1);
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox1.Image = Image.FromFile(#"C:\Desktop\image.jpg");
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true;
label1.Visible = true;
int Hvalue = panel1.HorizontalScroll.Value;
label1.Text = Hvalue.ToString();
label2.Visible = true;
int Vvalue = panel1.VerticalScroll.Value;
label2.Text = Vvalue.ToString();
if (textBox1.Text == "m")
{
// these are just values that I put in
panel1.HorizontalScroll.Value = 616;
panel1.VerticalScroll.Value = 90;
}
}

How to drag images from a listview (together with an imageview) to pictureboxes?

I am pretty new to C# and struggle a lot with a small project I want to do.
I am busy with something like a collage maker where I have a list of pictures on the left hand side and I want to drag and drop multiple images to the right hand side where I want to be able to move them around to create my collage.
I wanted to show an image but I am not allowed to post images with less than 10 reputation points. But look here for the image:
I can't manage to get it to work. I've looked online for help but I can't really find what I'm looking for. The stuff I do find are too unclear and I struggle to understand.
This is what I have so far for the code to drag and drop from the left to the right but it doesn't work;
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
int len = e.Data.GetFormats().Length - 1;
int i;
for (i = 0; i <= len; i++)
{
if (e.Data.GetFormats()[i].Equals("System.Windows.Forms.ListView+SelectedListViewItemCollection"))
{
//The data from the drag source is moved to the target.
e.Effect = DragDropEffects.Move;
}
}
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
//Return if the items are not selected in the ListView control.
if (listView1.SelectedItems.Count == 0)
{
return;
}
ListViewItem dragitem = listView1.SelectedItems[0];
pictureBox2.Image = imageList1.Images[dragitem.ImageIndex];
listView1.Items.Remove(dragitem);
}
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
listView1.DoDragDrop(listView1.SelectedItems, DragDropEffects.Move);
}
And after I can add image to the left, how can I drag and move them around using the mouse coordinates?
Any help will be appreciated please.
Everything is done using C# in Windows Forms.
Here is a full example you may want to play with:
It uses a form with a ListView, an ImageList and a Panel to hold the PictureBoxes.
You could use a FlowLayoutPanel but this won't let you move the Pictureboxes later.
You also could use a grid of Panels and their BackgroundImage.
First we set up the form:
private void Form1_Load(object sender, EventArgs e)
{
KeyPreview = true;
FillLV(10);
AddPBs(36);
listView1.MouseMove += listView1_MouseMove;
}
void FillLV(int count)
{
for (int i = 0; i < count; i++) listView1.Items.Add("Item" + i, i);
}
void AddPBs(int count)
{
int iWidth = imageList1.ImageSize.Width;
int iHeight = imageList1.ImageSize.Height;
int cols = panel1.ClientSize.Width / iWidth;
for (int i = 0; i < count; i++)
{
PictureBox PB = new PictureBox();
PB.BackColor = Color.LightGray;
PB.Margin = new System.Windows.Forms.Padding(0);
PB.ClientSize = new System.Drawing.Size(iWidth , iHeight );
PB.Location = new Point(iWidth * (i % cols), iHeight * (i / cols));
PB.Parent = panel1;
PB.DragEnter += PB_DragEnter;
PB.DragDrop += PB_DragDrop;
PB.AllowDrop = true;
PB.MouseClick += (ss, ee) => { currentPB = PB; PB.Focus(); };
}
}
Note how we add events to the dynamically created PictureBoxes and how we set their hidden AllowDrop property.
Also note the little lambda to make the MouseClick prepare for moving them around with the keyboard.
For this we will also need a reference to the current box:
PictureBox currentPB = null;
Now we start the dragging. This should not be done in the MouseDown or else it will interfere with normal selection and also happen before the new selection is made..
Either you do it in the MouseMove:
void listView1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (listView1.SelectedItems.Count > 0)
{
listView1.DoDragDrop(listView1.SelectedItems[0], DragDropEffects.Move);
}
}
}
Or (Update) for ListViews better and much simpler (thanks Hans!) in their ItemDrag event:
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
listView1.DoDragDrop(e.Item, DragDropEffects.Move);
}
Update: Both ways now use the dragged Item, not just its imageIndex, to make it simpler to remove the Item from the LV..
void PB_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(ListViewItem)))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
void PB_DragDrop(object sender, DragEventArgs e)
{
PictureBox pb = sender as PictureBox;
var item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
int index = item.ImageIndex;
pb.Image = imageList1.Images[index]; // make sure you have images for indices!!
}
Finally we use the keyboard to move the current box around. I have added code to bring it up and down in the z-order as well.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (currentPB == null) return;
if (e.KeyData == Keys.Left) currentPB.Left -= 1;
else if (e.KeyData == Keys.Right) currentPB.Left += 1;
else if (e.KeyData == Keys.Up) currentPB.Top -= 1;
else if (e.KeyData == Keys.Down) currentPB.Top += 1;
else
{
int z = panel1.Controls.GetChildIndex(currentPB);
if (e.KeyData == Keys.Home) panel1.Controls.SetChildIndex(currentPB, 0);
else if (e.KeyData == Keys.End)
panel1.Controls.SetChildIndex(currentPB, panel1.Controls.Count);
else if (e.KeyData == Keys.PageUp)
panel1.Controls.SetChildIndex(currentPB, z + 1);
else if (e.KeyData == Keys.PageDown)
{ if (z > 0) panel1.Controls.SetChildIndex(currentPB, z - 1); }
}
panel1.Invalidate();
}
For this to work the form must have : KeyPreview = true;
Note that the sizes in an ImageList are restricted to 256x256. So you may want to use only the index and use it to load larger images from disk..

Fading in and fading out for a form

i have a requirement in which my form is transparent,if my mouse enters into it the form
should became visible,if my mouse leaves out of the form it becomes transparent, i have three different controls placed in my form , each controls mouse leave and mouse enter is the same that of the form . if my mouse enters into the form and enters into a control
form_mouseleaveevent and control_mouseenterd gets fired so iam not able to achieve it,how to overcome this.
below is the piece of code for this:
private void TransToOpac()
{
if (!isTransparent)
return;
if (TtoOON == false )
{
TtoOON = true;
for (i = this.Opacity; i <= 1; i = i + 0.02)
{
this.Opacity = i;
Thread.Sleep(50);
}
isTransparent = false;
TtoOON = false;
}
}
private void OpacToTrans()
{
if (isTransparent)
return;
if (OtoTON == false )
{
OtoTON = true;
for (i = this.Opacity; i >= 0.5; i = i - 0.02)
{
this.Opacity = i;
Thread.Sleep(50);
}
isTransparent = true;
OtoTON = false;
}
}
private void OnMouseEntered(object sender, EventArgs e)
{
TransToOpac();
}
private void OnMouseLeft(object sender, EventArgs e)
{
OpacToTrans();
}
You can't get this done with MouseEnter/Leave events. The smaller problem is that the form's Leave event may never fire if a control is close to the edge. The bigger problem is that it will fire when the cursor moves into the non-client area (border, caption), you don't want to fade the form when the user tries to close or resize the window.
The crude but effective solution is to use a timer to check where the mouse is located:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.Opacity = 0.99; // Avoid flicker
mFadeTimer.Interval = 15;
mFadeTimer.Tick += new EventHandler(mFadeTimer_Tick);
mMouseTimer.Interval = 200;
mMouseTimer.Tick += new EventHandler(mMouseTimer_Tick);
mMouseTimer.Enabled = true;
}
void mMouseTimer_Tick(object sender, EventArgs e) {
if (this.Bounds.Contains(Control.MousePosition)) {
if (mFade <= 0) { mFade = 1; mFadeTimer.Enabled = true; }
}
else {
if (mFade >= 0) { mFade = -1; mFadeTimer.Enabled = true; }
}
}
void mFadeTimer_Tick(object sender, EventArgs e) {
double opaq = this.Opacity + mFade * 0.05;
if (opaq >= 0.99) { opaq = 0.99; mFadeTimer.Enabled = false; }
if (opaq <= 0.15) { opaq = 0.15; mFadeTimer.Enabled = false; }
this.Opacity = opaq;
}
private Timer mFadeTimer = new Timer();
private Timer mMouseTimer = new Timer();
private int mFade = 0;
}
You could also check in Form_MouseLeave whether the mouse pointer is still within the form's bounds and in that case not fade out.
EDIT
There are several ways to find out whether the mouse is still within form's bounds. Easiest would be to use the Mouse.GetPosition method to find the current mouse position. The result is the location of the mouse pointer in screen coordinates. You can then check, whether the form's bounding rectangle contains the location.

Categories