I have an image that is chopped into 4 pieces (2x2). I draw them in a random order and if the order of the small pics are correct write out "You win".
If you click on an image then it should be swap with the another next to it.
If you click the left button first change position with the third (right button 2-4). What is the problem with the code?
[![enter image description here][1]][1]
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;
using System.Collections;
namespace SimplePuzzle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonVéletlen_Click(object sender, EventArgs e)
{
Mix();
pictureBox1.Image = Image.FromFile("img\\1.png");
pictureBox2.Image = Image.FromFile("img\\2.png");
pictureBox3.Image = Image.FromFile("img\\3.png");
pictureBox4.Image = Image.FromFile("img\\4.png");
}
int[] arr = new int[4];
void Mix()
{
Random rnd = new Random();
int n = 4;
// Fill array 1-4
for (int i = 0; i < n; i++)
{
arr[i] = i + 1;
}
// Rnd array
for (int j = 0; j < n; j++)
{
int one = rnd.Next(n);
int another = rnd.Next(n);
int temp = arr[one];
arr[one] = arr[another];
arr[another] = temp;
}
for (int i = 0; i < 4; i++)
{
Console.WriteLine(arr[i].ToString());
}
// PictureBox1
if (arr[0]==0)
{
pictureBox1.Left = 0;
pictureBox1.Top = 0;
}
if (arr[0] == 1)
{
pictureBox1.Left = 150;
pictureBox1.Top = 0;
}
if (arr[0] == 2)
{
pictureBox1.Left = 0;
pictureBox1.Top = 150;
}
if (arr[0] == 3)
{
pictureBox1.Left = 150;
pictureBox1.Top = 150;
}
// PictureBox2
if (arr[1] == 0)
{
pictureBox2.Left = 0;
pictureBox2.Top = 0;
}
if (arr[1] == 1)
{
pictureBox2.Left = 150;
pictureBox2.Top = 0;
}
if (arr[1] == 2)
{
pictureBox2.Left = 0;
pictureBox2.Top = 150;
}
if (arr[1] == 3)
{
pictureBox2.Left = 150;
pictureBox2.Top = 150;
}
// PictureBox3
if (arr[2] == 0)
{
pictureBox3.Left = 0;
pictureBox3.Top = 0;
}
if (arr[2] == 1)
{
pictureBox3.Left = 150;
pictureBox3.Top = 0;
}
if (arr[2] == 2)
{
pictureBox3.Left = 0;
pictureBox3.Top = 150;
}
if (arr[2] == 3)
{
pictureBox3.Left = 150;
pictureBox3.Top = 150;
}
// PictureBox4
if (arr[3] == 0)
{
pictureBox4.Left = 0;
pictureBox4.Top = 0;
}
if (arr[3] == 1)
{
pictureBox4.Left = 150;
pictureBox4.Top = 0;
}
if (arr[3] == 2)
{
pictureBox4.Left = 0;
pictureBox4.Top = 150;
}
if (arr[3] == 3)
{
pictureBox4.Left = 150;
pictureBox4.Top = 150;
}
}
void CheckWin()
{
if (pictureBox1.Left==0 && pictureBox1.Top == 0 &&
pictureBox2.Left == 0 && pictureBox2.Top == 0 &&
pictureBox3.Left == 0 && pictureBox3.Top == 0 &&
pictureBox4.Left == 0 && pictureBox4.Top == 0)
{
MessageBox.Show("You have won!");
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBoxKöztes.Image = pictureBox1.Image;
pictureBox1.Image = pictureBox2.Image;
pictureBox2.Image = pictureBoxKöztes.Image;
CheckWin();
}
private void pictureBox2_Click(object sender, EventArgs e)
{
pictureBoxKöztes.Image = pictureBox2.Image;
pictureBox2.Image = pictureBox1.Image;
pictureBox1.Image = pictureBoxKöztes.Image;
CheckWin();
}
private void pictureBox3_Click_1(object sender, EventArgs e)
{
pictureBoxKöztes.Image = pictureBox3.Image;
pictureBox3.Image = pictureBox4.Image;
pictureBox4.Image = pictureBoxKöztes.Image;
CheckWin();
}
private void pictureBox4_Click(object sender, EventArgs e)
{
pictureBoxKöztes.Image = pictureBox4.Image;
pictureBox4.Image = pictureBox3.Image;
pictureBox3.Image = pictureBoxKöztes.Image;
CheckWin();
}
private void buttonFirstCol_Click(object sender, EventArgs e)
{
pictureBoxKöztes.Image = pictureBox1.Image;
pictureBox1.Image = pictureBox3.Image;
pictureBox3.Image = pictureBoxKöztes.Image;
CheckWin();
}
private void buttonSecondCol_Click(object sender, EventArgs e)
{
pictureBoxKöztes.Image = pictureBox2.Image;
pictureBox2.Image = pictureBox4.Image;
pictureBox4.Image = pictureBoxKöztes.Image;
CheckWin();
}
}
}
[1]: https://i.stack.imgur.com/G9dMy.png
The CheckWin() method is the problem.
All you are doing is checking that the left and top of the picture boxes == 0.
But there's no code moving them around, so it can't ever equal true.
Related
This is a link to the winforms project from my onedrive:
https://1drv.ms/u/s!AmVw2eqP6FhB4h01pNXIMlqdZJk_?e=wSGaRx
using Newtonsoft.Json;
using Ookii.Dialogs.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
namespace Image_Crop
{
public partial class Form1 : Form
{
Rectangle rect;
int pixelsCounter = 0;
Color SelectedColor = Color.LightGreen;
List<DrawingRectangle> DrawingRects = new List<DrawingRectangle>();
Bitmap rectImage;
int saveRectanglesCounter = 1;
bool drawBorder = true;
bool clearRectangles = true;
bool saveRectangles = true;
//bool drawnNewRectangle = false; // To think how to work with this flag bool variable
// where to use it how and how to solce this problem !!!!!
string rectangleName;
Dictionary<string, string> FileList = new Dictionary<string, string>();
string selectedPath;
int x, y;
private bool crop = false;
public Form1()
{
InitializeComponent();
textBox1.Text = Properties.Settings.Default.ImageToCropFolder;
textBox2.Text = Properties.Settings.Default.CroppedImagesFolder;
selectedPath = textBox2.Text;
if (textBox1.Text != "")
{
Bitmap bmp = new Bitmap(Image.FromFile(textBox1.Text),
pictureBox2.Width, pictureBox2.Height);
pictureBox2.Image = bmp;
}
checkBoxDrawBorder.Checked = true;
checkBoxClearRectangles.Checked = true;
checkBoxSaveRectangles.Checked = true;
if (selectedPath != "" && selectedPath != null)
{
if (System.IO.File.Exists(Path.Combine(selectedPath, "rectangles.txt")))
{
string g = System.IO.File.ReadAllText(Path.Combine(selectedPath, "rectangles.txt"));
g = g.Remove(0, 32);
FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
listBox1.DataSource = FileList.Keys.ToList();
label2.Text = listBox1.Items.Count.ToString();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
else
{
label2.Text = "0";
}
}
else
{
label2.Text = "0";
}
if ((selectedPath != "" && selectedPath != null) && textBox1.Text != "")
{
crop = true;
}
else
{
crop = false;
}
}
public class DrawingRectangle
{
public Rectangle Rect => new Rectangle(Location, Size);
public Size Size { get; set; }
public Point Location { get; set; }
public Control Owner { get; set; }
public Point StartPosition { get; set; }
public Color DrawingcColor { get; set; } = Color.LightGreen;
public float PenSize { get; set; } = 3f;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left || crop == false) return;
x = 0;
y = 0;
if (pictureBox2.Image != null && selectedPath != null)
{
if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
{
DrawingRects.Add(new DrawingRectangle()
{
Location = e.Location,
Size = Size.Empty,
StartPosition = e.Location,
Owner = (Control)sender,
DrawingcColor = SelectedColor
});
}
}
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
int X = e.X;
int Y = e.Y;
if (e.Button != MouseButtons.Left || crop == false) return;
if ((X >= 0 && X <= pictureBox2.Width) && (Y >= 0 && Y <= pictureBox2.Height))
{
if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
{
if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
{
x = e.X;
y = e.Y;
var dr = DrawingRects[DrawingRects.Count - 1];
if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }
if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }
dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));
pictureBox2.Invalidate();
}
}
}
}
int count = 0;
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left || crop == false) return;
if (DrawingRects.Count > 0 && pictureBox2.Image != null && selectedPath != "")
{
if ((x >= 0 && x <= pictureBox2.Image.Size.Width) && (y >= 0 && y <= pictureBox2.Image.Size.Height))
{
var dr = DrawingRects.Last();
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);
if (saveRectangles)
{
count++;
rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
FileList,
Formatting.Indented
);
using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
{
sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
sw.Write(json);
sw.Close();
}
rectImage.Save(rectangleName);
saveRectanglesCounter++;
}
pixelsCounter = rect.Width * rect.Height;
pictureBox1.Invalidate();
listBox1.DataSource = FileList.Keys.ToList();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
pictureBox2.Focus();
Graphics g = Graphics.FromImage(this.pictureBox1.Image);
g.Clear(this.pictureBox1.BackColor);
}
}
else
{
if (clearRectangles)
{
DrawingRects.Clear();
pictureBox2.Invalidate();
}
x = 0;
y = 0;
}
}
}
string GetNextName(string baseName, string extension)
{
int counter = 1;
string nextName = baseName + counter + extension;
while (System.IO.File.Exists(nextName))
{
counter++;
nextName = baseName + counter + extension;
}
return nextName;
}
private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
if (drawBorder)
{
ControlPaint.DrawBorder(e.Graphics, pictureBox2.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
}
if (pictureBox2.Image != null && selectedPath != null && DrawingRects.Count > 0)
{
DrawShapes(e.Graphics);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (drawBorder)
{
ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
}
if (rectImage != null && DrawingRects.Count > 0)
{
var dr = DrawingRects.Last();
e.Graphics.DrawImage(rectImage, dr.Rect);
if (clearRectangles)
{
DrawingRects.Clear();
pictureBox2.Invalidate();
}
}
}
private void DrawShapes(Graphics g)
{
if (DrawingRects.Count == 0) return;
g.SmoothingMode = SmoothingMode.AntiAlias;
foreach (var dr in DrawingRects)
{
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize))
{
g.DrawRectangle(pen, dr.Rect);
};
}
}
}
public Bitmap cropAtRect(Bitmap b, Rectangle r)
{
Bitmap nb = new Bitmap(r.Width, r.Height);
using (Graphics g = Graphics.FromImage(nb))
{
g.DrawImage(b, -r.X, -r.Y);
return nb;
}
}
private void checkBoxDrawBorder_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxDrawBorder.Checked)
{
drawBorder = true;
}
else
{
drawBorder = false;
}
pictureBox1.Invalidate();
pictureBox2.Invalidate();
}
private void checkBoxClearRectangles_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxClearRectangles.Checked)
{
clearRectangles = true;
}
else
{
clearRectangles = false;
}
pictureBox2.Invalidate();
}
private void checkBoxSaveRectangles_CheckedChanged(object sender, EventArgs e)
{
if(checkBoxSaveRectangles.Checked)
{
saveRectangles = true;
}
else
{
saveRectangles = false;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = ((ListBox)sender).SelectedItem;
var val = FileList[(string)item];
pictureBox1.Image = System.Drawing.Image.FromFile(val);
}
private void button1_Click(object sender, EventArgs e)
{
VistaOpenFileDialog dialog = new VistaOpenFileDialog();
{
dialog.Filter = "Images (*.jpg, *.bmp, *.gif)|*.jpg;*.bmp;*.gif";
};
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dialog.FileName;
Properties.Settings.Default.ImageToCropFolder = dialog.FileName;
Properties.Settings.Default.Save();
Bitmap bmp = new Bitmap(Image.FromFile(dialog.FileName),
pictureBox2.Width, pictureBox2.Height);
pictureBox2.Image = bmp;
if(textBox1.Text != "" && textBox2.Text != "")
{
crop = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox2.Text = dialog.SelectedPath;
selectedPath = dialog.SelectedPath;
Properties.Settings.Default.CroppedImagesFolder = selectedPath;
Properties.Settings.Default.Save();
if (textBox1.Text != "" && textBox2.Text != "")
{
crop = true;
}
}
}
}
}
The problem is in the mouse up event i can't find the logic with the saving flag saveRectangles.
this is the saving part in the mouse up
if (saveRectangles)
{
count++;
rectangleName = GetNextName(Path.Combine(selectedPath, "Rectangle"), ".bmp");
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
FileList,
Formatting.Indented
);
using (StreamWriter sw = new StreamWriter(Path.Combine(selectedPath, "rectangles.txt"), false))
{
sw.WriteLine("Total number of rectangles: " + count + Environment.NewLine);
sw.Write(json);
sw.Close();
}
rectImage.Save(rectangleName);
saveRectanglesCounter++;
}
if the checkBox checkBoxSaveRectangles is not checked when running the application and the folder in textBox1 is empty there are no saved images yet on the hard disk then it will throw exception at the line 201 in the MouseUp event :
Graphics g = Graphics.FromImage(this.pictureBox1.Image);
because the image in pictureBox1 is null.
but in that case i still want it to crop images and add the images information as items to the listBox just not to save it to the hard disk.
i think that rectImage variable is also used in the pictureBox1 paint event.
anyway the goal is to be able to keep cropping even if the saving checkbox not checked and the there are no saved images in the cropped images folder.
I'm working on a multimedia assignment and I found that the Dr is using this.load in the code so...
I don't understand why do we need this event handler as I think we can work without it.
I don't get why do I need such a ready made function and how it would be useful in multimedia programming or gaming programming.
This is my code :
namespace changecolors
{
public class Actor
{
public int X, Y, W, H;
public Color cl;
}
public partial class Form1 : Form
{
List<Actor> L = new List<Actor>();
int pos = -1;
public Form1()
{
this.WindowState = FormWindowState.Maximized;
this.Load += new EventHandler(Form1_Load);
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
this.MouseDown += new MouseEventHandler(Form1_MouseDown);
}
void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
pos = -1;
for (int i = 0; i < L.Count; i++)
{
if (e.X >= L[i].X
&& e.X <= L[i].X + L[i].W
&& e.Y >=L[i].Y
&& e.Y <= L[i].Y + L[i].H)
{
pos = i;
}
}
}
else
{
if (pos > -1)
{
L[pos].Y += 10;
}
}
DrawScene();
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Space:
DrawScene();
break;
}
}
void Form1_Load(object sender, EventArgs e)
{
int V = 100;
Color[] z = { Color.DarkGray, Color.Red, Color.Blue };
for (int i = 0; i < 3; i++)
{
Actor pnn = new Actor();
pnn.X = V;
pnn.Y = 200;
pnn.W = 70;
pnn.H = 170;
pnn.cl = z[i];
V += pnn.W;
L.Add(pnn);
}
}
void DrawScene()
{
Graphics g = this.CreateGraphics();
g.Clear(Color.MistyRose);
for (int i = 0; i < L.Count; i++)
{
SolidBrush br = new SolidBrush(L[i].cl);
g.FillRectangle(br,
L[i].X, L[i].Y,
L[i].W, L[i].H);
}
}
}
}
Let me explain my problem:
I have a picturebox and this should be used to draw several elements of a listbox.
I gave the picturebox a canvas. by left and rightclick u can put up a rectangle which should preview the element u want to draw on the canvas of the picturebox.
Now this is my problem:
this rectangle should just be a preview and should be erased every time i click on a another position of the picturebox and put up a new rectangle. it should just be drawn on the canvas when i click on the inputbutton.
So how can i preview the chosen elements in the rectangle made by left and rightclick?
I hope my question is clealy enough : /
This is what i did so far:
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 Interaktive_systeme_sta
{
public partial class Bildeditor : Form
{
void drawRect()
{
pbxBild.Refresh();
using (Graphics g = this.pbxBild.CreateGraphics())
{
Pen blackPen = new Pen(Color.Black, 1);
blackPen.DashPattern = new float[] {2,2};
int X = Convert.ToInt32(nupX.Value);
int Y = Convert.ToInt32(nupY.Value);
int B = Convert.ToInt32(nupBreite.Value);
int H = Convert.ToInt32(nupHoehe.Value);
g.DrawRectangle(blackPen, X, Y, B, H);
g.Dispose();
}
}
public Bildeditor()
{
InitializeComponent();
this.MinimumSize = new Size(630,420);
this.MaximumSize = new Size(630, 420);
int canvasWidth = pbxBild.Width;
int canvasHeight = pbxBild.Height;
nupBreite.Maximum = canvasWidth;
nupHoehe.Maximum = canvasHeight;
nupBreite.Minimum = 0;
nupHoehe.Minimum = 0;
nupBreite.Value = canvasWidth;
nupHoehe.Value = canvasHeight;
nupX.Maximum = canvasWidth;
nupY.Maximum = canvasHeight;
nupX.Minimum = 0;
nupY.Minimum = 0;
nupX.Value = 0;
nupY.Value = 0;
drawRect();
}
private void btnZuruecksetzten_Click(object sender, EventArgs e)
{
int canvasWidth = pbxBild.Width;
int canvasHeight = pbxBild.Height;
nupX.Value = 0;
nupY.Value = 0;
nupBreite.Value = canvasWidth-1;
nupHoehe.Value = canvasHeight-1;
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
drawRect();
}
private void pbxBild_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
Point mouseDownLocation = new Point(e.X, e.Y);
switch (e.Button)
{
case MouseButtons.Left:
if (e.X < 0)
{
nupX.Value = 0;
}
else
{
nupX.Value = e.X;
}
if (e.Y < 0)
{
nupY.Value = 0;
}
else
{
nupY.Value = e.Y;
}
break;
case MouseButtons.Right:
if (e.X - nupX.Value < 1)
{
nupBreite.Value = 1;
}
else
{
nupBreite.Value = e.X - nupX.Value;
}
if (e.Y - nupY.Value < 1)
{
nupHoehe.Value = 1;
}
else
{
nupHoehe.Value = e.Y - nupY.Value;
}
break;
}
drawRect();
}
private void nupY_ValueChanged(object sender, EventArgs e)
{
drawRect();
}
private void nupBreite_ValueChanged(object sender, EventArgs e)
{
drawRect();
}
private void nupHoehe_ValueChanged(object sender, EventArgs e)
{
drawRect();
}
private void btnEinfuegen_Click(object sender, EventArgs e)
{
if (lbBildelemente.SelectedIndex == 0)
{
zeichneBild();
}
else if (lbBildelemente.SelectedIndex == 1)
{
zeichneLine();
}
else if (lbBildelemente.SelectedIndex == 2)
{
zeichneRect();
}
else if (lbBildelemente.SelectedIndex == 3)
{
zeichneText();
}
else if (lbBildelemente.SelectedIndex == 4)
{
zeichneKreis();
}
}
private void lbBildelemente_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbBildelemente.SelectedIndex == 0)
{
tbFarbe.Enabled = false;
btnFarbe.Enabled = false;
nupPen.Enabled = false;
tbBild.Enabled = true;
btnBild.Enabled = true;
tbText.Enabled = false;
tbSchrift.Enabled = false;
btnSchrift.Enabled = false;
}
else if (lbBildelemente.SelectedIndex == 1 || lbBildelemente.SelectedIndex == 2 || lbBildelemente.SelectedIndex == 4)
{
tbFarbe.Enabled = true;
btnFarbe.Enabled = true;
nupPen.Enabled = true;
tbBild.Enabled = false;
btnBild.Enabled = false;
tbText.Enabled = false;
tbSchrift.Enabled = false;
btnSchrift.Enabled = false;
}
else if (lbBildelemente.SelectedIndex == 3)
{
tbFarbe.Enabled = true;
btnFarbe.Enabled = true;
nupPen.Enabled = true;
tbBild.Enabled = false;
btnBild.Enabled = false;
tbText.Enabled = true;
tbSchrift.Enabled = true;
btnSchrift.Enabled = true;
}
}
void zeichneBild()
{
Graphics g = pbxBild.CreateGraphics();
int X = Convert.ToInt32(nupX.Value);
int Y = Convert.ToInt32(nupY.Value);
int B = Convert.ToInt32(nupBreite.Value);
int H = Convert.ToInt32(nupHoehe.Value);
Bitmap bitmap = new Bitmap(tbBild.Text);
g.DrawImage(bitmap, X, Y, B, H);
}
// Als zusatzfunktion kann man die Pinseldicke auswählen
void zeichneRect()
{
Graphics g = pbxBild.CreateGraphics();
Pen Pen = new Pen(tbFarbe.BackColor, Convert.ToInt32(nupPen.Value));
int X = Convert.ToInt32(nupX.Value);
int Y = Convert.ToInt32(nupY.Value);
int B = Convert.ToInt32(nupBreite.Value);
int H = Convert.ToInt32(nupHoehe.Value);
g.DrawRectangle(Pen, X, Y, B, H);
}
//zusatzfunktion
void zeichneKreis()
{
Graphics g = pbxBild.CreateGraphics();
Pen Pen = new Pen(tbFarbe.BackColor, Convert.ToInt32(nupPen.Value));
int X = Convert.ToInt32(nupX.Value);
int Y = Convert.ToInt32(nupY.Value);
int B = Convert.ToInt32(nupBreite.Value);
int H = Convert.ToInt32(nupHoehe.Value);
g.DrawEllipse(Pen, X, Y, B, H);
}
void zeichneLine()
{
Graphics g = pbxBild.CreateGraphics();
Pen Pen = new Pen(tbFarbe.BackColor, Convert.ToInt32(nupPen.Value));
int X = Convert.ToInt32(nupX.Value);
int Y = Convert.ToInt32(nupY.Value);
int B = Convert.ToInt32(nupBreite.Value);
int H = Convert.ToInt32(nupHoehe.Value);
g.DrawLine(Pen, X, Y, X+B, Y+H);
}
void zeichneText()
{
Graphics g = pbxBild.CreateGraphics();
Brush brush = new SolidBrush(tbFarbe.BackColor);
int X = Convert.ToInt32(nupX.Value);
int Y = Convert.ToInt32(nupY.Value);
g.DrawString(tbText.Text, fontDialog1.Font, brush, X, Y);
}
private void btnFarbe_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
tbFarbe.BackColor = colorDialog1.Color;
}
}
private void btnSchrift_Click(object sender, EventArgs e)
{
// Show the dialog.
DialogResult result = fontDialog1.ShowDialog();
// See if OK was pressed.
if (result == DialogResult.OK)
{
// Get Font.
Font font = fontDialog1.Font;
// Set TextBox properties.
this.tbSchrift.Text = string.Format(font.Name +"; "+ font.Size +"pt");
}
}
private void btnBild_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Joint Photographic Experts Group (*.jpg)|*.jpg|"
+ "EMF Enhanced Metafile Format (*.emf)|*.emf|"
+ "Graphics Interchange Format (*.gif)|*.gif|"
+ "Bitmap (*.bmp)|*.bmp|"
+ "W3C Portable Network Graphics (*.png)|*.png";
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
tbBild.Text = openFileDialog.FileName;
}
}
private void bildbereichLöschenToolStripMenuItem_Click(object sender, EventArgs e)
{
pbxBild.Refresh();
}
private void bildLadenToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Joint Photographic Experts Group (*.jpg)|*.jpg|"
+ "EMF Enhanced Metafile Format (*.emf)|*.emf|"
+ "Graphics Interchange Format (*.gif)|*.gif|"
+ "Bitmap (*.bmp)|*.bmp|"
+ "W3C Portable Network Graphics (*.png)|*.png";
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
Graphics g = pbxBild.CreateGraphics();
int X = 0;
int Y = 0;
int B = Convert.ToInt32(pbxBild.Width);
int H = Convert.ToInt32(pbxBild.Height);
Bitmap bitmap = new Bitmap(openFileDialog.FileName);
g.DrawImage(bitmap, X, Y, B, H);
}
}
}
}
I think this is what you need
private void Form1_Load(object sender, EventArgs e)
{
listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem == "Circle")
{
pictureBox1.Image = circle;
}
}
This is all the events and functions in my Form1 what should i do ?
I need to detect the borders/bounds of the pictureBox1 control and stop the mouse move when its touching the borders.
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
label1.Text = e.X.ToString();
label2.Text = e.Y.ToString();
label1.Visible = true;
label2.Visible = true;
label3.Visible = true;
label4.Visible = true;
// find the index that is closest to the current mouse location
MinDist = float.MaxValue;
for (idx = 0; idx < Point_X.Count; ++idx)
{
float dx = Point_X[idx] - e.X;
float dy = Point_Y[idx] - e.Y;
float dist = (float)Math.Sqrt(dx * dx + dy * dy);
if (dist < MinDist)
{
MinDist = dist;
selectedIndex = idx;
}
}
if (MinDist < 5)
{
mouseMove = true;
OriginalX = Point_X[(int)selectedIndex];
OriginalY = Point_Y[(int)selectedIndex];
if (cyclicSelectedIndex.Count() == 2)
{
cyclicSelectedIndex[currentCyclicIndex] = (int)selectedIndex;
currentCyclicIndex++;
if (currentCyclicIndex > 1)
{
currentCyclicIndex = 0;
}
if ((cyclicSelectedIndex[0] == cyclicSelectedIndex[1]) || (cyclicSelectedIndex[0] == -1) || (cyclicSelectedIndex[1] == -1))
{
button2.Enabled = false;
}
else
{
button2.Enabled = true;
}
label13.Text = selectedIndex.ToString();
label13.Visible = true;
label14.Visible = true;
listView1.Items.Add(selectedIndex.ToString()).EnsureVisible();
}
}
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (mouseMove == true)
{
Point NewPoint = e.Location;
Point_X[(int)selectedIndex] = NewPoint.X;
Point_Y[(int)selectedIndex] = NewPoint.Y;
label1.Text = NewPoint.X.ToString();
label2.Text = NewPoint.Y.ToString();
pictureBox1.Refresh();
Point_X[(int)selectedIndex] = Math.Max(pictureBox1.Left, Math.Min(pictureBox1.Right, NewPoint.X));
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (mouseMove == true)
{
Point NewPoint = e.Location;
Point_X[(int)selectedIndex] = NewPoint.X;
Point_Y[(int)selectedIndex] = NewPoint.Y;
mouseMove = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
halfX = pictureBox1.ClientRectangle.Width / 2;
halfY = pictureBox1.ClientRectangle.Height / 2;
Random rnd = new Random();
offsetX = rnd.Next(-10, 10);
offsetY = rnd.Next(-10, 10);
addPoint(halfX + offsetX, halfY + offsetY);
pictureBox1.Refresh();
numberOfPoints++;
label16.Text = numberOfPoints.ToString();
label16.Visible = true;
label15.Visible = true;
}
private void addPoint(float x , float y)
{
Point_X.Add(x);
Point_Y.Add(y);
label5.Text = x.ToString();
label6.Text = y.ToString();
label5.Visible = true;
label6.Visible = true;
label7.Visible = true;
label8.Visible = true;
}
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Point connectionPointStart;
Point connectionPointEnd;
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
SolidBrush brush = new SolidBrush(Color.Red);
Pen p = new Pen(brush);
for (int idx = 0; idx < Point_X.Count; ++idx)
{
Point dPoint = new Point((int)Point_X[idx], (int)Point_Y[idx]);
dPoint.X = dPoint.X - 5; // was - 2
dPoint.Y = dPoint.Y - 5; // was - 2
Rectangle rect = new Rectangle(dPoint, new Size(10, 10));
g.FillEllipse(brush, rect);
}
for (int i = 0; i < connectionStart.Count; i++)
{
int startIndex = connectionStart[i];
int endIndex = connectionEnd[i];
connectionPointStart = new Point((int)Point_X[startIndex], (int)Point_Y[startIndex]);
connectionPointEnd = new Point((int)Point_X[endIndex], (int)Point_Y[endIndex]);
p.Width = 4;
g.DrawLine(p, connectionPointStart, connectionPointEnd);
}
}
private void button2_Click(object sender, EventArgs e)
{
addConnection(cyclicSelectedIndex[0], cyclicSelectedIndex[1]);
pictureBox1.Invalidate();
}
private void addConnection(int i, int j)
{
if (cyclicSelectedIndex[0] == -1)
{
return;
}
if (cyclicSelectedIndex[0] == cyclicSelectedIndex[1])
{
return;
}
if (connectionStart.Count() == 0)
{
connectionStart.Add(i);
connectionEnd.Add(j);
//label12.Text = i.ToString();
//label11.Text = j.ToString();
label12.Text = connectionStart[0].ToString();
label11.Text = connectionEnd[0].ToString();
label9.Visible = true;
label10.Visible = true;
label11.Visible = true;
label12.Visible = true;
return;
}
for (int f = 0; f < connectionStart.Count(); f++)
{
if ((connectionStart[f] == i && connectionEnd[f] == j) || (connectionStart[f] == j && connectionEnd[f] == i)) // this checking dosent work good !
{
button2.Enabled = false;
return;
}
else
{
label12.Text = connectionStart[f].ToString();
label11.Text = connectionEnd[f].ToString();
label9.Visible = true;
label10.Visible = true;
label11.Visible = true;
label12.Visible = true;
}
}
connectionStart.Add(i);
connectionEnd.Add(j);
}
Im not sure how to explain it. But how can i do it ?
Thanks.
When calculating the X value use Math.Max with that and the left boundary of the image, and Min on the right boundary of the image. Do the same with the Y value on the Top and Bottom.
Point_X[(int)selectedIndex] = Math.Max(imageLeft, Math.Min(imageRight, NewPoint.X));
I assume you can determine the left/right/top/bottom of the image?
I have created a program for some class work and it all works fine, but I'm having some problems with the alignment of the multiple bits of info inserted into the list box on the same rows.
When I print it, it looks messy and also looks messy in the list box.
Is there anyway I can neaten it up a little? I've tried pad right with no joy and list views confuse the hell out of me. Here is my code:
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 Microsoft.VisualBasic;
using System.Collections;
namespace Assignment2
{
public partial class frmCalculator : Form
{
bool blnDot = false;
double dbAllPoints = 0;
double dbAllMoney = 0;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
ddbItems.Items.Add("Glass");
ddbItems.Items.Add("Paper");
ddbItems.Items.Add("Beverage Cans");
ddbItems.Items.Add("Tins");
ddbItems.Items.Add("Milk Cartons");
ddbItems.Items.Add("Juice Boxes");
ddbItems.Items.Add("Plastics");
ddbItems.Items.Add("Clothes");
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '.'))
{
MessageBox.Show("Please input a number!", "Error");
e.Handled = true;
}
if (e.KeyChar == '.')
{
if (blnDot == true) { e.Handled = true; }
else { blnDot = true; }
}
}
private void txtInput_MouseClick(object sender, MouseEventArgs e)
{
txtInput.Text = "";
}
private void btnCalculate_Click(object sender, EventArgs e)
{
String strItem = "";
double dbMoney = 0;
double dbPoints = 0;
int intPoint = 0;
double dbWeight = 0;
if (((txtInput.Text == "")||(txtInput.Text=="Input the weight")|| (ddbItems.SelectedIndex==0)))
{
MessageBox.Show("Please input a weight into the textbox and make a selection from the drop down box", "Error");
}
else
{
if (ddbItems.SelectedIndex == 1)
{
intPoint = 7;
strItem = ddbItems.Items[1].ToString();
}
if (ddbItems.SelectedIndex == 2)
{
intPoint = 8;
strItem = ddbItems.Items[2].ToString();
}
if (ddbItems.SelectedIndex == 3)
{
intPoint = 10;
strItem = ddbItems.Items[3].ToString();
}
if (ddbItems.SelectedIndex == 4)
{
intPoint = 10;
strItem = ddbItems.Items[4].ToString();
}
if (ddbItems.SelectedIndex == 5)
{
intPoint = 3;
strItem = ddbItems.Items[5].ToString();
}
if (ddbItems.SelectedIndex == 6)
{
intPoint = 3;
strItem = ddbItems.Items[6].ToString();
}
if (ddbItems.SelectedIndex == 7)
{
intPoint = 5;
strItem = ddbItems.Items[7].ToString();
}
if (ddbItems.SelectedIndex == 8)
{
intPoint = 6;
strItem = ddbItems.Items[8].ToString();
}
dbWeight = Convert.ToDouble(txtInput.Text);
dbPoints = intPoint * dbWeight;
dbMoney = dbPoints * 0.01;
dbAllPoints = dbAllPoints + dbPoints;
dbAllMoney = dbAllMoney + dbMoney;
lblTotals.Visible = true;
lblTotals.Text = "You have " + dbAllPoints.ToString() + " points, and you have earned £" + dbAllMoney.ToString("0.00");
lstResults.Items.Add(strItem + " " + dbWeight.ToString() + "kg " + dbPoints.ToString() + " points £" + dbMoney.ToString("0.00"));
txtInput.Text = "Input the weight";
ddbItems.SelectedIndex = 0;
blnDot = false;
}
}
private void btnEnd_Click(object sender, EventArgs e)
{
frmWelcome frmWelcome = (frmWelcome)Application.OpenForms["frmWelcome"];
frmWelcome.Close();
this.Dispose();
}
private void btnReset_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Are you sure you want to reset everything?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.No) return;
txtInput.Text = "Input the weight";
lstResults.Items.Clear();
ddbItems.SelectedIndex = 0;
lblTotals.Text = "";
lblTotals.Visible = false;
blnDot = false;
}
private void btnPrint_Click(object sender, EventArgs e)
{
int intMax;
intMax = lstResults.Items.Count;
String[] arrResults = new String[intMax];
int intLoop;
for (intLoop = 0; intLoop < intMax; intLoop++)
{
arrResults[intLoop] = lstResults.Items[intLoop].ToString();
}
Array.Sort(arrResults);
lstResults.Items.Clear();
for (intLoop = 0; intLoop < intMax; intLoop++)
{
lstResults.Items.Add(arrResults[intLoop]);
}
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String strLine = "";
int intLoop;
Font pfont = new Font("Verdana", 18, GraphicsUnit.Point);
int intLine = 75;
strLine = "Item Weight Points Money";
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
intLine = intLine + 30;
for (intLoop = 0; intLoop < lstResults.Items.Count; intLoop++)
{
strLine = strLine +lstResults.Items[intLoop];
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
intLine = intLine + 30;
strLine = "";
}
intLine = intLine + 30;
strLine = lblTotals.Text;
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
}
}
}
You should use a DataGridView control instead of a ListBox since you are trying to display "column" information.
Likewise, when printing, you should be doing the DrawString for each column as well so that they line up properly.
If you want to continue with what you are doing, then you should use a mono-spaced font like Courier, not Verdana, and count the spaces between then lengths of the words.