Moving images from a dynamic list PictureBox - c#

I am initiating me into programming thanks to Stack Overflow.
The game I'm doing in c #, consists of several bees flying around the desktop, which I have to give Click and SCORE is going to increase by a certain time.
To which I did the following:
Create a list PictureBox dynamically (at runtime): OK
Load PictureBox with these GIF images randomly: OK
![Bee Games][1]
In this part I was stuck:
Place these randomly PictureBox (in the bottom of the form).
Make the PictureBox move randomly (more or less marked routes).
each PictureBox Click Event, Change the PictureBox image and hide (visible = false), and increase in SCORE + 1.
I need help please.
My code is as follows:
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.IO;
namespace MiPrimerJuego
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int x = 20;
int y = 600;
List<System.Windows.Forms.PictureBox> objeto = new List<PictureBox>();
for (int i = 0; i < 10; i++, x += 90)
{
PictureBox pBox = new PictureBox();
pBox.Height = 80;
pBox.Width = 50;
pBox.Location = new System.Drawing.Point(x, y);
objeto.Add(pBox);
pBox.SizeMode = PictureBoxSizeMode.StretchImage;
Controls.Add(pBox);
var rand = new Random();
var files = Directory.GetFiles(Application.StartupPath + #"/Images", "*.gif");
pBox.Image = System.Drawing.Bitmap.FromFile(files[rand.Next(files.Length)]);
}
}
}
}

Declare rand and files outside the for-loop and objeto outside the function/void as a Private member variable:
private List<PictureBox> objeto = new List<PictureBox>();
private void button1_Click(object sender, EventArgs e)
{
var files = Directory.GetFiles(Application.StartupPath + #"/Images", "*.gif");
int x = 20;
int y = 600;
var rand = new Random();
for (int i = 0; i < 10; i++)
{
x += 90;
PictureBox pBox = new PictureBox();
pBox.Height = 80;
pBox.Width = 50;
pBox.Location = new System.Drawing.Point(x, y);
objeto.Add(pBox);
pBox.SizeMode = PictureBoxSizeMode.StretchImage;
Controls.Add(pBox);
pBox.Image = System.Drawing.Bitmap.FromFile(files[rand.Next(files.Length)]);
}
}
}

Sorry, I did not explain properly.
What I do is this:
1 Make the PictureBox move randomly from the bottom of the form (more or less marked routes).
2 In the Click event of each PictureBox, Changing the PictureBox image and hide (visible = false), and increase in SCORE + 1.
My code is as follows:
using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
using System.IO;
namespaceMiPrimerJuego
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}
privatevoid button1_Click(object sender, EventArgs e)
{
int x = 20;
int y = 600;
List<System.Windows.Forms.PictureBox>objeto = newList<PictureBox>();
for (inti = 0; i< 10; i++, x += 90)
{
PictureBoxpBox = newPictureBox();
pBox.Height = 80;
pBox.Width = 50;
pBox.Location = newSystem.Drawing.Point(x, y);
objeto.Add(pBox);
pBox.SizeMode = PictureBoxSizeMode.StretchImage;
Controls.Add(pBox);
var rand = newRandom();
var files = Directory.GetFiles(Application.StartupPath + #"/Images", "*.gif");
pBox.Image = System.Drawing.Bitmap.FromFile(files[rand.Next(files.Length)]);
}
}
}
}

Related

Randomly put an image in specific places using C#

I am absolutely new with C#, so I hope my question is not completely off.
As you can see in the picture above, I have a form, in which there is a table (image) and a button. In the resources of the project, I have another image (black_rectangle.png), which is a black rectangle, exactly at the same size of each the table's cell. This is what I'm trying to achieve:
Each time the 'Again' button is clicked, I want the six black rectangles to cover two of the tree cells in each column, in a random manner. For example, after the first try, the table could look like this:
I'm basically stuck at the beginning:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
List<PictureBox> items = new List<PictureBox>();
PictureBox newPic= new PictureBox();
newPic.Height = 50;
newPic.Width = 50;
newPic.BackColor = Color.Maroon;
int x = rand.Next(10, this.ClientSize.Width - newPic.Width);
int y = rand.Next(10, this.ClientSize.Height - newPic.Height);
newPic.Location = new Point(x, y);
}
}
Assuming the table (image) is in "pictureBox1", you could try something like:
private Random rnd = new Random();
private List<int> positions = new List<int> { 0, 1, 2 };
private List<PictureBox> prevBoxes = new List<PictureBox>();
private void button1_Click(object sender, EventArgs e)
{
prevBoxes.ForEach(pb => pb.Dispose()); // remove previous boxes
for(int col=0; col<3; col++)
{
positions = positions.OrderBy(i => rnd.Next()).ToList(); // shuffle positions
for(int i=0; i<2; i++)
{
PictureBox newPic = new PictureBox();
newPic.Height = 50;
newPic.Width = 50;
newPic.BackColor = Color.Maroon;
newPic.Location = new Point(pictureBox1.Left + (col * 50), pictureBox1.Top + (positions[i] * 50));
this.Controls.Add(newPic);
newPic.BringToFront();
prevBoxes.Add(newPic);
}
}
}
Output:

Create Dynamic Web Control in c# desktop application

I just want to create multiple web control using c# in visual studio. I have written the code for that but it create only once, I think it show the control created at the last in the loop.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MDMScreenSharing
{
public partial class Form2 : Form
{
private List<Skybound.Gecko.GeckoWebBrowser> geckowebbrouser;
public Form2()
{
InitializeComponent();
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.AutoSize = true;
this.Padding = new Padding(0, 0, 20, 20);
this.StartPosition = FormStartPosition.CenterScreen;
}
private void Form2_Load(object sender, EventArgs e)
{
int inputNumber =5;
geckowebbrouser = new List<Skybound.Gecko.GeckoWebBrowser>();
for (int i = 1; i <= inputNumber; i++)
{
int j = 1;
String wbname = "br" + i;
Skybound.Gecko.GeckoWebBrowser gw = new Skybound.Gecko.GeckoWebBrowser();
gw.Width = 200;
gw.Height = 200;
gw.Parent = panel1;
gw.Name = wbname;
gw.Location = new Point(gw.Width, panel1.Bottom + (i * 30));
gw.Navigate("http://192.168.1.162:8080");
geckowebbrouser.Add(gw);
this.Controls.Add(gw);
j = j*gw.Width;
}
}
}
}
This will show the web control created at the last. I think the program should be more dynamic for that. What am I doing wrong?
The form output, that show only once.
with the new addition of code i have code that one of you provided. the code is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MDMScreenSharing
{
public partial class Form2 : Form
{
private List<Skybound.Gecko.GeckoWebBrowser> geckowebbrouser;
public Form2()
{
InitializeComponent();
// this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
// this.AutoSize = true;
//this.Padding = new Padding(0, 0, 20, 20);
// this.StartPosition = FormStartPosition.CenterScreen;
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(602, 395);
this.flowLayoutPanel1.TabIndex = 0;
}
private void Form2_Load(object sender, EventArgs e)
{
int inputNumber =4;
geckowebbrouser = new List<Skybound.Gecko.GeckoWebBrowser>();
for (int i = 1; i <= inputNumber; i++)
{
String wbname = "br" + i;
Skybound.Gecko.GeckoWebBrowser gw = new Skybound.Gecko.GeckoWebBrowser();
gw.Parent = flowLayoutPanel1;
gw.Width = 200;
gw.Height = 200;
gw.Name = wbname;
gw.Navigate("http://192.168.1.162:8080");
geckowebbrouser.Add(gw);
flowLayoutPanel1.Controls.Add(gw);
}
}
}
}
but the problem in this case only one browser window navigate the page.
like this
as you can see.
I think better approach will be using FlowLoayoutPanel so that you don't have to handle the position of each new control.
Go like this:
Add the FlowLayoutPanel through visual designer from toolbox.
Then on your designer.cs you should automatically have:
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(602, 395);
this.flowLayoutPanel1.TabIndex = 0;
FormLoad event:
private void Form1_Load ( object sender, EventArgs e )
{
int inputNumber = 5;
geckowebbrouser = new List<Skybound.Gecko.GeckoWebBrowser>();
for ( int i = 1; i <= inputNumber; i++ )
{
int j = 1;
String wbname = "br" + i;
var gw = new Skybound.Gecko.GeckoWebBrowser();
gw.Width = 300;
gw.Height = 300;
gw.Name = wbname;
geckowebbrouser.Add(gw);
flowLayoutPanel1.Controls.Add(gw);
gw.Navigate("http://www.google.com");
}
}
Update
The only difference from the WebBrowser implementation is that you need to call the Navigate method after you've added the control to the panel. Check the updated code above.
I have tested with default Skybound.Gecko.GeckoWebBrowser control too, and it's working just fine too:

c# gomoku game label array

I am trying to make a simple five in a row (gomoku) game for two players using windows forms and c#. I put a picturebox with a picture and stretched it out on the form. Now I want to put labels at all the intersections on the picture board so a user can click them and change their background color to black or white.
How can I make the labels created clickable on the form?
public partial class Form1 : Form
{
int labelCount = 0;
int iteration = 0;
public Form1()
{
InitializeComponent();
Label[] board = new Label[361];
for (int i = 0; i < 361; i++)
{
board[i] = new Label
{
Name = "label" + i,
Height = 55,
Width = 55,
MinimumSize = new Size(55, 55),
Text = "label " + i
};
}
int x = 0;
int y = 0;
foreach (var Label in board)
{
if (x >= 580)
{
x = 0;
y = y + Label.Height + 55;
}
Label.Location = new Point(x, y);
this.Controls.Add(Label);
x += Label.Width;
}
}
}
Should I make a one-dimensional [361] or two-dimensional array[{A,1}, {A,2}....{D,1}] to easily check for a winner? How can I connect it to the created labels so the array data corresponds to the objects on the board?
Well Sorry If don`t understand your question. For the Q.1 to add 361 labels you can try the code below. I hope it will help you.
public int x = 0;
public int y = 0;
private Label[] moku = new Label[361];
private void Form1_Load(object sender, EventArgs e)
{
try
{
for (int i = 0; i < 361; i++)
{
moku[i] = new Label();
moku[i].Parent = pictureBox1;//make the picturebox parent
moku[i].Location = new Point(x, y);
moku[i].Text = "O";
moku[i].Name = "moku" + i;
moku[i].BackColor = Color.Transparent;
pictureBox1.Controls.Add(moku[i]);
y += 55;
if (y >= 361) { x += 55; y = 0; x+=55; }
}
}catch(Exception er)
{
MessageBox.Show(er.ToString());
}
}
I prefer using a 2D array because it's easier if you want to check the surrounding boxes.
Form design:
Full source:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication6
{
public enum Player
{
Empty = 0,
White,
Black
}
public partial class Form1 : Form
{
// initialize board of 5x5
private Player[,] board = new Player[5, 5];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DrawBoard();
}
private void DrawBoard()
{
for (var i = 0; i <= board.GetUpperBound(0); i++)
{
for (var j = 0; j <= board.GetUpperBound(1); j++)
{
// for name and text
var name = string.Format("{0}, {1}", i, j);
var label = new Label()
{
Name = name, // name of label
Size = new Size(55, 55),
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(i * 55, j * 55), // location depends on iteration
Text = name
};
label.Click += ClickLabel; // subscribe the Click event handler
pictureBox1.Controls.Add(label); // add label to a container
}
}
}
// this event handler will handle all the labels click event
private void ClickLabel(object sender, EventArgs e)
{
var label = (Label)sender; // this is the label that you click
var x = Convert.ToInt32(label.Name.Split(',')[0]);
var y = Convert.ToInt32(label.Name.Split(',')[1]);
// change the color
if (radPlayerBlack.Checked)
{
// Player Black
label.ForeColor = Color.White;
label.BackColor = Color.Black;
board[x, y] = Player.Black;
}
else
{
// Player White
label.ForeColor = Color.Black;
label.BackColor = Color.White;
board[x, y] = Player.White;
}
}
}
}
You can check the value of the 2D array for black or white. Here's the value when I QuickWatch it in Visual Studio.

How to enable auto scroll?

I have a feeling that Im am missing something obvious but:
I have a single row of pictures in a form, in theory the pictures could go on forever. I need a scroll bar so that the user can look at all of the pictures in the row. I know I need to enable auto scroll but I have no idea how to enable it. Can someone tell me how to enable it or something that I am missing?
If it helps this is the code i am using to generate the pictures:
private void imagePalletToolStripMenuItem_Click(object sender, EventArgs e)
{
MyPalletGui.Show();
Dictionary<string,Bitmap> MyPallet = MyImageCollection.ToDictionary();
int xcor = -50;
int ycor = 0;
foreach (Bitmap curtImage in MyPallet.Values){
PictureBox myPicBox = new PictureBox();
xcor += 50;
myPicBox.Location = new Point(xcor, ycor);
myPicBox.Width = 50;
myPicBox.Height = 50;
myPicBox.Visible = true;
myPicBox.Image = new Bitmap(curtImage);
this.MyPalletGui.Controls.Add(myPicBox);
This code will do exactly what you want, it uses the Form as the ViewPort with AutoScroll:
public Form1()
{
InitializeComponent();
PopulatePictures();
}
private void PopulatePictures()
{
this.AutoScroll = true;
string[] list = Directory.GetFiles(#"C:\\Users\\Public\\Pictures\\Sample Pictures", "*.jpg");
PictureBox[] picturebox= new PictureBox[list.Length];
int y = 100;
for (int index = 0; index < picturebox.Length; index++)
{
picturebox[index] = new PictureBox();
this.Controls.Add(picturebox[index]);
picturebox[index].Location=new Point(index * 120, y);
if(x%12 == 0)
y = y + 150;
picturebox[index].Size = new Size(100,120);
picturebox[index].Image = Image.FromFile(list[index]);
}
}

Images not changing on new search. C# (asp.net project)

This uses bing's web service. I have a single image button and an array of image buttons. The single changes each time it is clicked to the next image in the array. The problem is if I click it and do a new search the array of image buttons does not change.
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using bing_search.net.bing.api;
using System.Collections;
namespace bing_search
{
public partial class _Default : System.Web.UI.Page
{
static ArrayList images = new ArrayList();
static Image[] imagearry;
static ImageButton[] imgButtnsArray;
static int counter = 0;
int fooBarCount = 0;
int firstLoad = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DoItButton_Click(object sender, EventArgs e)
{
images.Clear();
imagearry = null;
imgButtnsArray = null;
BingService bs = new BingService();
net.bing.api.SearchRequest req = new SearchRequest();
req.AppId = "0B15AB60D625A10059A4A04B68615C5B0D904CA9";
req.Query = SearchBox.Text;
req.Sources = new SourceType[] { SourceType.Image};
req.Market = "en-us";
req.Adult = AdultOption.Off;
req.Image = new ImageRequest();
req.Image.CountSpecified = true;
req.Image.Count = 50;
SearchResponse resp = bs.Search(req);
foreach (ImageResult result in resp.Image.Results)
{
Image im = new Image();
im.ImageUrl = result.MediaUrl;
im.Width = 200;
im.Height = 200;
images.Add(im);
//this.Controls.Add(im);
}
// Image lol = (Image)images[0];
int size = images.Count;
imagearry = new Image[size];
Type typ = typeof(Image);
imagearry = (Image [])images.ToArray(typ);
ImageButton1.ImageUrl = imagearry[0].ImageUrl;
int blaCount = 0;
ArrayList imgButtns = new ArrayList();
foreach (Image ii in images)
{
ImageButton imgb = new ImageButton();
imgb.Width = 200;
imgb.Height = 200;
imgButtns.Add(imgb);
}
size = imgButtns.Count;
imgButtnsArray = (ImageButton[])imgButtns.ToArray(typeof(ImageButton));
foreach (ImageButton iii in imgButtnsArray)
{
imgButtnsArray[fooBarCount].ImageUrl = imagearry[fooBarCount].ImageUrl;
Panel1.Controls.Add(iii);
fooBarCount++;
}
fooBarCount = 0;
counter = 0;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
counter++;
heightLable.Text = "clicked";
Image tempImage = (Image)imagearry[counter];
ImageButton1.ImageUrl = tempImage.ImageUrl;
foreach (ImageButton iii in imgButtnsArray)
{
imgButtnsArray[fooBarCount].ImageUrl = imagearry[fooBarCount].ImageUrl;
Panel1.Controls.Add(iii);
fooBarCount++;
}
fooBarCount = 0;
counter = 0;
}
}
}
You reset both counters on every click, so its always starts from the same image.
fooBarCount = 0;
counter = 0;
also they are not static, so they reset to 0 anyway on every page load, and show the same image and not change.
If from the other hand the cache is the problem, because I can not know whats the image file name, and maybe this is the issue here, then try something like.
imgButtnsArray[fooBarCount].ImageUrl =
imagearry[fooBarCount].ImageUrl +
"?rnd=" + RandomNumber.ToString();
I changed ImageButton1_Click to this and now it works. thanks for the quick responses. Back to playing with .net
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
counter++;
heightLable.Text = "clicked";
Image tempImage = (Image)imagearry[counter];
ImageButton1.ImageUrl = tempImage.ImageUrl;
//Random RandomNumber = new Random(10000);
foreach (ImageButton iii in imgButtnsArray)
{
Panel1.Controls.Add((Image)imagearry[fooBarCount]);
fooBarCount++;
}
fooBarCount = 0;
counter = 0;
}

Categories

Resources