I am writing some code in C# (Winforms .network). I get the error that pos does not exist in the current context. I understand the error, but I don't know how I can fix this. The error is in this part of the code:
if (j == x && i + pos == y)
{
label.BackColor = Color.Red;
}
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.Timers;
namespace TetrisBlok
{
public partial class Form1 : Form
{
private Label label;
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
}
public void Form1_Load(object sender, EventArgs e)
{
int[,] matrix = {
{0, 1, 0},
{0, 1, 0},
{0, 1, 1}};
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 20; j++)
{
label = new Label();
label.AutoSize = false;
label.Name = "label" + j.ToString() + i.ToString();
label.TabIndex = 0;
label.Text = "[" + j.ToString() + "]" + "[" + i.ToString() + "]";
label.Visible = true;
this.Controls.Add(label);
label.Location = new Point(Size.Width / 2 - (5 - i) * 50, Size.Height / 2 - (11 - j) * 30);
label.Size = new Size(50, 30);
label.BackColor = Color.White;
if (i % 2 == 0)
{
label.BackColor = Color.Blue;
}
int w = matrix.GetLength(0);
int h = matrix.GetLength(1);
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
if (matrix[x, y].Equals(1))
{
if (j == x && i + pos == y)
{
label.BackColor = Color.Red;
}
}
}
}
}
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int pos = 0;
if (e.KeyCode == Keys.Right)
{
pos = 1;
}
}
}
}
I get the error because I make int pos in the Form1_KeyDown. What must I change so I can use the int pos in the Form1_Load and the Form_KeyDown?
I want that whenever I press the right arrow key, int pos will increase by 1. Then I want to use that value in the Form1_Load so I can move something.
Related
I have a 2d array of LEDButton : Button.
I want to find out the index [x,y] of each buttons the user clicks.
I am new to Windows Forms and not used to working outside of a console so these GUI objects are very unfamiliar to me.
private void Form1_Load(object sender, EventArgs e)
{
LEDButton[,] leds = new LEDButton[11, 11];
for (int x = 0; x < leds.GetUpperBound(0); x++)
{
listBox1.Items.Add("x = " + x);
for (int y = 0; y < leds.GetUpperBound(1); y++)
{
leds[x, y] = new LEDButton()
{
Name = String.Format("Button{0}{1}", x, y),
TabIndex = 40 * x + y,
Location = new Point(40 * y + 50, 40 * x + 50)
};
leds[x, y].pointx = x;
leds[x, y].pointy = y;
}
}
// add buttons to controls
for (int x = 0; x < leds.GetUpperBound(0); x++)
{
for (int y = 0; y < leds.GetUpperBound(1); y++)
{
Controls.Add(leds[x, y]);
leds[x, y].Click += Form1_Click;
}
}
public class LEDButton : Button
{
public const int LEDWidth = 20;
public const int LEDHeight = 20;
public int pointx = 0;
public int pointy = 0;
public LEDButton()
{
BackColor = Color.FromArgb(0, 64, 0);
ForeColor = Color.Black;
FlatStyle = FlatStyle.Flat;
Size = new Size(LEDWidth, LEDHeight);
UseVisualStyleBackColor = false;
this.Click += LEDButton_Click; //throws error
}
}
I think I found my answer with the help of Lars.
Code should be
private void Form1_Click(object? sender, EventArgs e)
{
LEDButton btn = sender as LEDButton;
listBox2.Items.Add(btn.Name);
}
I set the points and when the points of the same color form a square, I draw a polygon. But when a new square is formed, the old one disappears.
can you tell me how to make sure that when drawing a new polygon, the old one does not disappear?
in the checkpoint() function, I check whether there is a square of points of the same color and return e coordinates for drawing.
public partial class Form1 : Form
{
private Class1 Class1 = new Class1();
private CellState currentPlayer = CellState.Red;
public const int SIZE = 11;
public const int Icon_Size = 30;
public Form1()
{
InitializeComponent();
}
//ставит точки
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
var p = new Point((int)Math.Round(1f * e.X / Icon_Size), (int)Math.Round(1f * e.Y / Icon_Size));
if (Class1[p] == CellState.Empty)
{
Class1.SetPoint(p, currentPlayer);
currentPlayer = Class1.Inverse(currentPlayer);
Invalidate();
}
}
//рисуем
private void OnPaint(object sender, PaintEventArgs e)
{
e.Graphics.ScaleTransform(Icon_Size, Icon_Size);
//рисуем сеточку
using (var pen = new Pen(Color.Gainsboro, 0.1f))
{
for (int x = 1; x < SIZE; x++)
e.Graphics.DrawLine(pen, x, 1, x, SIZE - 1);
for (int y = 1; y < SIZE; y++)
e.Graphics.DrawLine(pen, 1, y, SIZE - 1, y);
}
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//рисуем точки
using (var brush = new SolidBrush(Color.White))
for (int x = 1; x < Form1.SIZE; x++)
for (int y = 1; y < Form1.SIZE; y++)
{
var p = new Point(x, y);
var cell = Class1[p];
if (cell != CellState.Empty)
{
brush.Color = StateToColor(cell);
e.Graphics.FillEllipse(brush, x - 0.2f, y - 0.2f, 0.4f, 0.4f);
}
}
using (var PenP = new Pen(Color.Black, 0.1f))
using (var brush = new SolidBrush(Color.White))
{
Class1.CheckPoint();
int i = Class1.CheckPoint()[0];
int j = Class1.CheckPoint()[1];
int cp = Class1.CheckPoint()[2];
if (cp == 1)
{
PenP.Color = Color.Red;
brush.Color = Color.IndianRed;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
if (cp == 2)
{
PenP.Color = Color.Blue;
brush.Color = Color.RoyalBlue;
Point[] a = { new Point(i, j), new Point(i + 1, j), new Point(i + 1, j + 1), new Point(i, j + 1) };
e.Graphics.FillPolygon(brush, a);
e.Graphics.DrawPolygon(PenP, a);
}
}
}
//условие смены цвета под ход игрока
Color StateToColor(CellState state, byte alpha = 255)
{
var res = state == CellState.Blue ? Color.Blue : Color.Red;
return Color.FromArgb(alpha, res);
}
}
I received System.IndexOutOfRangeException in the part of the SearchForTheNextDotsTopRight() method
if ((pointsArray[i].X == j) &&
((pointsArray[i].Y) <= p.Y))
I just simply don't know why the array is not functioning in this situation. Looking forward for help, thanks you a lot!
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
namespace Draw_Test
{
public partial class Form1 : Form
{
public static int sizeOfArray = 20;
int TopBorderY = 100;
int LeftBorderX = 100;
int BottomBorderY = 800;
int RightBorderX = 800;
Point Base = new Point(0, 0);
Point[] pointsArray = new Point[sizeOfArray];
public Form1()
{
InitializeComponent();
}
private void PointsArray(PaintEventArgs e)
{
var rand = new Random();
for (int i = 0; i < sizeOfArray; i++)
{
pointsArray[i].X = rand.Next(100, 800);
pointsArray[i].Y = rand.Next(100, 800);
CreateDots(pointsArray[i], e);
}
Point Nearest = SearchForTheFirstDots(pointsArray);
CreateLines(Base, Nearest, e);
Point Next = SearchForTheNextDotsTopRight(Nearest, pointsArray);
CreateLines(Nearest, Next, e);
}
private Point SearchForTheNextDotsTopRight(Point p, Point[] pointsArray)
{
Point PointNext = p;
for (int j = p.X; j <= RightBorderX; j++)
{
for (int i = 0; i <= sizeOfArray; i++)
{
if ((pointsArray[i].X == j) &&
((pointsArray[i].Y) <= p.Y))
{
PointNext = pointsArray[i];
goto endofLoop:
}
}
}
endofLoop:
return PointNext;
}
private double CalculateDistance(Point p1, Point p2)
{
double distance = Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2);
return distance;
}
private Point SearchForTheFirstDots(Point[] pointsArray)
{
Point Nearest = pointsArray[0];
for (int i = 0; i < sizeOfArray; i++)
{
if (CalculateDistance(Base, pointsArray[i]) <
CalculateDistance(Base, Nearest))
{
Nearest = pointsArray[i];
}
}
//pointList.Add(Nearest);
return Nearest;
}
private void CreateDots(Point p, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Blue, 3);
int width = 3;
int height = 3;
int pointXform = p.X - width / 2;
int pointYform = p.Y - height / 2;
Rectangle r = new Rectangle(pointXform, pointYform, width, height);
g.DrawEllipse(pen, r);
}
private void CreateLines(Point p1, Point p2, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Blue, 3);
g.DrawLine(pen, p1, p2);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Point p1 = new Point(25, 25);
Point p2 = new Point(100, 150);
PointsArray(e);
}
}
}
replace:
for (int i = 0; i <= sizeOfArray; i++) //<---------------
{
if ((pointsArray[i].X == j) &&
((pointsArray[i].Y) <= p.Y))
{
PointNext = pointsArray[i];
goto endofLoop:
}
}
by
for (int i = 0; i < sizeOfArray; i++) //<---------------
{
if ((pointsArray[i].X == j) &&
((pointsArray[i].Y) <= p.Y))
{
PointNext = pointsArray[i];
goto endofLoop:
}
}
i have some issues with radio buttons in c#.
i have this little class called histogram and a function inside it that draws the histogram of any picture. i want to assign the function to a radio button so that when its clicked the histogram would be drawn. button 8 would draw all channels together, button 9 would draw only the red channel, button 10 - green, button 11 - blue. here is a picture of my form design and also my histogram class code.
http://i.imgur.com/x9Hd0TL.png the code that needs to be assigned to radio buttons is at the end of drawHistogram function. i marked them with cases.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication4
{
public class histogram
{
public int[] hR;
public int[] hG;
public int[] hB;
public int[] hI;
public histogram()
{
hR = new int[257];
hG = new int[257];
hB = new int[257];
hI = new int[257];
}
~histogram()
{
hR = null;
hG = null;
hB = null;
hI = null;
}
public void eraseHistogram()
{
for (int i = 0; i <257; i++)
{
hR[i] = 0;
hG[i] = 0;
hB[i] = 0;
hI[i] = 0;
}
}
public void readHistogram(rgbiPixels[,] imgArray)
{
eraseHistogram();
int W = imgArray.GetLength(0);
int H = imgArray.GetLength(1);
for (int x = 0; x < W; x++)
{
for (int y = 0; y < H; y++)
{
hR[imgArray[x, y].R]++;
hR[256] = Math.Max(hR[imgArray[x, y].R], hR[256]);
hI[imgArray[x, y].I]++;
hI[256] = Math.Max(hI[imgArray[x, y].I], hI[256]);
hG[imgArray[x, y].G]++;
hG[256] = Math.Max(hG[imgArray[x, y].G], hR[256]);
hB[imgArray[x, y].B]++;
hB[256] = Math.Max(hB[imgArray[x, y].B], hR[256]);
}
}
}
public Bitmap drawHistogram()
{
int r;
int g;
int b;
int i;
int normalizedMax = Math.Max(hI[256], Math.Max(hR[256], Math.Max(hG[256], hB[256])));
var bmp = new Bitmap(256, 100, PixelFormat.Format24bppRgb);
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 100; y++)
{
int normalizedValue = 100 * hI[x] / normalizedMax;
if (y < normalizedValue) { i = 255; }
else { i = 0; }
normalizedValue = 100 * hR[x] / normalizedMax;
if (y < normalizedValue) { r = 255; }
else { r = 0; }
normalizedValue = 100 * hG[x] / normalizedMax;
if (y < normalizedValue) { g = 255; }
else { g = 0; }
normalizedValue = 100 * hB[x] / normalizedMax;
if (y < normalizedValue) { b = 255; }
else { b = 0; }
//case 1, intensity
if (r == 0 && g == 0 && b == 0)
{ bmp.SetPixel(x, 99 - y, Color.FromArgb(i, i, i)); }
else if (i == 255)
{ bmp.SetPixel(x, 99 - y, Color.FromArgb((i + r) / 2, (i + g) / 2, (i + b) / 2)); }
else
{ bmp.SetPixel(x, 99 - y, Color.FromArgb(r, g, b)); }
/*//case 2, red
if (r == 255)
{ bmp.SetPixel(x, 99 - y, Color.FromArgb(255, 0, 0)); }*/
/*//case 3, green
if (g == 255)
{ bmp.SetPixel(x, 99 - y, Color.FromArgb(0, 255, 0)); }*/
/*//case 4, blue
if (b == 255)
{ bmp.SetPixel(x, 99 - y, Color.FromArgb(0, 0, 255)); }*/
}
}
return bmp;
}
}
}
I wrote bresenham algorithm for
0<Angular coefficient<1
I don't know much about graphics in C#,I realized that for drawing pixles I can use the function Fillrectangel with coordinate 1,1
I wanted to write my code then when clicking the mouse on panel and in two positions draw me a line from x0,y0 to xEnd,yEnd
so here is my code which has exception
Null reference exception was unhandled
object reference not set to an instance of the object
this exception is in line e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
I think the problem is that object e is Null and I should new it but how?
How can I correct my code so as to draw Line?
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;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Line l=new Line();
l.LineBres(Cursor.Position.X, Cursor.Position.Y, Cursor.Position.X, Cursor.Position.Y);
}
}
}
public class Line
{
System.Windows.Forms.DrawItemEventArgs e;
Color grad1 = Color.FromArgb(165, 194, 245);
public void LineBres(int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0;
int dy = yEnd = y0;
int p = 2 * dy - dx;
int twoDy = 2 * dy;
int twoDyMinusDx = 2 * (dy - dx);
int x, y;
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
e.Graphics.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
}
}
}
Here is what you need to change:
Add mouse click event for panel and change your Line code a bit - remove System.Windows.Forms.DrawItemEventArgs e; and pass Graphics of panel with panel1.CreateGraphics();. Here is the code:
private int firstX, firstY;//store coordinates of first click
private bool firstClick = true;
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
if (firstClick)
{
firstX = e.X;
firstY = e.Y;
firstClick = false;
}
else
{
Line l = new Line();
l.LineBres(firstX, firstY, e.X, e.Y, panel1.CreateGraphics());
firstClick = true;
}
}
public class Line
{
private Color grad1 = Color.FromArgb(165, 194, 245);
public void LineBres(int x0, int y0, int xEnd, int yEnd, Graphics e)
{
int dx = xEnd - x0;
int dy = yEnd = y0;
int p = 2*dy - dx;
int twoDy = 2*dy;
int twoDyMinusDx = 2*(dy - dx);
int x, y;
if (x0 > xEnd)
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
e.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
while (x < xEnd)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
e.FillRectangle(new SolidBrush(grad1), x, y, 1, 1);
}
}
}