I'm working on an app where I need to draw lines on Canvas, these lines need to be in an array so I can still add changes to it (Resizeable and color). I'm trying to build a paint-like function.
This is my code
private void w_Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
//lineStartPoint = e.GetPosition(w_Canvas);
//Thread.Sleep(2);
Line[] l = new Line[999999];
for (int d = 0; d < 999999; d++)
{
Point lineStartPoint = e.GetPosition(w_Canvas);
l[d].X1 = lineStartPoint.X;
l[d].Y1 = lineStartPoint.Y;
Thread.Sleep(1);
Point lineEnd = e.GetPosition(w_Canvas);
l[d].X2 = lineEnd.X;
l[d].Y2 = lineEnd.Y;
l[d].Stroke = brush;
l[d].StrokeThickness = 3;
//lineStartPoint = lineEnd;
//probeert ee nproperty the accessen warvan de property 0 is
}
DrawLines(l);
}
}
}
private void DrawLines(Line[] l)
{
foreach (Line line in l)
{
w_Canvas.Children.Add(line);
}
}
private void w_Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
isDrawing = false;
}
Currently I'm getting a 'System.NullReferenceException' where an object reference isn't installed on a copy of an object.
You try to access to l[d] but it's not initialized, add
l[d] = new Line();
In your for loop.
You have to create an instance of each line in the array.
Line[] l = new Line[999999];
for (int d = 0; d < 999999; d++)
{
l[d] = new Line();
}
Thanks to some help i got it
private void w_Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Point lineEnd = e.GetPosition(w_Canvas);
Line l = new Line();
LINE.Add(new Tuple<double, double, double, double>(lineStartPoint.X, lineStartPoint.Y, lineEnd.X, lineEnd.Y));
l.X1 = LINE[LINE.Count - 1].Item1;
l.Y1 = LINE[LINE.Count - 1].Item2;
l.X2 = LINE[LINE.Count - 1].Item3;
l.Y2 = LINE[LINE.Count - 1].Item4;
l.Stroke = brush;
l.StrokeThickness = 3;
w_Canvas.Children.Add(l);
lineStartPoint = lineEnd;
}
}
}
private void w_Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
isDrawing = false;
}
}
}
Thank you all for your help also!
Related
I want to have multiple cards with text and images or just red or blue color filled up. this is how the form should look like. So I am thinking about creating multiple picture boxes or labels But the problem is that the picture boxes are overlapping.
private void button1_Click(object sender, EventArgs e)
{
Createlabels();
}
private void Createlabels()
{
var n = 5;
PictureBox[] p = new PictureBox[n];
for (int i = 0; i < n; i++)
{
p[i] = new PictureBox();
p[i].Image = Image.FromFile(#"C:\Users\sania\Desktop\c sharp project\red1.Png");
p[i].SizeMode = PictureBoxSizeMode.Zoom;
p[i].Left = i * 100;
this.Controls.Add(p[i]);
}
}
private void button2_Click(object sender, EventArgs e)
{
Createlabels2();
}
private void Createlabels2()
{
var n = 10;
PictureBox[] q = new PictureBox[n];
for (int j = 0; j < n; j++)
{
q[j] = new PictureBox();
q[j].Image = Image.FromFile(#"C:\Users\sania\Desktop\c sharp project\blue.Png");
q[j].SizeMode = PictureBoxSizeMode.Zoom;
q[j].Left = j * 100;
this.Controls.Add(q[j]);
}
}
}
This is the code I did so far my output but it should look like this one
private void button1_Click(object sender, EventArgs e)
{
var n = 12;
Button[] p = new Button[n];
for (int i = 0; i < n; i++)
{
p[i] = new Button();
p[i].Image = Image.FromFile(#"C:\Users\sania\Desktop\c sharp project\red1.Png");
p[i].Text = i + " Reserved";
p[i].Left = i * 100;
this.Controls.Add(p[i])
}
}
private void button2_Click(object sender, EventArgs e)
{
Createlabels2();
}
private void Createlabels2()
{
var n = 12;
Button[] q = new Button[n];
for (int j = 0; j < n; j++)
{
q[j] = new Button();
q[j].Image = Image.FromFile(#"C:\Users\sania\Desktop\c sharp project\blue.Png");
//"ImagePanel" is a TableLayoutPanel
q[j].Text = j + 10 + " Booked";
q[j].Top = j * 100;
this.Controls.Add(q[j]);
}
}
}
I am currently working on a topdown game made in windows forms. In the game, your character rotates after your mouse and you can shoot a shot from your character in the direction of your mouse. To create multiple areas in the game, I chose to use groupboxes as separate areas in the game that you can switch between using buttons but I've run in to a problem. I can no longer rotate or move my character or even shoot within the groupboxes.
I've tried setting breakpoints and discovered that the keyup, keydown and mousemove methods are not being called but I don't know why. For some reason I get an error when i release space in the btnSave_Click method which i marked in the code.
static Image originalImage;
bool pRight, pLeft, pUp, pDown;
string[] Saves;
Save[] RSaves = new Save[4];
Save yoursave;
Save temp;
int slot;
NewGame newgame;
SavedGames savedgames;
string savedata, name = "";
int lvl = 1;
double exp = 0, money = 0;
int pSpeed = 5;
double deltaY, deltaX;
float interval = 7;
Point start;
Point nextStart;
Point cursor;
float radian;
const double Rad2Grad = (180 / Math.PI);
public MainGame()
{
InitializeComponent();
pbPlayer.BringToFront();
gbxTown.AllowDrop = true;
gbxQ1.AllowDrop = true;
pbShot.Location = pbPlayer.Location;
// newgame = new NewGame();
// savedgames = new SavedGames();
originalImage = pbPlayer.Image;
}
public void setSaves(string savedata, int slot)
{
Saves = savedata.Split('#');
string a1 = Saves[0];
string a2 = Saves[1];
string a3 = Saves[2];
string a4 = Saves[3];
RSaves[0] = temp.StringToSaves(temp, a1);
RSaves[1] = temp.StringToSaves(temp, a2);
RSaves[2] = temp.StringToSaves(temp, a3);
RSaves[3] = temp.StringToSaves(temp, a4);
yoursave = RSaves[slot - 1];
name = yoursave.getName();
this.slot = slot;
Controls.Add(pbPlayer);
Controls.Add(pbShot);
}
private void MainGame_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
pRight = false;
pLeft = true;
}
else if (e.KeyData == Keys.D)
{
pRight = true;
pLeft = false;
}
else if (e.KeyData == Keys.S)
{
pUp = true;
pDown = false;
}
else if (e.KeyData == Keys.W)
{
pUp = false;
pDown = true;
}
if (e.KeyData == Keys.Space)
{
start = pbPlayer.Location;
cursor = Cursor.Position;
nextStart = start;
deltaY = cursor.Y - start.Y;
deltaX = cursor.X - start.X;
double test = Angle(start, cursor);
radian = (float)(Angle(start, cursor) - 175);
timer2.Enabled = true;
}
}
private void MainGame_KeyUp_1(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
pLeft = false;
}
else if (e.KeyData == Keys.D)
{
pRight = false;
}
else if (e.KeyData == Keys.S)
{
pUp = false;
}
else if (e.KeyData == Keys.W)
{
pDown = false;
}
if (e.KeyData == Keys.Space)
{
timer2.Stop();
pbShot.Location = start;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
MovePlayer();
//checkCollision();
}
private void btnNextArea_Click(object sender, EventArgs e)
{
pbPlayer.Parent = gbxQ1;
pbShot.Parent = gbxQ1;
gbxQ1.Location = new Point(0, 0);
gbxTown.Location = new Point(605, 0);
pbPlayer.Location = new Point(100, 200);
pbShot.Location = pbPlayer.Location;
}
private void btnSave_Click(object sender, EventArgs e)
{
newgame = new NewGame();
savedgames = new SavedGames();
RSaves[slot - 1] = new Save(name, money, lvl, exp);
for (int i = 0; i < 4; i++) //When the Spacebar is released, a System.IndexOutOfRangeException error happens for i.
{
Saves[i] = RSaves[i].SavesToString();
}
savedata = Saves[0] + Saves[1] + Saves[2] + Saves[3];
System.IO.File.WriteAllLines(#"saves.txt", Saves);
newgame.setSaves(savedata);
savedgames.setSaves(savedata);
}
private void btnBack_Click(object sender, EventArgs e)
{
pbPlayer.Parent = gbxTown;
pbShot.Parent = gbxTown;
gbxTown.Location = new Point(0, 0);
gbxQ1.Location = new Point(605, 0);
pbPlayer.Location = new Point(100, 200);
pbShot.Location = pbPlayer.Location;
}
private void MainGame_MouseMove_1(object sender, MouseEventArgs e)
{
var y2 = e.Y;
var y1 = (this.pbPlayer.Location.Y + (this.pbPlayer.Height / 2));
var x2 = e.X;
var x1 = (this.pbPlayer.Location.X + (this.pbPlayer.Width / 2));
var angle = (float)Math.Atan2((y1 - y2), (x1 - x2));
pbPlayer.Image = RotateImage(originalImage, (angle * 57));
}
private double Angle(Point start, Point end)
{
return (float)Math.Atan2(end.Y - start.Y, end.X - start.X) * 57;
}
private void timer2_Tick_1(object sender, EventArgs e)
{
nextStart.X -= Convert.ToInt16(interval * ((float)Math.Cos(radian / Rad2Grad)));
nextStart.Y -= Convert.ToInt16(interval * ((float)Math.Sin(radian / Rad2Grad)));
pbShot.Location = nextStart;
}
public static Image RotateImage(Image img, float rotationAngle)
{
Bitmap bmp = new Bitmap(img.Width, img.Height);
Graphics gfx = Graphics.FromImage(bmp);
gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);
gfx.RotateTransform(rotationAngle);
gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.DrawImage(img, new Point(0, 0));
gfx.Dispose();
return bmp;
}
private void MovePlayer()
{
if (pRight == true && pbPlayer.Left < 900)
{
pbPlayer.Left += pSpeed;
}
else if (pLeft == true && pbPlayer.Left > 0)
{
pbPlayer.Left -= pSpeed;
}
else if (pUp == true && pbPlayer.Top < 600)
{
pbPlayer.Top += pSpeed;
}
else if (pDown == true && pbPlayer.Top > 0)
{
pbPlayer.Top -= pSpeed;
}
}
The expected outcome is for the movement, aiming and firing to work as intended within the groupboxes but currently they do not execute in the code while in the groupboxes. It works fine in the form but not in the groupboxes. I would appriciate any help.
I am new in C# and trying to create zedgraph of lessor sensor.
First I create a global variable and write code for graph. My graph is working but after reached to the point of 100 of x axis it will overlap to old line. z1.GraphPane.CurveList.Clear(); command is not working. I tried listPointsOne.clear(); command also but that clear the line and doesn't show anything on graph. Please help me out with this.
My code is below :
string DatafromCOM;
double[] x = new double[100];
double[] y = new double[100];
int i;
PointPairList listPointsOne = new PointPairList();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
while (serialPort1.BytesToRead > 0)
{
DatafromCOM = serialPort1.ReadLine();
double iData;
var ok = double.TryParse(txtKQ.Text, out iData);
if (DatafromCOM.Trim() != "" && ok)
{
i= (i + 1) % 100;
x[i] = i;
y[i] = iData;
listPointsOne.Add(i,iData);
}
}
}
catch { }
}
private void timer1_Tick(object sender, EventArgs e)
{
z1.GraphPane.CurveList.Clear();
z1.GraphPane.AddCurve(null, listPointsOne, Color.Red, SymbolType.None);
z1.AxisChange();
z1.Invalidate();
}
You should clear the curvlist
string DatafromCOM;
double[] x = new double[100];
double[] y = new double[100];
int i;
PointPairList listPointsOne = new PointPairList();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
while (serialPort1.BytesToRead > 0)
{
DatafromCOM = serialPort1.ReadLine();
double iData;
var ok = double.TryParse(txtKQ.Text, out iData);
if (DatafromCOM.Trim() != "" && ok)
{
i= (i + 1) % 100;
x[i] = i;
y[i] = iData;
listPointsOne.Add(i,iData);
}
z1.GraphPane.CurveList.Clear(); // Change here
}
}
catch { }
}
private void timer1_Tick(object sender, EventArgs e)
{
z1.GraphPane.AddCurve(null, listPointsOne, Color.Red, SymbolType.None);
z1.AxisChange();
z1.Invalidate();
}
I encounter a strange problem. I've got a canvas and drawed a complexe structure:
an Image inside a Grid inside a Border.
My Image is the one which is active for moving.
It works well the first time i drag my structure but the second time nothing works at all no exception but nothing works. It seems to me to be a problem of mouse capture but i can't catch what's about.
Here is my event code :
bool captured = false;
double x_shape, x_canvas, y_shape, y_canvas;
double x_shape_Origine, y_shape_Origine;
Border source = null;
int CountZ = 10;
private void shape_MoveButtonDown(object sender, MouseButtonEventArgs e)
{
/// AWFULLY SOURCE WAS null. I don't understand Why it was working the
/// first time
Mouse.Capture(source);
captured = true;
Image myImage = (Image)sender;
Grid outerGrid = (Grid)myImage.Parent;
source = (Border)outerGrid.Parent;
Canvas.SetZIndex(source, CountZ++);
x_shape = Canvas.GetLeft(source);
y_shape = Canvas.GetTop(source);
x_canvas = e.GetPosition(myCanvas).X;
y_canvas = e.GetPosition(myCanvas).Y;
}
private void shape_MoveMoving(object sender, MouseEventArgs e)
{
if (captured)
{
double x = e.GetPosition(myCanvas).X;
double y = e.GetPosition(myCanvas).Y;
x_shape += x - x_canvas;
Canvas.SetLeft(source, x_shape);
x_canvas = x;
y_shape += y - y_canvas;
Canvas.SetTop(source, y_shape);
y_canvas = y;
}
}
private void shape_MoveButtonUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
captured = false;
}
private void shape_MouseEnter(object sender, MouseEventArgs e)
{
if (!captured)
{
Border inner = (Border)sender;
Grid parentInner = (Grid)inner.Parent;
parentInner.Children[0].Visibility = Visibility.Visible;
parentInner.Children[2].Visibility = Visibility.Visible;
parentInner.Children[5].Visibility = Visibility.Visible;
parentInner.Children[6].Visibility = Visibility.Visible;
parentInner.Children[8].Visibility = Visibility.Visible;
parentInner.Background = new SolidColorBrush(Colors.Red);
}
}
private void shape_MouseLeave(object sender, MouseEventArgs e)
{
if (!captured)
{
Grid outer = (Grid)sender;
outer.Children[0].Visibility = Visibility.Hidden;
outer.Children[2].Visibility = Visibility.Hidden;
outer.Children[5].Visibility = Visibility.Hidden;
outer.Children[6].Visibility = Visibility.Hidden;
outer.Children[8].Visibility = Visibility.Hidden;
outer.Background = null;
}
}
Hope it will make sense for you
I had a complete sample for D&D with WPF and Silverlight. Here full code, hope it helps.
class MyWnd : Window
{
public MyWnd()
{
var c = new Canvas();
c.Background = new SolidColorBrush(Colors.White);
var rect = new Rectangle { Fill = new SolidColorBrush(Colors.Red), Width = 20, Height = 20 };
c.Children.Add(rect);
this.Content = c;
Canvas.SetLeft(rect, 0);
Canvas.SetTop(rect, 0);
rect.MouseLeftButtonDown+=Handle_MouseDown;
rect.MouseLeftButtonUp+=Handle_MouseUp;
rect.MouseMove+=Handle_MouseMove;
}
bool isMouseCaptured;
double mouseVerticalPosition;
double mouseHorizontalPosition;
public void Handle_MouseDown(object sender, MouseEventArgs args)
{
var item = sender as FrameworkElement;
mouseVerticalPosition = args.GetPosition(null).Y;
mouseHorizontalPosition = args.GetPosition(null).X;
isMouseCaptured = true;
item.CaptureMouse();
}
public void Handle_MouseMove(object sender, MouseEventArgs args)
{
var item = sender as FrameworkElement;
if (isMouseCaptured)
{
// Calculate the current position of the object.
double deltaV = args.GetPosition(null).Y - mouseVerticalPosition;
double deltaH = args.GetPosition(null).X - mouseHorizontalPosition;
double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);
// Set new position of object.
item.SetValue(Canvas.TopProperty, newTop);
item.SetValue(Canvas.LeftProperty, newLeft);
// Update position global variables.
mouseVerticalPosition = args.GetPosition(null).Y;
mouseHorizontalPosition = args.GetPosition(null).X;
}
}
public void Handle_MouseUp(object sender, MouseEventArgs args)
{
var item = sender as FrameworkElement;
isMouseCaptured = false;
item.ReleaseMouseCapture();
mouseVerticalPosition = -1;
mouseHorizontalPosition = -1;
}
}
void Main()
{
var wnd = new MyWnd();
wnd.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
PictureBox dynamicPicture1 = new PictureBox();
dynamicPicture1.Tag = i;
dynamicPicture1.Location = new Point(x, y);
dynamicPicture1.Name = "pictureBox" + i;
dynamicPicture1.Size = new System.Drawing.Size(30, 27);
dynamicPicture1.ImageLocation =
"C:\\Users\\Newfolder\\Downloads\\x`enter code here`ryrvc.jpg";
panel1.Controls.Add(dynamicPicture1);
}
Try this updated code.
private void button1_Click(object sender, EventArgs e)
{
int s = 4;
int x = 0;
int y = 0;
for (int i = 0; i < s; i++)
{
if (i == 0)
{
x = 38;
y = 60;
}
else
{
y += 50;
}
PictureBox dynamicPicture1 = new PictureBox();
dynamicPicture1.Tag = i;
dynamicPicture1.Location = new Point(x, y);
dynamicPicture1.Name = "pictureBox" + i;
dynamicPicture1.Size = new System.Drawing.Size(30, 27);
dynamicPicture1.ImageLocation = #"C:\Users\nxa00960\Downloads\abc.jpg";
panel1.Controls.Add(dynamicPicture1);
dynamicPicture1.Click += dynamicPicture1_Click;
}
}
void dynamicPicture1_Click(object sender, EventArgs e)
{
var pictureBox = sender as PictureBox;
switch (pictureBox.Name)
{
case "pictureBox0":
//do something
break;
case "pictureBox1":
//do something
break;
case "pictureBox2":
//do something
break;
case "pictureBox3":
//do something
break;
default:
break;
}
}
You should put the Method name of your event handler:
dynamicPicture1.Click += dynamicPicture1_Click; //note the name here
And define the event handler somewhere:
void dynamicPicture1_Click(object sender, EventArgs e) {
throw new NotImplementedException(); //default not implemented
}
The name of the event handler must match each other...