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;
}
}
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 have this code that draws a rectangle using the ShapeClass.cs. But I want to update the Rectangle parameters using a button event in the mainform. How do I do that? The PaintRectangle class only gets the initial value on the textbox from the main form. ......................................................................................................................................................................
MAin Class
#region //Passing of values
public string ShapeWidth() { return textBox_Shape_Width.Text;}
public string ShapeHeight() { return textBox_Shape_Height.Text; }
#endregion
private void btn_Draw_Click(object sender, EventArgs e)
{
ShapeClass s = new ShapeClass();
var value = s.diffVar[0];
MessageBox.Show(value.ToString());
pictureBox_Canvas.Paint += paintRect;
pictureBox_Canvas.Refresh();
}
#region //Methods for Hide and Show
public void HideButtons()
{
btn_Rectangle.Visible = false;
btn_Square.Visible = false;
btn_Ellipse.Visible = false;
btn_Circle.Visible = false;
btn_Triangle.Visible = false;
}
public void ShowButtons()
{
btn_Rectangle.Visible = true;
btn_Square.Visible = true;
btn_Ellipse.Visible = true;
btn_Circle.Visible = true;
btn_Triangle.Visible = true;
}
public void HideSettings()
{
btn_Draw.Visible = false;
btn_Accept.Visible = false;
btn_Cancel.Visible = false;
btn_Reset.Visible = false;
btn_Accept.Visible = false;
trackBar_Size.Visible = false;
trackBar_Stroke.Visible = false;
trackBar_Corner.Visible = false;
label_Corner.Visible = false;
label_Height.Visible = false;
label_Size.Visible = false;
label_Stroke.Visible = false;
rb_Both.Visible = false;
rb_Height.Visible = false;
rb_Width.Visible = false;
textBox_Shape_Height.Visible =false;
textBox_Shape_Width.Visible = false;
lbl_Width.Visible = false;
}
public void ShowSettings()
{
btn_Draw.Visible = true;
btn_Accept.Visible = true;
btn_Cancel.Visible = true;
btn_Reset.Visible = true;
btn_Accept.Visible = true;
trackBar_Size.Visible = true;
trackBar_Stroke.Visible = true;
trackBar_Corner.Visible = true;
label_Corner.Visible = true;
label_Height.Visible = true;
label_Size.Visible = true;
label_Stroke.Visible = true;
rb_Both.Visible = true;
rb_Height.Visible = true;
rb_Width.Visible = true;
textBox_Shape_Height.Visible = true;
textBox_Shape_Width.Visible = true;
lbl_Width.Visible = true;
}
#endregion
#region //Rectangle Creation and Scaling
private void btn_Rectangle_Click(object sender, EventArgs e)
{
HideButtons();
ShowSettings();
}
public void paintRect(object sender, PaintEventArgs e)
{
ShapeClass s = new ShapeClass();
s.paintRectangle(e);
}
#endregion
#region //Show and Hide Grid (Checkbox Event)
//Drawing the Grid
private void checkBox_Grid_CheckedChanged(object sender, EventArgs e)
{
if (checkBox_Grid.Checked == true)
{
DrawGrid();
}
else if (!checkBox_Grid.Checked == true)
{
pictureBox_Canvas.Refresh();
HideGrid();
}
else
return;
}
private void DrawGrid()
{
Graphics grid = Graphics.FromImage(bm);
int numOfCells = 301;
int cellSize = 5;
Pen p = new Pen(Color.LightSlateGray);
p.Width = 0.5F;
for (int y = 0; y < numOfCells; ++y)
{
grid.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);
}
for (int x = 0; x < numOfCells; ++x)
{
grid.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);
}
pictureBox_Canvas.Image = bm;
}
//Hides the Grid
private void HideGrid()
{
Graphics grid = Graphics.FromImage(bm);
Pen p = new Pen(Color.White);
p.Width = 0.5F;
int numOfCells = 301;
int cellSize = 5;
for (int y = 0; y < numOfCells; ++y)
{
grid.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);
}
for (int x = 0; x < numOfCells; ++x)
{
grid.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);
}
pictureBox_Canvas.Image = bm;
}
#endregion
#region //Square Creation and Scaling
private void btn_Square_Click(object sender, EventArgs e)
{
HideButtons();
ShowSettings();
}
#endregion
#region //Circle Creation and Scaling
private void btn_Circle_Click(object sender, EventArgs e)
{
HideButtons();
ShowSettings();
}
#endregion
#region //Ellipse Creation and Scaling
private void btn_Ellipse_Click(object sender, EventArgs e)
{
HideButtons();
ShowSettings();
}
#endregion
#region //Triangle Creation and Scaling
private void btn_Triangle_Click(object sender, EventArgs e)
{
HideButtons();
ShowSettings();
}
#endregion
#region //Accept Button
private void btn_Accept_Click(object sender, EventArgs e)
{
HideSettings();
ShowButtons();
}
#endregion
#region //Reset Button
private void btn_Reset_Click(object sender, EventArgs e)
{
HideSettings();
ShowButtons();
}
#endregion
#region //Cancel Button
private void btn_Cancel_Click(object sender, EventArgs e)
{
HideSettings();
ShowButtons();
}
#endregion
#region //VALIDATIONS
private void textBox_Shape_Width_TextChanged(object sender, EventArgs e)
{
if(Convert.ToInt32(textBox_Shape_Width.Text)>128)
{
MessageBox.Show("Width cannot exceed 128.");
textBox_Shape_Width.Text = 128.ToString();
}
}
private void textBox_Shape_Height_TextChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(textBox_Shape_Height.Text) > 128)
{
MessageBox.Show("Height cannot exceed 128");
textBox_Shape_Height.Text = 128.ToString();
}
}
#endregion
private void trackBar_Size_ValueChanged(object sender, EventArgs e)
{
}
}
}
Shape Class
namespace SealCreator2._0
{
public class ShapeClass :Form1
{
Form1 f1 = new Form1();
public double w1,h1, Rect_Width;
public List<object> diffVar = new List<object>();
public void paintRectangle(PaintEventArgs e)
{
int x, y;
w1 = Convert.ToDouble((Convert.ToInt32(f1.ShapeWidth()) * 96) / 25.4);
h1 = Convert.ToDouble((Convert.ToInt32(f1.ShapeHeight()) * 96) / 25.4);
x = ((484 / 2) - (Convert.ToInt32(w1) / 2)); // Positions the Shape in the center of the PictureBox
y = ((484 / 2) - (Convert.ToInt32(h1) / 2));// Positions the Shape in the center of the PictureBox
//Draws a Rectangle
Pen red = new Pen(Color.Red, 3);
Rectangle rect = new Rectangle(x, y, Convert.ToInt32(w1), Convert.ToInt32(h1));
e.Graphics.DrawRectangle(red, rect);
diffVar.Add(w1);
diffVar.Add(h1);
}
}
}
You can create other class which contain both PaintEventArgs and your params. Ex:
public class DrawArgs
{
// parameter which you can modify base on your logic
public int width;
public int height;
public int x;
public int y;
//your paint event
public PaintEventArgs e;
}
And modify your ShapeClass.paintRectangle() method:
public class ShapeClass
{
public void paintRectangle(DrawArgs drawArgs)
{
//w1 = Convert.ToDouble((Convert.ToInt32(f1.ShapeWidth()) * 96) / 25.4);
//h1 = Convert.ToDouble((Convert.ToInt32(f1.ShapeHeight()) * 96) / 25.4);
//x = ((484 / 2) - (Convert.ToInt32(w1) / 2));
//y = ((484 / 2) - (Convert.ToInt32(h1) / 2));
// get your params
var x = drawArgs.x;
var y = drawArgs.y;
var w1 = drawArgs.width;
var h1 = drawArgs.height;
Pen red = new Pen(Color.Red, 3);
Rectangle rect = new Rectangle(x, y, Convert.ToInt32(w1), Convert.ToInt32(h1));
drawArgs.e.Graphics.DrawRectangle(red, rect);
}
}
And you can call it from paintRect method():
public void paintRect(object sender, PaintEventArgs e)
{
ShapeClass s = new ShapeClass();
var drawArg = new DrawArgs
{
e = e,
// and add your params here
x = something,
y = something,
///.....
};
s.paintRectangle(drawArg);
}
P/S: it is just an example. You can modify the DrawArgs class base on your logic
Add a anothe function to change the parameters.
For example:
void UpdateParameters()
{
ChangeParameters();
}
Give you another suggestion: You can edit this question to add Codes.
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.
I'm having problems with playing sound using System.Windows.Media.MediaPlayer, what is weird is how it works the first time around, however on the second time it throws an exception with the message of The calling thread cannot access this object because a different thread owns it.
This is my code below, look at m_BackgroundWorker_DoWork specifically which is where it actually plays the sound where the sound file location is different to the last stored one:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Timers;
using System.Media;
namespace RPGInventor
{
public partial class GameMapPanel : UserControl
{
protected Point m_Size;
protected bool m_bGrid;
protected CMap m_Map;
protected System.Timers.Timer m_Timer;
//protected SoundPlayer m_SoundPlayer;
protected System.Windows.Media.MediaPlayer m_SoundPlayer;
protected string m_szLastMedia;
protected bool m_bRepeatBGS;
public GameMapPanel()
{
InitializeComponent();
this.Width = 0;
this.Height = 0;
m_Size = new Point(0, 0);
m_Timer = new System.Timers.Timer(1000 / 60);
m_Timer.Elapsed += m_Timer_Elapsed;
//m_SoundPlayer = new SoundPlayer();
m_SoundPlayer = new System.Windows.Media.MediaPlayer();
m_szLastMedia = "";
}
void m_Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Invalidate();
}
public void setupGrid(int nCols, int nRows)
{
this.Width = nCols * 32;
this.Height = nRows * 32;
m_Size = new Point(nCols, nRows);
m_Map.setGridSize(nCols, nRows);
GameDialog parent = (GameDialog)this.Parent;
parent.updateScrollBars();
}
public void setMap(CMap map)
{
this.m_Map = map;
MainForm mf = (MainForm)CUtil.findForm("RPG Inventor");
//m_BackgroundWorker.RunWorkerAsync();
m_BackgroundWorker_DoWork(null, null);
for (int i = 0; i < getMap().getEvents().Count; ++i)
{
CEvent cevent = (CEvent)getMap().getEvents()[i];
if (cevent.getType() == (int)CEvent.EventType.TRANSFER)
{
CTransferEvent transferEvent = (CTransferEvent)cevent;
if (CResources.getLoadedMap(transferEvent.getMapName()) == null)
{
CMap temp = new CMap("", 0, 0);
CMap Loadmap = temp.retrieve(mf.m_Database, transferEvent.getMapName());
CResources.addLoadedMap(Loadmap);
}
CLayer layer = (CLayer)getMap().getMapLayers()[1];
CTransferObject transferObj = new CTransferObject(transferEvent);
transferObj.setLocation(new Point(transferEvent.getGridLoc().X * 32,
transferEvent.getGridLoc().Y * 32));
layer.addObject(transferObj, 2);
}
if (cevent.getType() == (int)CEvent.EventType.DOOR)
{
CDoorEvent doorEvent = (CDoorEvent)cevent;
if (CResources.getLoadedMap(doorEvent.getMapName()) == null)
{
CMap temp = new CMap("", 0, 0);
CMap Loadmap = temp.retrieve(mf.m_Database, doorEvent.getMapName());
CResources.addLoadedMap(Loadmap);
}
CLayer layer = (CLayer)getMap().getMapLayers()[1];
CDoorObject doorObj = new CDoorObject(doorEvent);
int nH = doorObj.getHeight();
int nDiff = nH - 32;
int nY = (doorEvent.getGridLoc().Y * 32) - nDiff;
doorObj.setLocation(new Point(doorEvent.getGridLoc().X * 32, nY));
layer.addObject(doorObj, 2);
}
}
}
public CMap getMap()
{
return this.m_Map;
}
public void addCharacterSet(CCharacterSet charSet)
{
CSpriteObject spriteObj = new CSpriteObject();
spriteObj.loadImage(charSet.CharGraphic);
spriteObj.setAnimations(charSet.CharSize.Y, charSet.CharSize.X);
spriteObj.setCharSet(charSet);
spriteObj.setVisible(true);
//spriteObj.setListener(this);
for (int i=0; i<m_Map.getEvents().Count; ++i)
{
CEvent cevent = (CEvent) m_Map.getEvents()[i];
if (cevent.getType() == (int)CEvent.EventType.PLAYER_START)
{
int nSpaceY = 32; int nDifference = spriteObj.getHeight() - nSpaceY;
spriteObj.setLocation(new Point(cevent.getGridLoc().X * 32,
(cevent.getGridLoc().Y * 32) - nDifference));
}
}
CLayer layer = (CLayer)m_Map.getMapLayers()[1];
layer.addObject(spriteObj, 2);
}
public void addCharacterSet(CCharacterSet charSet, Point ptGrid, int nDir)
{
GameDialog gd = (GameDialog)this.Parent;
MainForm mf = (MainForm)gd.Owner;
CSpriteObject spriteObj = new CSpriteObject();
spriteObj.loadImage(charSet.CharGraphic);
spriteObj.setAnimations(charSet.CharSize.Y, charSet.CharSize.X);
spriteObj.setCharSet(charSet);
spriteObj.setVisible(true);
spriteObj.setLocation(new Point(ptGrid.X * 32, ptGrid.Y * 32));
spriteObj.setDirection(nDir);
spriteObj.setCurrentAnim(nDir);
//spriteObj.setListener(this);
CLayer layer = (CLayer)m_Map.getMapLayers()[1];
layer.addObject(spriteObj, 2);
}
public void Closed()
{
m_SoundPlayer.Stop();
m_SoundPlayer.Close();
}
private void GameMapPanel_Load(object sender, EventArgs e)
{
//this.Height = 0;
//this.Width = 0;
GameDialog holder = (GameDialog)this.Parent;
holder.updateScrollBars();
m_Timer.Start();
}
private void GameMapPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
//create back buffer
Bitmap backBuffer = new Bitmap(Width, Height);
Graphics backG = Graphics.FromImage(backBuffer);
if (m_Map != null)
{
ArrayList mapLayers = m_Map.getMapLayers();
for (int i = 0; i < mapLayers.Count; ++i)
{
CLayer layer = (CLayer)mapLayers[i];
layer.DrawLayer(backG);
}
}
g.DrawImage(backBuffer, new Point(0, 0));
}
private void GameMapPanel_MouseEnter(object sender, EventArgs e)
{
this.Focus();
}
private void GameMapPanel_KeyDown(object sender, KeyEventArgs e)
{
//get CharSet
GameDialog gd = (GameDialog)this.Parent;
MainForm mf = (MainForm)gd.Owner;
CSpriteObject player = new CSpriteObject();
CCharacterSet dbCharSet = (CCharacterSet)mf.m_Database.m_Characters[0];
ArrayList list = m_Map.getMapLayers();
CLayer layer = (CLayer)list[1];
for (int i = 0; i < layer.getObjects().Count; i++)
{
CMapObject mapObj = layer.getObject(i);
if (mapObj.getType() == (int)CMapObject.MapObjectType.SPRITE)
{
CSpriteObject sprite = (CSpriteObject)mapObj;
if (sprite.getCharSet().Name.Equals(dbCharSet.Name))
{
player = sprite;
}
}
}
if (e.KeyCode == Keys.Down)
{
player.setDirection((int)CSpriteObject.Direction.DOWN);
player.startTimer();
}
if (e.KeyCode == Keys.Up)
{
player.setDirection((int)CSpriteObject.Direction.UP);
player.startTimer();
}
if (e.KeyCode == Keys.Left)
{
player.setDirection((int)CSpriteObject.Direction.LEFT);
player.startTimer();
}
if (e.KeyCode == Keys.Right)
{
player.setDirection((int)CSpriteObject.Direction.RIGHT);
player.startTimer();
}
}
private void GameMapPanel_KeyUp(object sender, KeyEventArgs e)
{
//get CharSet
GameDialog gd = (GameDialog)this.Parent;
MainForm mf = (MainForm)gd.Owner;
CSpriteObject player = new CSpriteObject();
CCharacterSet dbCharSet = (CCharacterSet)mf.m_Database.m_Characters[0];
ArrayList list = m_Map.getMapLayers();
CLayer layer = (CLayer)list[1];
for (int i = 0; i < layer.getObjects().Count; i++)
{
CMapObject mapObj = layer.getObject(i);
if (mapObj.getType() == (int)CMapObject.MapObjectType.SPRITE)
{
CSpriteObject sprite = (CSpriteObject)mapObj;
if (sprite.getCharSet().Name.Equals(dbCharSet.Name))
{
player = sprite;
}
}
}
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
{
player.stopTimer();
}
}
private void GameMapPanel_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
case Keys.Left:
case Keys.Right:
e.IsInputKey = true;
break;
}
}
private void m_BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
MainForm mf = (MainForm)CUtil.findForm("RPG Inventor");
if (this.getMap().getSoundDir() != null && this.getMap().getSoundDir() != ""
&& this.getMap().getSoundName() != null && this.getMap().getSoundName() != "")
{
String szPath = ".\\Projects\\" + mf.m_Database.m_Name + "\\Audio\\" +
this.getMap().getSoundDir() + "\\" + this.getMap().getSoundName();
string szSoundPlayerPath = m_szLastMedia;
if (!szSoundPlayerPath.Equals(szPath))
{
try
{
m_SoundPlayer.Stop();
m_SoundPlayer.Open(new Uri(szPath, UriKind.Relative));
m_SoundPlayer.Play();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//m_SoundPlayer.Stop();
//m_SoundPlayer.SoundLocation = szPath;
//m_SoundPlayer.PlayLooping();
}
}
}
}
}
In WinForms, controls created in one thread cannot be accessed from any other thread. So you need to run the code on the main thread using Invoke.
Try this:
if (!szSoundPlayerPath.Equals(szPath))
{
try
{
this.Invoke((MethodInvoker)delegate
{
m_SoundPlayer.Stop();
m_SoundPlayer.Open(new Uri(szPath, UriKind.Relative));
m_SoundPlayer.Play();
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I'm not 100% sure if the above three lines are what's causing the exception, but you just need to wrap whatever lines of code are causing the error in the Invoke statement.
When using a WPF element inside a different Thread than the UI thread you need to invoke using the Dispatcher.Invoke if you want a synchronous call, but if you can it is prefered to use Dispatcher.BeginInvoke.
Change your code with:
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
m_SoundPlayer.Stop();
m_SoundPlayer.Open(new Uri(szPath, UriKind.Relative));
m_SoundPlayer.Play();
}));
Thank you so much for your input, this is what I have come up with as a result and it works
if (InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
m_SoundPlayer.Stop();
m_SoundPlayer.Open(new Uri(szPath, UriKind.Relative));
m_SoundPlayer.Play();
}));
}
else
{
m_SoundPlayer.Stop();
m_SoundPlayer.Open(new Uri(szPath, UriKind.Relative));
m_SoundPlayer.Play();
}
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?